catch.hpp 642 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970
  1. /*
  2. * Catch v2.13.9
  3. * Generated: 2022-04-12 22:37:23.260201
  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 9
  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. using TStorage = typename std::aligned_storage<sizeof(T), std::alignment_of<T>::value>::type;
  6020. ObjectStorage() : data() {}
  6021. ObjectStorage(const ObjectStorage& other)
  6022. {
  6023. new(&data) T(other.stored_object());
  6024. }
  6025. ObjectStorage(ObjectStorage&& other)
  6026. {
  6027. new(&data) T(std::move(other.stored_object()));
  6028. }
  6029. ~ObjectStorage() { destruct_on_exit<T>(); }
  6030. template <typename... Args>
  6031. void construct(Args&&... args)
  6032. {
  6033. new (&data) T(std::forward<Args>(args)...);
  6034. }
  6035. template <bool AllowManualDestruction = !Destruct>
  6036. typename std::enable_if<AllowManualDestruction>::type destruct()
  6037. {
  6038. stored_object().~T();
  6039. }
  6040. private:
  6041. // If this is a constructor benchmark, destruct the underlying object
  6042. template <typename U>
  6043. void destruct_on_exit(typename std::enable_if<Destruct, U>::type* = 0) { destruct<true>(); }
  6044. // Otherwise, don't
  6045. template <typename U>
  6046. void destruct_on_exit(typename std::enable_if<!Destruct, U>::type* = 0) { }
  6047. T& stored_object() {
  6048. return *static_cast<T*>(static_cast<void*>(&data));
  6049. }
  6050. T const& stored_object() const {
  6051. return *static_cast<T*>(static_cast<void*>(&data));
  6052. }
  6053. TStorage data;
  6054. };
  6055. }
  6056. template <typename T>
  6057. using storage_for = Detail::ObjectStorage<T, true>;
  6058. template <typename T>
  6059. using destructable_object = Detail::ObjectStorage<T, false>;
  6060. }
  6061. }
  6062. // end catch_constructor.hpp
  6063. // end catch_benchmarking_all.hpp
  6064. #endif
  6065. #endif // ! CATCH_CONFIG_IMPL_ONLY
  6066. #ifdef CATCH_IMPL
  6067. // start catch_impl.hpp
  6068. #ifdef __clang__
  6069. #pragma clang diagnostic push
  6070. #pragma clang diagnostic ignored "-Wweak-vtables"
  6071. #endif
  6072. // Keep these here for external reporters
  6073. // start catch_test_case_tracker.h
  6074. #include <string>
  6075. #include <vector>
  6076. #include <memory>
  6077. namespace Catch {
  6078. namespace TestCaseTracking {
  6079. struct NameAndLocation {
  6080. std::string name;
  6081. SourceLineInfo location;
  6082. NameAndLocation( std::string const& _name, SourceLineInfo const& _location );
  6083. friend bool operator==(NameAndLocation const& lhs, NameAndLocation const& rhs) {
  6084. return lhs.name == rhs.name
  6085. && lhs.location == rhs.location;
  6086. }
  6087. };
  6088. class ITracker;
  6089. using ITrackerPtr = std::shared_ptr<ITracker>;
  6090. class ITracker {
  6091. NameAndLocation m_nameAndLocation;
  6092. public:
  6093. ITracker(NameAndLocation const& nameAndLoc) :
  6094. m_nameAndLocation(nameAndLoc)
  6095. {}
  6096. // static queries
  6097. NameAndLocation const& nameAndLocation() const {
  6098. return m_nameAndLocation;
  6099. }
  6100. virtual ~ITracker();
  6101. // dynamic queries
  6102. virtual bool isComplete() const = 0; // Successfully completed or failed
  6103. virtual bool isSuccessfullyCompleted() const = 0;
  6104. virtual bool isOpen() const = 0; // Started but not complete
  6105. virtual bool hasChildren() const = 0;
  6106. virtual bool hasStarted() const = 0;
  6107. virtual ITracker& parent() = 0;
  6108. // actions
  6109. virtual void close() = 0; // Successfully complete
  6110. virtual void fail() = 0;
  6111. virtual void markAsNeedingAnotherRun() = 0;
  6112. virtual void addChild( ITrackerPtr const& child ) = 0;
  6113. virtual ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) = 0;
  6114. virtual void openChild() = 0;
  6115. // Debug/ checking
  6116. virtual bool isSectionTracker() const = 0;
  6117. virtual bool isGeneratorTracker() const = 0;
  6118. };
  6119. class TrackerContext {
  6120. enum RunState {
  6121. NotStarted,
  6122. Executing,
  6123. CompletedCycle
  6124. };
  6125. ITrackerPtr m_rootTracker;
  6126. ITracker* m_currentTracker = nullptr;
  6127. RunState m_runState = NotStarted;
  6128. public:
  6129. ITracker& startRun();
  6130. void endRun();
  6131. void startCycle();
  6132. void completeCycle();
  6133. bool completedCycle() const;
  6134. ITracker& currentTracker();
  6135. void setCurrentTracker( ITracker* tracker );
  6136. };
  6137. class TrackerBase : public ITracker {
  6138. protected:
  6139. enum CycleState {
  6140. NotStarted,
  6141. Executing,
  6142. ExecutingChildren,
  6143. NeedsAnotherRun,
  6144. CompletedSuccessfully,
  6145. Failed
  6146. };
  6147. using Children = std::vector<ITrackerPtr>;
  6148. TrackerContext& m_ctx;
  6149. ITracker* m_parent;
  6150. Children m_children;
  6151. CycleState m_runState = NotStarted;
  6152. public:
  6153. TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  6154. bool isComplete() const override;
  6155. bool isSuccessfullyCompleted() const override;
  6156. bool isOpen() const override;
  6157. bool hasChildren() const override;
  6158. bool hasStarted() const override {
  6159. return m_runState != NotStarted;
  6160. }
  6161. void addChild( ITrackerPtr const& child ) override;
  6162. ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) override;
  6163. ITracker& parent() override;
  6164. void openChild() override;
  6165. bool isSectionTracker() const override;
  6166. bool isGeneratorTracker() const override;
  6167. void open();
  6168. void close() override;
  6169. void fail() override;
  6170. void markAsNeedingAnotherRun() override;
  6171. private:
  6172. void moveToParent();
  6173. void moveToThis();
  6174. };
  6175. class SectionTracker : public TrackerBase {
  6176. std::vector<std::string> m_filters;
  6177. std::string m_trimmed_name;
  6178. public:
  6179. SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  6180. bool isSectionTracker() const override;
  6181. bool isComplete() const override;
  6182. static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation );
  6183. void tryOpen();
  6184. void addInitialFilters( std::vector<std::string> const& filters );
  6185. void addNextFilters( std::vector<std::string> const& filters );
  6186. //! Returns filters active in this tracker
  6187. std::vector<std::string> const& getFilters() const;
  6188. //! Returns whitespace-trimmed name of the tracked section
  6189. std::string const& trimmedName() const;
  6190. };
  6191. } // namespace TestCaseTracking
  6192. using TestCaseTracking::ITracker;
  6193. using TestCaseTracking::TrackerContext;
  6194. using TestCaseTracking::SectionTracker;
  6195. } // namespace Catch
  6196. // end catch_test_case_tracker.h
  6197. // start catch_leak_detector.h
  6198. namespace Catch {
  6199. struct LeakDetector {
  6200. LeakDetector();
  6201. ~LeakDetector();
  6202. };
  6203. }
  6204. // end catch_leak_detector.h
  6205. // Cpp files will be included in the single-header file here
  6206. // start catch_stats.cpp
  6207. // Statistical analysis tools
  6208. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  6209. #include <cassert>
  6210. #include <random>
  6211. #if defined(CATCH_CONFIG_USE_ASYNC)
  6212. #include <future>
  6213. #endif
  6214. namespace {
  6215. double erf_inv(double x) {
  6216. // Code accompanying the article "Approximating the erfinv function" in GPU Computing Gems, Volume 2
  6217. double w, p;
  6218. w = -log((1.0 - x) * (1.0 + x));
  6219. if (w < 6.250000) {
  6220. w = w - 3.125000;
  6221. p = -3.6444120640178196996e-21;
  6222. p = -1.685059138182016589e-19 + p * w;
  6223. p = 1.2858480715256400167e-18 + p * w;
  6224. p = 1.115787767802518096e-17 + p * w;
  6225. p = -1.333171662854620906e-16 + p * w;
  6226. p = 2.0972767875968561637e-17 + p * w;
  6227. p = 6.6376381343583238325e-15 + p * w;
  6228. p = -4.0545662729752068639e-14 + p * w;
  6229. p = -8.1519341976054721522e-14 + p * w;
  6230. p = 2.6335093153082322977e-12 + p * w;
  6231. p = -1.2975133253453532498e-11 + p * w;
  6232. p = -5.4154120542946279317e-11 + p * w;
  6233. p = 1.051212273321532285e-09 + p * w;
  6234. p = -4.1126339803469836976e-09 + p * w;
  6235. p = -2.9070369957882005086e-08 + p * w;
  6236. p = 4.2347877827932403518e-07 + p * w;
  6237. p = -1.3654692000834678645e-06 + p * w;
  6238. p = -1.3882523362786468719e-05 + p * w;
  6239. p = 0.0001867342080340571352 + p * w;
  6240. p = -0.00074070253416626697512 + p * w;
  6241. p = -0.0060336708714301490533 + p * w;
  6242. p = 0.24015818242558961693 + p * w;
  6243. p = 1.6536545626831027356 + p * w;
  6244. } else if (w < 16.000000) {
  6245. w = sqrt(w) - 3.250000;
  6246. p = 2.2137376921775787049e-09;
  6247. p = 9.0756561938885390979e-08 + p * w;
  6248. p = -2.7517406297064545428e-07 + p * w;
  6249. p = 1.8239629214389227755e-08 + p * w;
  6250. p = 1.5027403968909827627e-06 + p * w;
  6251. p = -4.013867526981545969e-06 + p * w;
  6252. p = 2.9234449089955446044e-06 + p * w;
  6253. p = 1.2475304481671778723e-05 + p * w;
  6254. p = -4.7318229009055733981e-05 + p * w;
  6255. p = 6.8284851459573175448e-05 + p * w;
  6256. p = 2.4031110387097893999e-05 + p * w;
  6257. p = -0.0003550375203628474796 + p * w;
  6258. p = 0.00095328937973738049703 + p * w;
  6259. p = -0.0016882755560235047313 + p * w;
  6260. p = 0.0024914420961078508066 + p * w;
  6261. p = -0.0037512085075692412107 + p * w;
  6262. p = 0.005370914553590063617 + p * w;
  6263. p = 1.0052589676941592334 + p * w;
  6264. p = 3.0838856104922207635 + p * w;
  6265. } else {
  6266. w = sqrt(w) - 5.000000;
  6267. p = -2.7109920616438573243e-11;
  6268. p = -2.5556418169965252055e-10 + p * w;
  6269. p = 1.5076572693500548083e-09 + p * w;
  6270. p = -3.7894654401267369937e-09 + p * w;
  6271. p = 7.6157012080783393804e-09 + p * w;
  6272. p = -1.4960026627149240478e-08 + p * w;
  6273. p = 2.9147953450901080826e-08 + p * w;
  6274. p = -6.7711997758452339498e-08 + p * w;
  6275. p = 2.2900482228026654717e-07 + p * w;
  6276. p = -9.9298272942317002539e-07 + p * w;
  6277. p = 4.5260625972231537039e-06 + p * w;
  6278. p = -1.9681778105531670567e-05 + p * w;
  6279. p = 7.5995277030017761139e-05 + p * w;
  6280. p = -0.00021503011930044477347 + p * w;
  6281. p = -0.00013871931833623122026 + p * w;
  6282. p = 1.0103004648645343977 + p * w;
  6283. p = 4.8499064014085844221 + p * w;
  6284. }
  6285. return p * x;
  6286. }
  6287. double standard_deviation(std::vector<double>::iterator first, std::vector<double>::iterator last) {
  6288. auto m = Catch::Benchmark::Detail::mean(first, last);
  6289. double variance = std::accumulate(first, last, 0., [m](double a, double b) {
  6290. double diff = b - m;
  6291. return a + diff * diff;
  6292. }) / (last - first);
  6293. return std::sqrt(variance);
  6294. }
  6295. }
  6296. namespace Catch {
  6297. namespace Benchmark {
  6298. namespace Detail {
  6299. double weighted_average_quantile(int k, int q, std::vector<double>::iterator first, std::vector<double>::iterator last) {
  6300. auto count = last - first;
  6301. double idx = (count - 1) * k / static_cast<double>(q);
  6302. int j = static_cast<int>(idx);
  6303. double g = idx - j;
  6304. std::nth_element(first, first + j, last);
  6305. auto xj = first[j];
  6306. if (g == 0) return xj;
  6307. auto xj1 = *std::min_element(first + (j + 1), last);
  6308. return xj + g * (xj1 - xj);
  6309. }
  6310. double erfc_inv(double x) {
  6311. return erf_inv(1.0 - x);
  6312. }
  6313. double normal_quantile(double p) {
  6314. static const double ROOT_TWO = std::sqrt(2.0);
  6315. double result = 0.0;
  6316. assert(p >= 0 && p <= 1);
  6317. if (p < 0 || p > 1) {
  6318. return result;
  6319. }
  6320. result = -erfc_inv(2.0 * p);
  6321. // result *= normal distribution standard deviation (1.0) * sqrt(2)
  6322. result *= /*sd * */ ROOT_TWO;
  6323. // result += normal disttribution mean (0)
  6324. return result;
  6325. }
  6326. double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n) {
  6327. double sb = stddev.point;
  6328. double mn = mean.point / n;
  6329. double mg_min = mn / 2.;
  6330. double sg = (std::min)(mg_min / 4., sb / std::sqrt(n));
  6331. double sg2 = sg * sg;
  6332. double sb2 = sb * sb;
  6333. auto c_max = [n, mn, sb2, sg2](double x) -> double {
  6334. double k = mn - x;
  6335. double d = k * k;
  6336. double nd = n * d;
  6337. double k0 = -n * nd;
  6338. double k1 = sb2 - n * sg2 + nd;
  6339. double det = k1 * k1 - 4 * sg2 * k0;
  6340. return (int)(-2. * k0 / (k1 + std::sqrt(det)));
  6341. };
  6342. auto var_out = [n, sb2, sg2](double c) {
  6343. double nc = n - c;
  6344. return (nc / n) * (sb2 - nc * sg2);
  6345. };
  6346. return (std::min)(var_out(1), var_out((std::min)(c_max(0.), c_max(mg_min)))) / sb2;
  6347. }
  6348. bootstrap_analysis analyse_samples(double confidence_level, int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last) {
  6349. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION
  6350. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  6351. static std::random_device entropy;
  6352. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
  6353. auto n = static_cast<int>(last - first); // seriously, one can't use integral types without hell in C++
  6354. auto mean = &Detail::mean<std::vector<double>::iterator>;
  6355. auto stddev = &standard_deviation;
  6356. #if defined(CATCH_CONFIG_USE_ASYNC)
  6357. auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
  6358. auto seed = entropy();
  6359. return std::async(std::launch::async, [=] {
  6360. std::mt19937 rng(seed);
  6361. auto resampled = resample(rng, n_resamples, first, last, f);
  6362. return bootstrap(confidence_level, first, last, resampled, f);
  6363. });
  6364. };
  6365. auto mean_future = Estimate(mean);
  6366. auto stddev_future = Estimate(stddev);
  6367. auto mean_estimate = mean_future.get();
  6368. auto stddev_estimate = stddev_future.get();
  6369. #else
  6370. auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
  6371. auto seed = entropy();
  6372. std::mt19937 rng(seed);
  6373. auto resampled = resample(rng, n_resamples, first, last, f);
  6374. return bootstrap(confidence_level, first, last, resampled, f);
  6375. };
  6376. auto mean_estimate = Estimate(mean);
  6377. auto stddev_estimate = Estimate(stddev);
  6378. #endif // CATCH_USE_ASYNC
  6379. double outlier_variance = Detail::outlier_variance(mean_estimate, stddev_estimate, n);
  6380. return { mean_estimate, stddev_estimate, outlier_variance };
  6381. }
  6382. } // namespace Detail
  6383. } // namespace Benchmark
  6384. } // namespace Catch
  6385. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  6386. // end catch_stats.cpp
  6387. // start catch_approx.cpp
  6388. #include <cmath>
  6389. #include <limits>
  6390. namespace {
  6391. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  6392. // But without the subtraction to allow for INFINITY in comparison
  6393. bool marginComparison(double lhs, double rhs, double margin) {
  6394. return (lhs + margin >= rhs) && (rhs + margin >= lhs);
  6395. }
  6396. }
  6397. namespace Catch {
  6398. namespace Detail {
  6399. Approx::Approx ( double value )
  6400. : m_epsilon( std::numeric_limits<float>::epsilon()*100 ),
  6401. m_margin( 0.0 ),
  6402. m_scale( 0.0 ),
  6403. m_value( value )
  6404. {}
  6405. Approx Approx::custom() {
  6406. return Approx( 0 );
  6407. }
  6408. Approx Approx::operator-() const {
  6409. auto temp(*this);
  6410. temp.m_value = -temp.m_value;
  6411. return temp;
  6412. }
  6413. std::string Approx::toString() const {
  6414. ReusableStringStream rss;
  6415. rss << "Approx( " << ::Catch::Detail::stringify( m_value ) << " )";
  6416. return rss.str();
  6417. }
  6418. bool Approx::equalityComparisonImpl(const double other) const {
  6419. // First try with fixed margin, then compute margin based on epsilon, scale and Approx's value
  6420. // Thanks to Richard Harris for his help refining the scaled margin value
  6421. return marginComparison(m_value, other, m_margin)
  6422. || marginComparison(m_value, other, m_epsilon * (m_scale + std::fabs(std::isinf(m_value)? 0 : m_value)));
  6423. }
  6424. void Approx::setMargin(double newMargin) {
  6425. CATCH_ENFORCE(newMargin >= 0,
  6426. "Invalid Approx::margin: " << newMargin << '.'
  6427. << " Approx::Margin has to be non-negative.");
  6428. m_margin = newMargin;
  6429. }
  6430. void Approx::setEpsilon(double newEpsilon) {
  6431. CATCH_ENFORCE(newEpsilon >= 0 && newEpsilon <= 1.0,
  6432. "Invalid Approx::epsilon: " << newEpsilon << '.'
  6433. << " Approx::epsilon has to be in [0, 1]");
  6434. m_epsilon = newEpsilon;
  6435. }
  6436. } // end namespace Detail
  6437. namespace literals {
  6438. Detail::Approx operator "" _a(long double val) {
  6439. return Detail::Approx(val);
  6440. }
  6441. Detail::Approx operator "" _a(unsigned long long val) {
  6442. return Detail::Approx(val);
  6443. }
  6444. } // end namespace literals
  6445. std::string StringMaker<Catch::Detail::Approx>::convert(Catch::Detail::Approx const& value) {
  6446. return value.toString();
  6447. }
  6448. } // end namespace Catch
  6449. // end catch_approx.cpp
  6450. // start catch_assertionhandler.cpp
  6451. // start catch_debugger.h
  6452. namespace Catch {
  6453. bool isDebuggerActive();
  6454. }
  6455. #ifdef CATCH_PLATFORM_MAC
  6456. #if defined(__i386__) || defined(__x86_64__)
  6457. #define CATCH_TRAP() __asm__("int $3\n" : : ) /* NOLINT */
  6458. #elif defined(__aarch64__)
  6459. #define CATCH_TRAP() __asm__(".inst 0xd4200000")
  6460. #endif
  6461. #elif defined(CATCH_PLATFORM_IPHONE)
  6462. // use inline assembler
  6463. #if defined(__i386__) || defined(__x86_64__)
  6464. #define CATCH_TRAP() __asm__("int $3")
  6465. #elif defined(__aarch64__)
  6466. #define CATCH_TRAP() __asm__(".inst 0xd4200000")
  6467. #elif defined(__arm__) && !defined(__thumb__)
  6468. #define CATCH_TRAP() __asm__(".inst 0xe7f001f0")
  6469. #elif defined(__arm__) && defined(__thumb__)
  6470. #define CATCH_TRAP() __asm__(".inst 0xde01")
  6471. #endif
  6472. #elif defined(CATCH_PLATFORM_LINUX)
  6473. // If we can use inline assembler, do it because this allows us to break
  6474. // directly at the location of the failing check instead of breaking inside
  6475. // raise() called from it, i.e. one stack frame below.
  6476. #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64))
  6477. #define CATCH_TRAP() asm volatile ("int $3") /* NOLINT */
  6478. #else // Fall back to the generic way.
  6479. #include <signal.h>
  6480. #define CATCH_TRAP() raise(SIGTRAP)
  6481. #endif
  6482. #elif defined(_MSC_VER)
  6483. #define CATCH_TRAP() __debugbreak()
  6484. #elif defined(__MINGW32__)
  6485. extern "C" __declspec(dllimport) void __stdcall DebugBreak();
  6486. #define CATCH_TRAP() DebugBreak()
  6487. #endif
  6488. #ifndef CATCH_BREAK_INTO_DEBUGGER
  6489. #ifdef CATCH_TRAP
  6490. #define CATCH_BREAK_INTO_DEBUGGER() []{ if( Catch::isDebuggerActive() ) { CATCH_TRAP(); } }()
  6491. #else
  6492. #define CATCH_BREAK_INTO_DEBUGGER() []{}()
  6493. #endif
  6494. #endif
  6495. // end catch_debugger.h
  6496. // start catch_run_context.h
  6497. // start catch_fatal_condition.h
  6498. #include <cassert>
  6499. namespace Catch {
  6500. // Wrapper for platform-specific fatal error (signals/SEH) handlers
  6501. //
  6502. // Tries to be cooperative with other handlers, and not step over
  6503. // other handlers. This means that unknown structured exceptions
  6504. // are passed on, previous signal handlers are called, and so on.
  6505. //
  6506. // Can only be instantiated once, and assumes that once a signal
  6507. // is caught, the binary will end up terminating. Thus, there
  6508. class FatalConditionHandler {
  6509. bool m_started = false;
  6510. // Install/disengage implementation for specific platform.
  6511. // Should be if-defed to work on current platform, can assume
  6512. // engage-disengage 1:1 pairing.
  6513. void engage_platform();
  6514. void disengage_platform();
  6515. public:
  6516. // Should also have platform-specific implementations as needed
  6517. FatalConditionHandler();
  6518. ~FatalConditionHandler();
  6519. void engage() {
  6520. assert(!m_started && "Handler cannot be installed twice.");
  6521. m_started = true;
  6522. engage_platform();
  6523. }
  6524. void disengage() {
  6525. assert(m_started && "Handler cannot be uninstalled without being installed first");
  6526. m_started = false;
  6527. disengage_platform();
  6528. }
  6529. };
  6530. //! Simple RAII guard for (dis)engaging the FatalConditionHandler
  6531. class FatalConditionHandlerGuard {
  6532. FatalConditionHandler* m_handler;
  6533. public:
  6534. FatalConditionHandlerGuard(FatalConditionHandler* handler):
  6535. m_handler(handler) {
  6536. m_handler->engage();
  6537. }
  6538. ~FatalConditionHandlerGuard() {
  6539. m_handler->disengage();
  6540. }
  6541. };
  6542. } // end namespace Catch
  6543. // end catch_fatal_condition.h
  6544. #include <string>
  6545. namespace Catch {
  6546. struct IMutableContext;
  6547. ///////////////////////////////////////////////////////////////////////////
  6548. class RunContext : public IResultCapture, public IRunner {
  6549. public:
  6550. RunContext( RunContext const& ) = delete;
  6551. RunContext& operator =( RunContext const& ) = delete;
  6552. explicit RunContext( IConfigPtr const& _config, IStreamingReporterPtr&& reporter );
  6553. ~RunContext() override;
  6554. void testGroupStarting( std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount );
  6555. void testGroupEnded( std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount );
  6556. Totals runTest(TestCase const& testCase);
  6557. IConfigPtr config() const;
  6558. IStreamingReporter& reporter() const;
  6559. public: // IResultCapture
  6560. // Assertion handlers
  6561. void handleExpr
  6562. ( AssertionInfo const& info,
  6563. ITransientExpression const& expr,
  6564. AssertionReaction& reaction ) override;
  6565. void handleMessage
  6566. ( AssertionInfo const& info,
  6567. ResultWas::OfType resultType,
  6568. StringRef const& message,
  6569. AssertionReaction& reaction ) override;
  6570. void handleUnexpectedExceptionNotThrown
  6571. ( AssertionInfo const& info,
  6572. AssertionReaction& reaction ) override;
  6573. void handleUnexpectedInflightException
  6574. ( AssertionInfo const& info,
  6575. std::string const& message,
  6576. AssertionReaction& reaction ) override;
  6577. void handleIncomplete
  6578. ( AssertionInfo const& info ) override;
  6579. void handleNonExpr
  6580. ( AssertionInfo const &info,
  6581. ResultWas::OfType resultType,
  6582. AssertionReaction &reaction ) override;
  6583. bool sectionStarted( SectionInfo const& sectionInfo, Counts& assertions ) override;
  6584. void sectionEnded( SectionEndInfo const& endInfo ) override;
  6585. void sectionEndedEarly( SectionEndInfo const& endInfo ) override;
  6586. auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker& override;
  6587. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  6588. void benchmarkPreparing( std::string const& name ) override;
  6589. void benchmarkStarting( BenchmarkInfo const& info ) override;
  6590. void benchmarkEnded( BenchmarkStats<> const& stats ) override;
  6591. void benchmarkFailed( std::string const& error ) override;
  6592. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  6593. void pushScopedMessage( MessageInfo const& message ) override;
  6594. void popScopedMessage( MessageInfo const& message ) override;
  6595. void emplaceUnscopedMessage( MessageBuilder const& builder ) override;
  6596. std::string getCurrentTestName() const override;
  6597. const AssertionResult* getLastResult() const override;
  6598. void exceptionEarlyReported() override;
  6599. void handleFatalErrorCondition( StringRef message ) override;
  6600. bool lastAssertionPassed() override;
  6601. void assertionPassed() override;
  6602. public:
  6603. // !TBD We need to do this another way!
  6604. bool aborting() const final;
  6605. private:
  6606. void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr );
  6607. void invokeActiveTestCase();
  6608. void resetAssertionInfo();
  6609. bool testForMissingAssertions( Counts& assertions );
  6610. void assertionEnded( AssertionResult const& result );
  6611. void reportExpr
  6612. ( AssertionInfo const &info,
  6613. ResultWas::OfType resultType,
  6614. ITransientExpression const *expr,
  6615. bool negated );
  6616. void populateReaction( AssertionReaction& reaction );
  6617. private:
  6618. void handleUnfinishedSections();
  6619. TestRunInfo m_runInfo;
  6620. IMutableContext& m_context;
  6621. TestCase const* m_activeTestCase = nullptr;
  6622. ITracker* m_testCaseTracker = nullptr;
  6623. Option<AssertionResult> m_lastResult;
  6624. IConfigPtr m_config;
  6625. Totals m_totals;
  6626. IStreamingReporterPtr m_reporter;
  6627. std::vector<MessageInfo> m_messages;
  6628. std::vector<ScopedMessage> m_messageScopes; /* Keeps owners of so-called unscoped messages. */
  6629. AssertionInfo m_lastAssertionInfo;
  6630. std::vector<SectionEndInfo> m_unfinishedSections;
  6631. std::vector<ITracker*> m_activeSections;
  6632. TrackerContext m_trackerContext;
  6633. FatalConditionHandler m_fatalConditionhandler;
  6634. bool m_lastAssertionPassed = false;
  6635. bool m_shouldReportUnexpected = true;
  6636. bool m_includeSuccessfulResults;
  6637. };
  6638. void seedRng(IConfig const& config);
  6639. unsigned int rngSeed();
  6640. } // end namespace Catch
  6641. // end catch_run_context.h
  6642. namespace Catch {
  6643. namespace {
  6644. auto operator <<( std::ostream& os, ITransientExpression const& expr ) -> std::ostream& {
  6645. expr.streamReconstructedExpression( os );
  6646. return os;
  6647. }
  6648. }
  6649. LazyExpression::LazyExpression( bool isNegated )
  6650. : m_isNegated( isNegated )
  6651. {}
  6652. LazyExpression::LazyExpression( LazyExpression const& other ) : m_isNegated( other.m_isNegated ) {}
  6653. LazyExpression::operator bool() const {
  6654. return m_transientExpression != nullptr;
  6655. }
  6656. auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream& {
  6657. if( lazyExpr.m_isNegated )
  6658. os << "!";
  6659. if( lazyExpr ) {
  6660. if( lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression() )
  6661. os << "(" << *lazyExpr.m_transientExpression << ")";
  6662. else
  6663. os << *lazyExpr.m_transientExpression;
  6664. }
  6665. else {
  6666. os << "{** error - unchecked empty expression requested **}";
  6667. }
  6668. return os;
  6669. }
  6670. AssertionHandler::AssertionHandler
  6671. ( StringRef const& macroName,
  6672. SourceLineInfo const& lineInfo,
  6673. StringRef capturedExpression,
  6674. ResultDisposition::Flags resultDisposition )
  6675. : m_assertionInfo{ macroName, lineInfo, capturedExpression, resultDisposition },
  6676. m_resultCapture( getResultCapture() )
  6677. {}
  6678. void AssertionHandler::handleExpr( ITransientExpression const& expr ) {
  6679. m_resultCapture.handleExpr( m_assertionInfo, expr, m_reaction );
  6680. }
  6681. void AssertionHandler::handleMessage(ResultWas::OfType resultType, StringRef const& message) {
  6682. m_resultCapture.handleMessage( m_assertionInfo, resultType, message, m_reaction );
  6683. }
  6684. auto AssertionHandler::allowThrows() const -> bool {
  6685. return getCurrentContext().getConfig()->allowThrows();
  6686. }
  6687. void AssertionHandler::complete() {
  6688. setCompleted();
  6689. if( m_reaction.shouldDebugBreak ) {
  6690. // If you find your debugger stopping you here then go one level up on the
  6691. // call-stack for the code that caused it (typically a failed assertion)
  6692. // (To go back to the test and change execution, jump over the throw, next)
  6693. CATCH_BREAK_INTO_DEBUGGER();
  6694. }
  6695. if (m_reaction.shouldThrow) {
  6696. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  6697. throw Catch::TestFailureException();
  6698. #else
  6699. CATCH_ERROR( "Test failure requires aborting test!" );
  6700. #endif
  6701. }
  6702. }
  6703. void AssertionHandler::setCompleted() {
  6704. m_completed = true;
  6705. }
  6706. void AssertionHandler::handleUnexpectedInflightException() {
  6707. m_resultCapture.handleUnexpectedInflightException( m_assertionInfo, Catch::translateActiveException(), m_reaction );
  6708. }
  6709. void AssertionHandler::handleExceptionThrownAsExpected() {
  6710. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  6711. }
  6712. void AssertionHandler::handleExceptionNotThrownAsExpected() {
  6713. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  6714. }
  6715. void AssertionHandler::handleUnexpectedExceptionNotThrown() {
  6716. m_resultCapture.handleUnexpectedExceptionNotThrown( m_assertionInfo, m_reaction );
  6717. }
  6718. void AssertionHandler::handleThrowingCallSkipped() {
  6719. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  6720. }
  6721. // This is the overload that takes a string and infers the Equals matcher from it
  6722. // The more general overload, that takes any string matcher, is in catch_capture_matchers.cpp
  6723. void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString ) {
  6724. handleExceptionMatchExpr( handler, Matchers::Equals( str ), matcherString );
  6725. }
  6726. } // namespace Catch
  6727. // end catch_assertionhandler.cpp
  6728. // start catch_assertionresult.cpp
  6729. namespace Catch {
  6730. AssertionResultData::AssertionResultData(ResultWas::OfType _resultType, LazyExpression const & _lazyExpression):
  6731. lazyExpression(_lazyExpression),
  6732. resultType(_resultType) {}
  6733. std::string AssertionResultData::reconstructExpression() const {
  6734. if( reconstructedExpression.empty() ) {
  6735. if( lazyExpression ) {
  6736. ReusableStringStream rss;
  6737. rss << lazyExpression;
  6738. reconstructedExpression = rss.str();
  6739. }
  6740. }
  6741. return reconstructedExpression;
  6742. }
  6743. AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data )
  6744. : m_info( info ),
  6745. m_resultData( data )
  6746. {}
  6747. // Result was a success
  6748. bool AssertionResult::succeeded() const {
  6749. return Catch::isOk( m_resultData.resultType );
  6750. }
  6751. // Result was a success, or failure is suppressed
  6752. bool AssertionResult::isOk() const {
  6753. return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition );
  6754. }
  6755. ResultWas::OfType AssertionResult::getResultType() const {
  6756. return m_resultData.resultType;
  6757. }
  6758. bool AssertionResult::hasExpression() const {
  6759. return !m_info.capturedExpression.empty();
  6760. }
  6761. bool AssertionResult::hasMessage() const {
  6762. return !m_resultData.message.empty();
  6763. }
  6764. std::string AssertionResult::getExpression() const {
  6765. // Possibly overallocating by 3 characters should be basically free
  6766. std::string expr; expr.reserve(m_info.capturedExpression.size() + 3);
  6767. if (isFalseTest(m_info.resultDisposition)) {
  6768. expr += "!(";
  6769. }
  6770. expr += m_info.capturedExpression;
  6771. if (isFalseTest(m_info.resultDisposition)) {
  6772. expr += ')';
  6773. }
  6774. return expr;
  6775. }
  6776. std::string AssertionResult::getExpressionInMacro() const {
  6777. std::string expr;
  6778. if( m_info.macroName.empty() )
  6779. expr = static_cast<std::string>(m_info.capturedExpression);
  6780. else {
  6781. expr.reserve( m_info.macroName.size() + m_info.capturedExpression.size() + 4 );
  6782. expr += m_info.macroName;
  6783. expr += "( ";
  6784. expr += m_info.capturedExpression;
  6785. expr += " )";
  6786. }
  6787. return expr;
  6788. }
  6789. bool AssertionResult::hasExpandedExpression() const {
  6790. return hasExpression() && getExpandedExpression() != getExpression();
  6791. }
  6792. std::string AssertionResult::getExpandedExpression() const {
  6793. std::string expr = m_resultData.reconstructExpression();
  6794. return expr.empty()
  6795. ? getExpression()
  6796. : expr;
  6797. }
  6798. std::string AssertionResult::getMessage() const {
  6799. return m_resultData.message;
  6800. }
  6801. SourceLineInfo AssertionResult::getSourceInfo() const {
  6802. return m_info.lineInfo;
  6803. }
  6804. StringRef AssertionResult::getTestMacroName() const {
  6805. return m_info.macroName;
  6806. }
  6807. } // end namespace Catch
  6808. // end catch_assertionresult.cpp
  6809. // start catch_capture_matchers.cpp
  6810. namespace Catch {
  6811. using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
  6812. // This is the general overload that takes a any string matcher
  6813. // There is another overload, in catch_assertionhandler.h/.cpp, that only takes a string and infers
  6814. // the Equals matcher (so the header does not mention matchers)
  6815. void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString ) {
  6816. std::string exceptionMessage = Catch::translateActiveException();
  6817. MatchExpr<std::string, StringMatcher const&> expr( exceptionMessage, matcher, matcherString );
  6818. handler.handleExpr( expr );
  6819. }
  6820. } // namespace Catch
  6821. // end catch_capture_matchers.cpp
  6822. // start catch_commandline.cpp
  6823. // start catch_commandline.h
  6824. // start catch_clara.h
  6825. // Use Catch's value for console width (store Clara's off to the side, if present)
  6826. #ifdef CLARA_CONFIG_CONSOLE_WIDTH
  6827. #define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  6828. #undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  6829. #endif
  6830. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH-1
  6831. #ifdef __clang__
  6832. #pragma clang diagnostic push
  6833. #pragma clang diagnostic ignored "-Wweak-vtables"
  6834. #pragma clang diagnostic ignored "-Wexit-time-destructors"
  6835. #pragma clang diagnostic ignored "-Wshadow"
  6836. #endif
  6837. // start clara.hpp
  6838. // Copyright 2017 Two Blue Cubes Ltd. All rights reserved.
  6839. //
  6840. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  6841. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6842. //
  6843. // See https://github.com/philsquared/Clara for more details
  6844. // Clara v1.1.5
  6845. #ifndef CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  6846. #define CATCH_CLARA_CONFIG_CONSOLE_WIDTH 80
  6847. #endif
  6848. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  6849. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  6850. #endif
  6851. #ifndef CLARA_CONFIG_OPTIONAL_TYPE
  6852. #ifdef __has_include
  6853. #if __has_include(<optional>) && __cplusplus >= 201703L
  6854. #include <optional>
  6855. #define CLARA_CONFIG_OPTIONAL_TYPE std::optional
  6856. #endif
  6857. #endif
  6858. #endif
  6859. // ----------- #included from clara_textflow.hpp -----------
  6860. // TextFlowCpp
  6861. //
  6862. // A single-header library for wrapping and laying out basic text, by Phil Nash
  6863. //
  6864. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  6865. // file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6866. //
  6867. // This project is hosted at https://github.com/philsquared/textflowcpp
  6868. #include <cassert>
  6869. #include <ostream>
  6870. #include <sstream>
  6871. #include <vector>
  6872. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  6873. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80
  6874. #endif
  6875. namespace Catch {
  6876. namespace clara {
  6877. namespace TextFlow {
  6878. inline auto isWhitespace(char c) -> bool {
  6879. static std::string chars = " \t\n\r";
  6880. return chars.find(c) != std::string::npos;
  6881. }
  6882. inline auto isBreakableBefore(char c) -> bool {
  6883. static std::string chars = "[({<|";
  6884. return chars.find(c) != std::string::npos;
  6885. }
  6886. inline auto isBreakableAfter(char c) -> bool {
  6887. static std::string chars = "])}>.,:;*+-=&/\\";
  6888. return chars.find(c) != std::string::npos;
  6889. }
  6890. class Columns;
  6891. class Column {
  6892. std::vector<std::string> m_strings;
  6893. size_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH;
  6894. size_t m_indent = 0;
  6895. size_t m_initialIndent = std::string::npos;
  6896. public:
  6897. class iterator {
  6898. friend Column;
  6899. Column const& m_column;
  6900. size_t m_stringIndex = 0;
  6901. size_t m_pos = 0;
  6902. size_t m_len = 0;
  6903. size_t m_end = 0;
  6904. bool m_suffix = false;
  6905. iterator(Column const& column, size_t stringIndex)
  6906. : m_column(column),
  6907. m_stringIndex(stringIndex) {}
  6908. auto line() const -> std::string const& { return m_column.m_strings[m_stringIndex]; }
  6909. auto isBoundary(size_t at) const -> bool {
  6910. assert(at > 0);
  6911. assert(at <= line().size());
  6912. return at == line().size() ||
  6913. (isWhitespace(line()[at]) && !isWhitespace(line()[at - 1])) ||
  6914. isBreakableBefore(line()[at]) ||
  6915. isBreakableAfter(line()[at - 1]);
  6916. }
  6917. void calcLength() {
  6918. assert(m_stringIndex < m_column.m_strings.size());
  6919. m_suffix = false;
  6920. auto width = m_column.m_width - indent();
  6921. m_end = m_pos;
  6922. if (line()[m_pos] == '\n') {
  6923. ++m_end;
  6924. }
  6925. while (m_end < line().size() && line()[m_end] != '\n')
  6926. ++m_end;
  6927. if (m_end < m_pos + width) {
  6928. m_len = m_end - m_pos;
  6929. } else {
  6930. size_t len = width;
  6931. while (len > 0 && !isBoundary(m_pos + len))
  6932. --len;
  6933. while (len > 0 && isWhitespace(line()[m_pos + len - 1]))
  6934. --len;
  6935. if (len > 0) {
  6936. m_len = len;
  6937. } else {
  6938. m_suffix = true;
  6939. m_len = width - 1;
  6940. }
  6941. }
  6942. }
  6943. auto indent() const -> size_t {
  6944. auto initial = m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos;
  6945. return initial == std::string::npos ? m_column.m_indent : initial;
  6946. }
  6947. auto addIndentAndSuffix(std::string const &plain) const -> std::string {
  6948. return std::string(indent(), ' ') + (m_suffix ? plain + "-" : plain);
  6949. }
  6950. public:
  6951. using difference_type = std::ptrdiff_t;
  6952. using value_type = std::string;
  6953. using pointer = value_type * ;
  6954. using reference = value_type & ;
  6955. using iterator_category = std::forward_iterator_tag;
  6956. explicit iterator(Column const& column) : m_column(column) {
  6957. assert(m_column.m_width > m_column.m_indent);
  6958. assert(m_column.m_initialIndent == std::string::npos || m_column.m_width > m_column.m_initialIndent);
  6959. calcLength();
  6960. if (m_len == 0)
  6961. m_stringIndex++; // Empty string
  6962. }
  6963. auto operator *() const -> std::string {
  6964. assert(m_stringIndex < m_column.m_strings.size());
  6965. assert(m_pos <= m_end);
  6966. return addIndentAndSuffix(line().substr(m_pos, m_len));
  6967. }
  6968. auto operator ++() -> iterator& {
  6969. m_pos += m_len;
  6970. if (m_pos < line().size() && line()[m_pos] == '\n')
  6971. m_pos += 1;
  6972. else
  6973. while (m_pos < line().size() && isWhitespace(line()[m_pos]))
  6974. ++m_pos;
  6975. if (m_pos == line().size()) {
  6976. m_pos = 0;
  6977. ++m_stringIndex;
  6978. }
  6979. if (m_stringIndex < m_column.m_strings.size())
  6980. calcLength();
  6981. return *this;
  6982. }
  6983. auto operator ++(int) -> iterator {
  6984. iterator prev(*this);
  6985. operator++();
  6986. return prev;
  6987. }
  6988. auto operator ==(iterator const& other) const -> bool {
  6989. return
  6990. m_pos == other.m_pos &&
  6991. m_stringIndex == other.m_stringIndex &&
  6992. &m_column == &other.m_column;
  6993. }
  6994. auto operator !=(iterator const& other) const -> bool {
  6995. return !operator==(other);
  6996. }
  6997. };
  6998. using const_iterator = iterator;
  6999. explicit Column(std::string const& text) { m_strings.push_back(text); }
  7000. auto width(size_t newWidth) -> Column& {
  7001. assert(newWidth > 0);
  7002. m_width = newWidth;
  7003. return *this;
  7004. }
  7005. auto indent(size_t newIndent) -> Column& {
  7006. m_indent = newIndent;
  7007. return *this;
  7008. }
  7009. auto initialIndent(size_t newIndent) -> Column& {
  7010. m_initialIndent = newIndent;
  7011. return *this;
  7012. }
  7013. auto width() const -> size_t { return m_width; }
  7014. auto begin() const -> iterator { return iterator(*this); }
  7015. auto end() const -> iterator { return { *this, m_strings.size() }; }
  7016. inline friend std::ostream& operator << (std::ostream& os, Column const& col) {
  7017. bool first = true;
  7018. for (auto line : col) {
  7019. if (first)
  7020. first = false;
  7021. else
  7022. os << "\n";
  7023. os << line;
  7024. }
  7025. return os;
  7026. }
  7027. auto operator + (Column const& other)->Columns;
  7028. auto toString() const -> std::string {
  7029. std::ostringstream oss;
  7030. oss << *this;
  7031. return oss.str();
  7032. }
  7033. };
  7034. class Spacer : public Column {
  7035. public:
  7036. explicit Spacer(size_t spaceWidth) : Column("") {
  7037. width(spaceWidth);
  7038. }
  7039. };
  7040. class Columns {
  7041. std::vector<Column> m_columns;
  7042. public:
  7043. class iterator {
  7044. friend Columns;
  7045. struct EndTag {};
  7046. std::vector<Column> const& m_columns;
  7047. std::vector<Column::iterator> m_iterators;
  7048. size_t m_activeIterators;
  7049. iterator(Columns const& columns, EndTag)
  7050. : m_columns(columns.m_columns),
  7051. m_activeIterators(0) {
  7052. m_iterators.reserve(m_columns.size());
  7053. for (auto const& col : m_columns)
  7054. m_iterators.push_back(col.end());
  7055. }
  7056. public:
  7057. using difference_type = std::ptrdiff_t;
  7058. using value_type = std::string;
  7059. using pointer = value_type * ;
  7060. using reference = value_type & ;
  7061. using iterator_category = std::forward_iterator_tag;
  7062. explicit iterator(Columns const& columns)
  7063. : m_columns(columns.m_columns),
  7064. m_activeIterators(m_columns.size()) {
  7065. m_iterators.reserve(m_columns.size());
  7066. for (auto const& col : m_columns)
  7067. m_iterators.push_back(col.begin());
  7068. }
  7069. auto operator ==(iterator const& other) const -> bool {
  7070. return m_iterators == other.m_iterators;
  7071. }
  7072. auto operator !=(iterator const& other) const -> bool {
  7073. return m_iterators != other.m_iterators;
  7074. }
  7075. auto operator *() const -> std::string {
  7076. std::string row, padding;
  7077. for (size_t i = 0; i < m_columns.size(); ++i) {
  7078. auto width = m_columns[i].width();
  7079. if (m_iterators[i] != m_columns[i].end()) {
  7080. std::string col = *m_iterators[i];
  7081. row += padding + col;
  7082. if (col.size() < width)
  7083. padding = std::string(width - col.size(), ' ');
  7084. else
  7085. padding = "";
  7086. } else {
  7087. padding += std::string(width, ' ');
  7088. }
  7089. }
  7090. return row;
  7091. }
  7092. auto operator ++() -> iterator& {
  7093. for (size_t i = 0; i < m_columns.size(); ++i) {
  7094. if (m_iterators[i] != m_columns[i].end())
  7095. ++m_iterators[i];
  7096. }
  7097. return *this;
  7098. }
  7099. auto operator ++(int) -> iterator {
  7100. iterator prev(*this);
  7101. operator++();
  7102. return prev;
  7103. }
  7104. };
  7105. using const_iterator = iterator;
  7106. auto begin() const -> iterator { return iterator(*this); }
  7107. auto end() const -> iterator { return { *this, iterator::EndTag() }; }
  7108. auto operator += (Column const& col) -> Columns& {
  7109. m_columns.push_back(col);
  7110. return *this;
  7111. }
  7112. auto operator + (Column const& col) -> Columns {
  7113. Columns combined = *this;
  7114. combined += col;
  7115. return combined;
  7116. }
  7117. inline friend std::ostream& operator << (std::ostream& os, Columns const& cols) {
  7118. bool first = true;
  7119. for (auto line : cols) {
  7120. if (first)
  7121. first = false;
  7122. else
  7123. os << "\n";
  7124. os << line;
  7125. }
  7126. return os;
  7127. }
  7128. auto toString() const -> std::string {
  7129. std::ostringstream oss;
  7130. oss << *this;
  7131. return oss.str();
  7132. }
  7133. };
  7134. inline auto Column::operator + (Column const& other) -> Columns {
  7135. Columns cols;
  7136. cols += *this;
  7137. cols += other;
  7138. return cols;
  7139. }
  7140. }
  7141. }
  7142. }
  7143. // ----------- end of #include from clara_textflow.hpp -----------
  7144. // ........... back in clara.hpp
  7145. #include <cctype>
  7146. #include <string>
  7147. #include <memory>
  7148. #include <set>
  7149. #include <algorithm>
  7150. #if !defined(CATCH_PLATFORM_WINDOWS) && ( defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) )
  7151. #define CATCH_PLATFORM_WINDOWS
  7152. #endif
  7153. namespace Catch { namespace clara {
  7154. namespace detail {
  7155. // Traits for extracting arg and return type of lambdas (for single argument lambdas)
  7156. template<typename L>
  7157. struct UnaryLambdaTraits : UnaryLambdaTraits<decltype( &L::operator() )> {};
  7158. template<typename ClassT, typename ReturnT, typename... Args>
  7159. struct UnaryLambdaTraits<ReturnT( ClassT::* )( Args... ) const> {
  7160. static const bool isValid = false;
  7161. };
  7162. template<typename ClassT, typename ReturnT, typename ArgT>
  7163. struct UnaryLambdaTraits<ReturnT( ClassT::* )( ArgT ) const> {
  7164. static const bool isValid = true;
  7165. using ArgType = typename std::remove_const<typename std::remove_reference<ArgT>::type>::type;
  7166. using ReturnType = ReturnT;
  7167. };
  7168. class TokenStream;
  7169. // Transport for raw args (copied from main args, or supplied via init list for testing)
  7170. class Args {
  7171. friend TokenStream;
  7172. std::string m_exeName;
  7173. std::vector<std::string> m_args;
  7174. public:
  7175. Args( int argc, char const* const* argv )
  7176. : m_exeName(argv[0]),
  7177. m_args(argv + 1, argv + argc) {}
  7178. Args( std::initializer_list<std::string> args )
  7179. : m_exeName( *args.begin() ),
  7180. m_args( args.begin()+1, args.end() )
  7181. {}
  7182. auto exeName() const -> std::string {
  7183. return m_exeName;
  7184. }
  7185. };
  7186. // Wraps a token coming from a token stream. These may not directly correspond to strings as a single string
  7187. // may encode an option + its argument if the : or = form is used
  7188. enum class TokenType {
  7189. Option, Argument
  7190. };
  7191. struct Token {
  7192. TokenType type;
  7193. std::string token;
  7194. };
  7195. inline auto isOptPrefix( char c ) -> bool {
  7196. return c == '-'
  7197. #ifdef CATCH_PLATFORM_WINDOWS
  7198. || c == '/'
  7199. #endif
  7200. ;
  7201. }
  7202. // Abstracts iterators into args as a stream of tokens, with option arguments uniformly handled
  7203. class TokenStream {
  7204. using Iterator = std::vector<std::string>::const_iterator;
  7205. Iterator it;
  7206. Iterator itEnd;
  7207. std::vector<Token> m_tokenBuffer;
  7208. void loadBuffer() {
  7209. m_tokenBuffer.resize( 0 );
  7210. // Skip any empty strings
  7211. while( it != itEnd && it->empty() )
  7212. ++it;
  7213. if( it != itEnd ) {
  7214. auto const &next = *it;
  7215. if( isOptPrefix( next[0] ) ) {
  7216. auto delimiterPos = next.find_first_of( " :=" );
  7217. if( delimiterPos != std::string::npos ) {
  7218. m_tokenBuffer.push_back( { TokenType::Option, next.substr( 0, delimiterPos ) } );
  7219. m_tokenBuffer.push_back( { TokenType::Argument, next.substr( delimiterPos + 1 ) } );
  7220. } else {
  7221. if( next[1] != '-' && next.size() > 2 ) {
  7222. std::string opt = "- ";
  7223. for( size_t i = 1; i < next.size(); ++i ) {
  7224. opt[1] = next[i];
  7225. m_tokenBuffer.push_back( { TokenType::Option, opt } );
  7226. }
  7227. } else {
  7228. m_tokenBuffer.push_back( { TokenType::Option, next } );
  7229. }
  7230. }
  7231. } else {
  7232. m_tokenBuffer.push_back( { TokenType::Argument, next } );
  7233. }
  7234. }
  7235. }
  7236. public:
  7237. explicit TokenStream( Args const &args ) : TokenStream( args.m_args.begin(), args.m_args.end() ) {}
  7238. TokenStream( Iterator it, Iterator itEnd ) : it( it ), itEnd( itEnd ) {
  7239. loadBuffer();
  7240. }
  7241. explicit operator bool() const {
  7242. return !m_tokenBuffer.empty() || it != itEnd;
  7243. }
  7244. auto count() const -> size_t { return m_tokenBuffer.size() + (itEnd - it); }
  7245. auto operator*() const -> Token {
  7246. assert( !m_tokenBuffer.empty() );
  7247. return m_tokenBuffer.front();
  7248. }
  7249. auto operator->() const -> Token const * {
  7250. assert( !m_tokenBuffer.empty() );
  7251. return &m_tokenBuffer.front();
  7252. }
  7253. auto operator++() -> TokenStream & {
  7254. if( m_tokenBuffer.size() >= 2 ) {
  7255. m_tokenBuffer.erase( m_tokenBuffer.begin() );
  7256. } else {
  7257. if( it != itEnd )
  7258. ++it;
  7259. loadBuffer();
  7260. }
  7261. return *this;
  7262. }
  7263. };
  7264. class ResultBase {
  7265. public:
  7266. enum Type {
  7267. Ok, LogicError, RuntimeError
  7268. };
  7269. protected:
  7270. ResultBase( Type type ) : m_type( type ) {}
  7271. virtual ~ResultBase() = default;
  7272. virtual void enforceOk() const = 0;
  7273. Type m_type;
  7274. };
  7275. template<typename T>
  7276. class ResultValueBase : public ResultBase {
  7277. public:
  7278. auto value() const -> T const & {
  7279. enforceOk();
  7280. return m_value;
  7281. }
  7282. protected:
  7283. ResultValueBase( Type type ) : ResultBase( type ) {}
  7284. ResultValueBase( ResultValueBase const &other ) : ResultBase( other ) {
  7285. if( m_type == ResultBase::Ok )
  7286. new( &m_value ) T( other.m_value );
  7287. }
  7288. ResultValueBase( Type, T const &value ) : ResultBase( Ok ) {
  7289. new( &m_value ) T( value );
  7290. }
  7291. auto operator=( ResultValueBase const &other ) -> ResultValueBase & {
  7292. if( m_type == ResultBase::Ok )
  7293. m_value.~T();
  7294. ResultBase::operator=(other);
  7295. if( m_type == ResultBase::Ok )
  7296. new( &m_value ) T( other.m_value );
  7297. return *this;
  7298. }
  7299. ~ResultValueBase() override {
  7300. if( m_type == Ok )
  7301. m_value.~T();
  7302. }
  7303. union {
  7304. T m_value;
  7305. };
  7306. };
  7307. template<>
  7308. class ResultValueBase<void> : public ResultBase {
  7309. protected:
  7310. using ResultBase::ResultBase;
  7311. };
  7312. template<typename T = void>
  7313. class BasicResult : public ResultValueBase<T> {
  7314. public:
  7315. template<typename U>
  7316. explicit BasicResult( BasicResult<U> const &other )
  7317. : ResultValueBase<T>( other.type() ),
  7318. m_errorMessage( other.errorMessage() )
  7319. {
  7320. assert( type() != ResultBase::Ok );
  7321. }
  7322. template<typename U>
  7323. static auto ok( U const &value ) -> BasicResult { return { ResultBase::Ok, value }; }
  7324. static auto ok() -> BasicResult { return { ResultBase::Ok }; }
  7325. static auto logicError( std::string const &message ) -> BasicResult { return { ResultBase::LogicError, message }; }
  7326. static auto runtimeError( std::string const &message ) -> BasicResult { return { ResultBase::RuntimeError, message }; }
  7327. explicit operator bool() const { return m_type == ResultBase::Ok; }
  7328. auto type() const -> ResultBase::Type { return m_type; }
  7329. auto errorMessage() const -> std::string { return m_errorMessage; }
  7330. protected:
  7331. void enforceOk() const override {
  7332. // Errors shouldn't reach this point, but if they do
  7333. // the actual error message will be in m_errorMessage
  7334. assert( m_type != ResultBase::LogicError );
  7335. assert( m_type != ResultBase::RuntimeError );
  7336. if( m_type != ResultBase::Ok )
  7337. std::abort();
  7338. }
  7339. std::string m_errorMessage; // Only populated if resultType is an error
  7340. BasicResult( ResultBase::Type type, std::string const &message )
  7341. : ResultValueBase<T>(type),
  7342. m_errorMessage(message)
  7343. {
  7344. assert( m_type != ResultBase::Ok );
  7345. }
  7346. using ResultValueBase<T>::ResultValueBase;
  7347. using ResultBase::m_type;
  7348. };
  7349. enum class ParseResultType {
  7350. Matched, NoMatch, ShortCircuitAll, ShortCircuitSame
  7351. };
  7352. class ParseState {
  7353. public:
  7354. ParseState( ParseResultType type, TokenStream const &remainingTokens )
  7355. : m_type(type),
  7356. m_remainingTokens( remainingTokens )
  7357. {}
  7358. auto type() const -> ParseResultType { return m_type; }
  7359. auto remainingTokens() const -> TokenStream { return m_remainingTokens; }
  7360. private:
  7361. ParseResultType m_type;
  7362. TokenStream m_remainingTokens;
  7363. };
  7364. using Result = BasicResult<void>;
  7365. using ParserResult = BasicResult<ParseResultType>;
  7366. using InternalParseResult = BasicResult<ParseState>;
  7367. struct HelpColumns {
  7368. std::string left;
  7369. std::string right;
  7370. };
  7371. template<typename T>
  7372. inline auto convertInto( std::string const &source, T& target ) -> ParserResult {
  7373. std::stringstream ss;
  7374. ss << source;
  7375. ss >> target;
  7376. if( ss.fail() )
  7377. return ParserResult::runtimeError( "Unable to convert '" + source + "' to destination type" );
  7378. else
  7379. return ParserResult::ok( ParseResultType::Matched );
  7380. }
  7381. inline auto convertInto( std::string const &source, std::string& target ) -> ParserResult {
  7382. target = source;
  7383. return ParserResult::ok( ParseResultType::Matched );
  7384. }
  7385. inline auto convertInto( std::string const &source, bool &target ) -> ParserResult {
  7386. std::string srcLC = source;
  7387. std::transform( srcLC.begin(), srcLC.end(), srcLC.begin(), []( unsigned char c ) { return static_cast<char>( std::tolower(c) ); } );
  7388. if (srcLC == "y" || srcLC == "1" || srcLC == "true" || srcLC == "yes" || srcLC == "on")
  7389. target = true;
  7390. else if (srcLC == "n" || srcLC == "0" || srcLC == "false" || srcLC == "no" || srcLC == "off")
  7391. target = false;
  7392. else
  7393. return ParserResult::runtimeError( "Expected a boolean value but did not recognise: '" + source + "'" );
  7394. return ParserResult::ok( ParseResultType::Matched );
  7395. }
  7396. #ifdef CLARA_CONFIG_OPTIONAL_TYPE
  7397. template<typename T>
  7398. inline auto convertInto( std::string const &source, CLARA_CONFIG_OPTIONAL_TYPE<T>& target ) -> ParserResult {
  7399. T temp;
  7400. auto result = convertInto( source, temp );
  7401. if( result )
  7402. target = std::move(temp);
  7403. return result;
  7404. }
  7405. #endif // CLARA_CONFIG_OPTIONAL_TYPE
  7406. struct NonCopyable {
  7407. NonCopyable() = default;
  7408. NonCopyable( NonCopyable const & ) = delete;
  7409. NonCopyable( NonCopyable && ) = delete;
  7410. NonCopyable &operator=( NonCopyable const & ) = delete;
  7411. NonCopyable &operator=( NonCopyable && ) = delete;
  7412. };
  7413. struct BoundRef : NonCopyable {
  7414. virtual ~BoundRef() = default;
  7415. virtual auto isContainer() const -> bool { return false; }
  7416. virtual auto isFlag() const -> bool { return false; }
  7417. };
  7418. struct BoundValueRefBase : BoundRef {
  7419. virtual auto setValue( std::string const &arg ) -> ParserResult = 0;
  7420. };
  7421. struct BoundFlagRefBase : BoundRef {
  7422. virtual auto setFlag( bool flag ) -> ParserResult = 0;
  7423. virtual auto isFlag() const -> bool { return true; }
  7424. };
  7425. template<typename T>
  7426. struct BoundValueRef : BoundValueRefBase {
  7427. T &m_ref;
  7428. explicit BoundValueRef( T &ref ) : m_ref( ref ) {}
  7429. auto setValue( std::string const &arg ) -> ParserResult override {
  7430. return convertInto( arg, m_ref );
  7431. }
  7432. };
  7433. template<typename T>
  7434. struct BoundValueRef<std::vector<T>> : BoundValueRefBase {
  7435. std::vector<T> &m_ref;
  7436. explicit BoundValueRef( std::vector<T> &ref ) : m_ref( ref ) {}
  7437. auto isContainer() const -> bool override { return true; }
  7438. auto setValue( std::string const &arg ) -> ParserResult override {
  7439. T temp;
  7440. auto result = convertInto( arg, temp );
  7441. if( result )
  7442. m_ref.push_back( temp );
  7443. return result;
  7444. }
  7445. };
  7446. struct BoundFlagRef : BoundFlagRefBase {
  7447. bool &m_ref;
  7448. explicit BoundFlagRef( bool &ref ) : m_ref( ref ) {}
  7449. auto setFlag( bool flag ) -> ParserResult override {
  7450. m_ref = flag;
  7451. return ParserResult::ok( ParseResultType::Matched );
  7452. }
  7453. };
  7454. template<typename ReturnType>
  7455. struct LambdaInvoker {
  7456. static_assert( std::is_same<ReturnType, ParserResult>::value, "Lambda must return void or clara::ParserResult" );
  7457. template<typename L, typename ArgType>
  7458. static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
  7459. return lambda( arg );
  7460. }
  7461. };
  7462. template<>
  7463. struct LambdaInvoker<void> {
  7464. template<typename L, typename ArgType>
  7465. static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
  7466. lambda( arg );
  7467. return ParserResult::ok( ParseResultType::Matched );
  7468. }
  7469. };
  7470. template<typename ArgType, typename L>
  7471. inline auto invokeLambda( L const &lambda, std::string const &arg ) -> ParserResult {
  7472. ArgType temp{};
  7473. auto result = convertInto( arg, temp );
  7474. return !result
  7475. ? result
  7476. : LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( lambda, temp );
  7477. }
  7478. template<typename L>
  7479. struct BoundLambda : BoundValueRefBase {
  7480. L m_lambda;
  7481. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  7482. explicit BoundLambda( L const &lambda ) : m_lambda( lambda ) {}
  7483. auto setValue( std::string const &arg ) -> ParserResult override {
  7484. return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>( m_lambda, arg );
  7485. }
  7486. };
  7487. template<typename L>
  7488. struct BoundFlagLambda : BoundFlagRefBase {
  7489. L m_lambda;
  7490. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  7491. static_assert( std::is_same<typename UnaryLambdaTraits<L>::ArgType, bool>::value, "flags must be boolean" );
  7492. explicit BoundFlagLambda( L const &lambda ) : m_lambda( lambda ) {}
  7493. auto setFlag( bool flag ) -> ParserResult override {
  7494. return LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( m_lambda, flag );
  7495. }
  7496. };
  7497. enum class Optionality { Optional, Required };
  7498. struct Parser;
  7499. class ParserBase {
  7500. public:
  7501. virtual ~ParserBase() = default;
  7502. virtual auto validate() const -> Result { return Result::ok(); }
  7503. virtual auto parse( std::string const& exeName, TokenStream const &tokens) const -> InternalParseResult = 0;
  7504. virtual auto cardinality() const -> size_t { return 1; }
  7505. auto parse( Args const &args ) const -> InternalParseResult {
  7506. return parse( args.exeName(), TokenStream( args ) );
  7507. }
  7508. };
  7509. template<typename DerivedT>
  7510. class ComposableParserImpl : public ParserBase {
  7511. public:
  7512. template<typename T>
  7513. auto operator|( T const &other ) const -> Parser;
  7514. template<typename T>
  7515. auto operator+( T const &other ) const -> Parser;
  7516. };
  7517. // Common code and state for Args and Opts
  7518. template<typename DerivedT>
  7519. class ParserRefImpl : public ComposableParserImpl<DerivedT> {
  7520. protected:
  7521. Optionality m_optionality = Optionality::Optional;
  7522. std::shared_ptr<BoundRef> m_ref;
  7523. std::string m_hint;
  7524. std::string m_description;
  7525. explicit ParserRefImpl( std::shared_ptr<BoundRef> const &ref ) : m_ref( ref ) {}
  7526. public:
  7527. template<typename T>
  7528. ParserRefImpl( T &ref, std::string const &hint )
  7529. : m_ref( std::make_shared<BoundValueRef<T>>( ref ) ),
  7530. m_hint( hint )
  7531. {}
  7532. template<typename LambdaT>
  7533. ParserRefImpl( LambdaT const &ref, std::string const &hint )
  7534. : m_ref( std::make_shared<BoundLambda<LambdaT>>( ref ) ),
  7535. m_hint(hint)
  7536. {}
  7537. auto operator()( std::string const &description ) -> DerivedT & {
  7538. m_description = description;
  7539. return static_cast<DerivedT &>( *this );
  7540. }
  7541. auto optional() -> DerivedT & {
  7542. m_optionality = Optionality::Optional;
  7543. return static_cast<DerivedT &>( *this );
  7544. };
  7545. auto required() -> DerivedT & {
  7546. m_optionality = Optionality::Required;
  7547. return static_cast<DerivedT &>( *this );
  7548. };
  7549. auto isOptional() const -> bool {
  7550. return m_optionality == Optionality::Optional;
  7551. }
  7552. auto cardinality() const -> size_t override {
  7553. if( m_ref->isContainer() )
  7554. return 0;
  7555. else
  7556. return 1;
  7557. }
  7558. auto hint() const -> std::string { return m_hint; }
  7559. };
  7560. class ExeName : public ComposableParserImpl<ExeName> {
  7561. std::shared_ptr<std::string> m_name;
  7562. std::shared_ptr<BoundValueRefBase> m_ref;
  7563. template<typename LambdaT>
  7564. static auto makeRef(LambdaT const &lambda) -> std::shared_ptr<BoundValueRefBase> {
  7565. return std::make_shared<BoundLambda<LambdaT>>( lambda) ;
  7566. }
  7567. public:
  7568. ExeName() : m_name( std::make_shared<std::string>( "<executable>" ) ) {}
  7569. explicit ExeName( std::string &ref ) : ExeName() {
  7570. m_ref = std::make_shared<BoundValueRef<std::string>>( ref );
  7571. }
  7572. template<typename LambdaT>
  7573. explicit ExeName( LambdaT const& lambda ) : ExeName() {
  7574. m_ref = std::make_shared<BoundLambda<LambdaT>>( lambda );
  7575. }
  7576. // The exe name is not parsed out of the normal tokens, but is handled specially
  7577. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  7578. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
  7579. }
  7580. auto name() const -> std::string { return *m_name; }
  7581. auto set( std::string const& newName ) -> ParserResult {
  7582. auto lastSlash = newName.find_last_of( "\\/" );
  7583. auto filename = ( lastSlash == std::string::npos )
  7584. ? newName
  7585. : newName.substr( lastSlash+1 );
  7586. *m_name = filename;
  7587. if( m_ref )
  7588. return m_ref->setValue( filename );
  7589. else
  7590. return ParserResult::ok( ParseResultType::Matched );
  7591. }
  7592. };
  7593. class Arg : public ParserRefImpl<Arg> {
  7594. public:
  7595. using ParserRefImpl::ParserRefImpl;
  7596. auto parse( std::string const &, TokenStream const &tokens ) const -> InternalParseResult override {
  7597. auto validationResult = validate();
  7598. if( !validationResult )
  7599. return InternalParseResult( validationResult );
  7600. auto remainingTokens = tokens;
  7601. auto const &token = *remainingTokens;
  7602. if( token.type != TokenType::Argument )
  7603. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
  7604. assert( !m_ref->isFlag() );
  7605. auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
  7606. auto result = valueRef->setValue( remainingTokens->token );
  7607. if( !result )
  7608. return InternalParseResult( result );
  7609. else
  7610. return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
  7611. }
  7612. };
  7613. inline auto normaliseOpt( std::string const &optName ) -> std::string {
  7614. #ifdef CATCH_PLATFORM_WINDOWS
  7615. if( optName[0] == '/' )
  7616. return "-" + optName.substr( 1 );
  7617. else
  7618. #endif
  7619. return optName;
  7620. }
  7621. class Opt : public ParserRefImpl<Opt> {
  7622. protected:
  7623. std::vector<std::string> m_optNames;
  7624. public:
  7625. template<typename LambdaT>
  7626. explicit Opt( LambdaT const &ref ) : ParserRefImpl( std::make_shared<BoundFlagLambda<LambdaT>>( ref ) ) {}
  7627. explicit Opt( bool &ref ) : ParserRefImpl( std::make_shared<BoundFlagRef>( ref ) ) {}
  7628. template<typename LambdaT>
  7629. Opt( LambdaT const &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  7630. template<typename T>
  7631. Opt( T &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  7632. auto operator[]( std::string const &optName ) -> Opt & {
  7633. m_optNames.push_back( optName );
  7634. return *this;
  7635. }
  7636. auto getHelpColumns() const -> std::vector<HelpColumns> {
  7637. std::ostringstream oss;
  7638. bool first = true;
  7639. for( auto const &opt : m_optNames ) {
  7640. if (first)
  7641. first = false;
  7642. else
  7643. oss << ", ";
  7644. oss << opt;
  7645. }
  7646. if( !m_hint.empty() )
  7647. oss << " <" << m_hint << ">";
  7648. return { { oss.str(), m_description } };
  7649. }
  7650. auto isMatch( std::string const &optToken ) const -> bool {
  7651. auto normalisedToken = normaliseOpt( optToken );
  7652. for( auto const &name : m_optNames ) {
  7653. if( normaliseOpt( name ) == normalisedToken )
  7654. return true;
  7655. }
  7656. return false;
  7657. }
  7658. using ParserBase::parse;
  7659. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  7660. auto validationResult = validate();
  7661. if( !validationResult )
  7662. return InternalParseResult( validationResult );
  7663. auto remainingTokens = tokens;
  7664. if( remainingTokens && remainingTokens->type == TokenType::Option ) {
  7665. auto const &token = *remainingTokens;
  7666. if( isMatch(token.token ) ) {
  7667. if( m_ref->isFlag() ) {
  7668. auto flagRef = static_cast<detail::BoundFlagRefBase*>( m_ref.get() );
  7669. auto result = flagRef->setFlag( true );
  7670. if( !result )
  7671. return InternalParseResult( result );
  7672. if( result.value() == ParseResultType::ShortCircuitAll )
  7673. return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
  7674. } else {
  7675. auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
  7676. ++remainingTokens;
  7677. if( !remainingTokens )
  7678. return InternalParseResult::runtimeError( "Expected argument following " + token.token );
  7679. auto const &argToken = *remainingTokens;
  7680. if( argToken.type != TokenType::Argument )
  7681. return InternalParseResult::runtimeError( "Expected argument following " + token.token );
  7682. auto result = valueRef->setValue( argToken.token );
  7683. if( !result )
  7684. return InternalParseResult( result );
  7685. if( result.value() == ParseResultType::ShortCircuitAll )
  7686. return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
  7687. }
  7688. return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
  7689. }
  7690. }
  7691. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
  7692. }
  7693. auto validate() const -> Result override {
  7694. if( m_optNames.empty() )
  7695. return Result::logicError( "No options supplied to Opt" );
  7696. for( auto const &name : m_optNames ) {
  7697. if( name.empty() )
  7698. return Result::logicError( "Option name cannot be empty" );
  7699. #ifdef CATCH_PLATFORM_WINDOWS
  7700. if( name[0] != '-' && name[0] != '/' )
  7701. return Result::logicError( "Option name must begin with '-' or '/'" );
  7702. #else
  7703. if( name[0] != '-' )
  7704. return Result::logicError( "Option name must begin with '-'" );
  7705. #endif
  7706. }
  7707. return ParserRefImpl::validate();
  7708. }
  7709. };
  7710. struct Help : Opt {
  7711. Help( bool &showHelpFlag )
  7712. : Opt([&]( bool flag ) {
  7713. showHelpFlag = flag;
  7714. return ParserResult::ok( ParseResultType::ShortCircuitAll );
  7715. })
  7716. {
  7717. static_cast<Opt &>( *this )
  7718. ("display usage information")
  7719. ["-?"]["-h"]["--help"]
  7720. .optional();
  7721. }
  7722. };
  7723. struct Parser : ParserBase {
  7724. mutable ExeName m_exeName;
  7725. std::vector<Opt> m_options;
  7726. std::vector<Arg> m_args;
  7727. auto operator|=( ExeName const &exeName ) -> Parser & {
  7728. m_exeName = exeName;
  7729. return *this;
  7730. }
  7731. auto operator|=( Arg const &arg ) -> Parser & {
  7732. m_args.push_back(arg);
  7733. return *this;
  7734. }
  7735. auto operator|=( Opt const &opt ) -> Parser & {
  7736. m_options.push_back(opt);
  7737. return *this;
  7738. }
  7739. auto operator|=( Parser const &other ) -> Parser & {
  7740. m_options.insert(m_options.end(), other.m_options.begin(), other.m_options.end());
  7741. m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end());
  7742. return *this;
  7743. }
  7744. template<typename T>
  7745. auto operator|( T const &other ) const -> Parser {
  7746. return Parser( *this ) |= other;
  7747. }
  7748. // Forward deprecated interface with '+' instead of '|'
  7749. template<typename T>
  7750. auto operator+=( T const &other ) -> Parser & { return operator|=( other ); }
  7751. template<typename T>
  7752. auto operator+( T const &other ) const -> Parser { return operator|( other ); }
  7753. auto getHelpColumns() const -> std::vector<HelpColumns> {
  7754. std::vector<HelpColumns> cols;
  7755. for (auto const &o : m_options) {
  7756. auto childCols = o.getHelpColumns();
  7757. cols.insert( cols.end(), childCols.begin(), childCols.end() );
  7758. }
  7759. return cols;
  7760. }
  7761. void writeToStream( std::ostream &os ) const {
  7762. if (!m_exeName.name().empty()) {
  7763. os << "usage:\n" << " " << m_exeName.name() << " ";
  7764. bool required = true, first = true;
  7765. for( auto const &arg : m_args ) {
  7766. if (first)
  7767. first = false;
  7768. else
  7769. os << " ";
  7770. if( arg.isOptional() && required ) {
  7771. os << "[";
  7772. required = false;
  7773. }
  7774. os << "<" << arg.hint() << ">";
  7775. if( arg.cardinality() == 0 )
  7776. os << " ... ";
  7777. }
  7778. if( !required )
  7779. os << "]";
  7780. if( !m_options.empty() )
  7781. os << " options";
  7782. os << "\n\nwhere options are:" << std::endl;
  7783. }
  7784. auto rows = getHelpColumns();
  7785. size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH;
  7786. size_t optWidth = 0;
  7787. for( auto const &cols : rows )
  7788. optWidth = (std::max)(optWidth, cols.left.size() + 2);
  7789. optWidth = (std::min)(optWidth, consoleWidth/2);
  7790. for( auto const &cols : rows ) {
  7791. auto row =
  7792. TextFlow::Column( cols.left ).width( optWidth ).indent( 2 ) +
  7793. TextFlow::Spacer(4) +
  7794. TextFlow::Column( cols.right ).width( consoleWidth - 7 - optWidth );
  7795. os << row << std::endl;
  7796. }
  7797. }
  7798. friend auto operator<<( std::ostream &os, Parser const &parser ) -> std::ostream& {
  7799. parser.writeToStream( os );
  7800. return os;
  7801. }
  7802. auto validate() const -> Result override {
  7803. for( auto const &opt : m_options ) {
  7804. auto result = opt.validate();
  7805. if( !result )
  7806. return result;
  7807. }
  7808. for( auto const &arg : m_args ) {
  7809. auto result = arg.validate();
  7810. if( !result )
  7811. return result;
  7812. }
  7813. return Result::ok();
  7814. }
  7815. using ParserBase::parse;
  7816. auto parse( std::string const& exeName, TokenStream const &tokens ) const -> InternalParseResult override {
  7817. struct ParserInfo {
  7818. ParserBase const* parser = nullptr;
  7819. size_t count = 0;
  7820. };
  7821. const size_t totalParsers = m_options.size() + m_args.size();
  7822. assert( totalParsers < 512 );
  7823. // ParserInfo parseInfos[totalParsers]; // <-- this is what we really want to do
  7824. ParserInfo parseInfos[512];
  7825. {
  7826. size_t i = 0;
  7827. for (auto const &opt : m_options) parseInfos[i++].parser = &opt;
  7828. for (auto const &arg : m_args) parseInfos[i++].parser = &arg;
  7829. }
  7830. m_exeName.set( exeName );
  7831. auto result = InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
  7832. while( result.value().remainingTokens() ) {
  7833. bool tokenParsed = false;
  7834. for( size_t i = 0; i < totalParsers; ++i ) {
  7835. auto& parseInfo = parseInfos[i];
  7836. if( parseInfo.parser->cardinality() == 0 || parseInfo.count < parseInfo.parser->cardinality() ) {
  7837. result = parseInfo.parser->parse(exeName, result.value().remainingTokens());
  7838. if (!result)
  7839. return result;
  7840. if (result.value().type() != ParseResultType::NoMatch) {
  7841. tokenParsed = true;
  7842. ++parseInfo.count;
  7843. break;
  7844. }
  7845. }
  7846. }
  7847. if( result.value().type() == ParseResultType::ShortCircuitAll )
  7848. return result;
  7849. if( !tokenParsed )
  7850. return InternalParseResult::runtimeError( "Unrecognised token: " + result.value().remainingTokens()->token );
  7851. }
  7852. // !TBD Check missing required options
  7853. return result;
  7854. }
  7855. };
  7856. template<typename DerivedT>
  7857. template<typename T>
  7858. auto ComposableParserImpl<DerivedT>::operator|( T const &other ) const -> Parser {
  7859. return Parser() | static_cast<DerivedT const &>( *this ) | other;
  7860. }
  7861. } // namespace detail
  7862. // A Combined parser
  7863. using detail::Parser;
  7864. // A parser for options
  7865. using detail::Opt;
  7866. // A parser for arguments
  7867. using detail::Arg;
  7868. // Wrapper for argc, argv from main()
  7869. using detail::Args;
  7870. // Specifies the name of the executable
  7871. using detail::ExeName;
  7872. // Convenience wrapper for option parser that specifies the help option
  7873. using detail::Help;
  7874. // enum of result types from a parse
  7875. using detail::ParseResultType;
  7876. // Result type for parser operation
  7877. using detail::ParserResult;
  7878. }} // namespace Catch::clara
  7879. // end clara.hpp
  7880. #ifdef __clang__
  7881. #pragma clang diagnostic pop
  7882. #endif
  7883. // Restore Clara's value for console width, if present
  7884. #ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  7885. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  7886. #undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  7887. #endif
  7888. // end catch_clara.h
  7889. namespace Catch {
  7890. clara::Parser makeCommandLineParser( ConfigData& config );
  7891. } // end namespace Catch
  7892. // end catch_commandline.h
  7893. #include <fstream>
  7894. #include <ctime>
  7895. namespace Catch {
  7896. clara::Parser makeCommandLineParser( ConfigData& config ) {
  7897. using namespace clara;
  7898. auto const setWarning = [&]( std::string const& warning ) {
  7899. auto warningSet = [&]() {
  7900. if( warning == "NoAssertions" )
  7901. return WarnAbout::NoAssertions;
  7902. if ( warning == "NoTests" )
  7903. return WarnAbout::NoTests;
  7904. return WarnAbout::Nothing;
  7905. }();
  7906. if (warningSet == WarnAbout::Nothing)
  7907. return ParserResult::runtimeError( "Unrecognised warning: '" + warning + "'" );
  7908. config.warnings = static_cast<WarnAbout::What>( config.warnings | warningSet );
  7909. return ParserResult::ok( ParseResultType::Matched );
  7910. };
  7911. auto const loadTestNamesFromFile = [&]( std::string const& filename ) {
  7912. std::ifstream f( filename.c_str() );
  7913. if( !f.is_open() )
  7914. return ParserResult::runtimeError( "Unable to load input file: '" + filename + "'" );
  7915. std::string line;
  7916. while( std::getline( f, line ) ) {
  7917. line = trim(line);
  7918. if( !line.empty() && !startsWith( line, '#' ) ) {
  7919. if( !startsWith( line, '"' ) )
  7920. line = '"' + line + '"';
  7921. config.testsOrTags.push_back( line );
  7922. config.testsOrTags.emplace_back( "," );
  7923. }
  7924. }
  7925. //Remove comma in the end
  7926. if(!config.testsOrTags.empty())
  7927. config.testsOrTags.erase( config.testsOrTags.end()-1 );
  7928. return ParserResult::ok( ParseResultType::Matched );
  7929. };
  7930. auto const setTestOrder = [&]( std::string const& order ) {
  7931. if( startsWith( "declared", order ) )
  7932. config.runOrder = RunTests::InDeclarationOrder;
  7933. else if( startsWith( "lexical", order ) )
  7934. config.runOrder = RunTests::InLexicographicalOrder;
  7935. else if( startsWith( "random", order ) )
  7936. config.runOrder = RunTests::InRandomOrder;
  7937. else
  7938. return clara::ParserResult::runtimeError( "Unrecognised ordering: '" + order + "'" );
  7939. return ParserResult::ok( ParseResultType::Matched );
  7940. };
  7941. auto const setRngSeed = [&]( std::string const& seed ) {
  7942. if( seed != "time" )
  7943. return clara::detail::convertInto( seed, config.rngSeed );
  7944. config.rngSeed = static_cast<unsigned int>( std::time(nullptr) );
  7945. return ParserResult::ok( ParseResultType::Matched );
  7946. };
  7947. auto const setColourUsage = [&]( std::string const& useColour ) {
  7948. auto mode = toLower( useColour );
  7949. if( mode == "yes" )
  7950. config.useColour = UseColour::Yes;
  7951. else if( mode == "no" )
  7952. config.useColour = UseColour::No;
  7953. else if( mode == "auto" )
  7954. config.useColour = UseColour::Auto;
  7955. else
  7956. return ParserResult::runtimeError( "colour mode must be one of: auto, yes or no. '" + useColour + "' not recognised" );
  7957. return ParserResult::ok( ParseResultType::Matched );
  7958. };
  7959. auto const setWaitForKeypress = [&]( std::string const& keypress ) {
  7960. auto keypressLc = toLower( keypress );
  7961. if (keypressLc == "never")
  7962. config.waitForKeypress = WaitForKeypress::Never;
  7963. else if( keypressLc == "start" )
  7964. config.waitForKeypress = WaitForKeypress::BeforeStart;
  7965. else if( keypressLc == "exit" )
  7966. config.waitForKeypress = WaitForKeypress::BeforeExit;
  7967. else if( keypressLc == "both" )
  7968. config.waitForKeypress = WaitForKeypress::BeforeStartAndExit;
  7969. else
  7970. return ParserResult::runtimeError( "keypress argument must be one of: never, start, exit or both. '" + keypress + "' not recognised" );
  7971. return ParserResult::ok( ParseResultType::Matched );
  7972. };
  7973. auto const setVerbosity = [&]( std::string const& verbosity ) {
  7974. auto lcVerbosity = toLower( verbosity );
  7975. if( lcVerbosity == "quiet" )
  7976. config.verbosity = Verbosity::Quiet;
  7977. else if( lcVerbosity == "normal" )
  7978. config.verbosity = Verbosity::Normal;
  7979. else if( lcVerbosity == "high" )
  7980. config.verbosity = Verbosity::High;
  7981. else
  7982. return ParserResult::runtimeError( "Unrecognised verbosity, '" + verbosity + "'" );
  7983. return ParserResult::ok( ParseResultType::Matched );
  7984. };
  7985. auto const setReporter = [&]( std::string const& reporter ) {
  7986. IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
  7987. auto lcReporter = toLower( reporter );
  7988. auto result = factories.find( lcReporter );
  7989. if( factories.end() != result )
  7990. config.reporterName = lcReporter;
  7991. else
  7992. return ParserResult::runtimeError( "Unrecognized reporter, '" + reporter + "'. Check available with --list-reporters" );
  7993. return ParserResult::ok( ParseResultType::Matched );
  7994. };
  7995. auto cli
  7996. = ExeName( config.processName )
  7997. | Help( config.showHelp )
  7998. | Opt( config.listTests )
  7999. ["-l"]["--list-tests"]
  8000. ( "list all/matching test cases" )
  8001. | Opt( config.listTags )
  8002. ["-t"]["--list-tags"]
  8003. ( "list all/matching tags" )
  8004. | Opt( config.showSuccessfulTests )
  8005. ["-s"]["--success"]
  8006. ( "include successful tests in output" )
  8007. | Opt( config.shouldDebugBreak )
  8008. ["-b"]["--break"]
  8009. ( "break into debugger on failure" )
  8010. | Opt( config.noThrow )
  8011. ["-e"]["--nothrow"]
  8012. ( "skip exception tests" )
  8013. | Opt( config.showInvisibles )
  8014. ["-i"]["--invisibles"]
  8015. ( "show invisibles (tabs, newlines)" )
  8016. | Opt( config.outputFilename, "filename" )
  8017. ["-o"]["--out"]
  8018. ( "output filename" )
  8019. | Opt( setReporter, "name" )
  8020. ["-r"]["--reporter"]
  8021. ( "reporter to use (defaults to console)" )
  8022. | Opt( config.name, "name" )
  8023. ["-n"]["--name"]
  8024. ( "suite name" )
  8025. | Opt( [&]( bool ){ config.abortAfter = 1; } )
  8026. ["-a"]["--abort"]
  8027. ( "abort at first failure" )
  8028. | Opt( [&]( int x ){ config.abortAfter = x; }, "no. failures" )
  8029. ["-x"]["--abortx"]
  8030. ( "abort after x failures" )
  8031. | Opt( setWarning, "warning name" )
  8032. ["-w"]["--warn"]
  8033. ( "enable warnings" )
  8034. | Opt( [&]( bool flag ) { config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never; }, "yes|no" )
  8035. ["-d"]["--durations"]
  8036. ( "show test durations" )
  8037. | Opt( config.minDuration, "seconds" )
  8038. ["-D"]["--min-duration"]
  8039. ( "show test durations for tests taking at least the given number of seconds" )
  8040. | Opt( loadTestNamesFromFile, "filename" )
  8041. ["-f"]["--input-file"]
  8042. ( "load test names to run from a file" )
  8043. | Opt( config.filenamesAsTags )
  8044. ["-#"]["--filenames-as-tags"]
  8045. ( "adds a tag for the filename" )
  8046. | Opt( config.sectionsToRun, "section name" )
  8047. ["-c"]["--section"]
  8048. ( "specify section to run" )
  8049. | Opt( setVerbosity, "quiet|normal|high" )
  8050. ["-v"]["--verbosity"]
  8051. ( "set output verbosity" )
  8052. | Opt( config.listTestNamesOnly )
  8053. ["--list-test-names-only"]
  8054. ( "list all/matching test cases names only" )
  8055. | Opt( config.listReporters )
  8056. ["--list-reporters"]
  8057. ( "list all reporters" )
  8058. | Opt( setTestOrder, "decl|lex|rand" )
  8059. ["--order"]
  8060. ( "test case order (defaults to decl)" )
  8061. | Opt( setRngSeed, "'time'|number" )
  8062. ["--rng-seed"]
  8063. ( "set a specific seed for random numbers" )
  8064. | Opt( setColourUsage, "yes|no" )
  8065. ["--use-colour"]
  8066. ( "should output be colourised" )
  8067. | Opt( config.libIdentify )
  8068. ["--libidentify"]
  8069. ( "report name and version according to libidentify standard" )
  8070. | Opt( setWaitForKeypress, "never|start|exit|both" )
  8071. ["--wait-for-keypress"]
  8072. ( "waits for a keypress before exiting" )
  8073. | Opt( config.benchmarkSamples, "samples" )
  8074. ["--benchmark-samples"]
  8075. ( "number of samples to collect (default: 100)" )
  8076. | Opt( config.benchmarkResamples, "resamples" )
  8077. ["--benchmark-resamples"]
  8078. ( "number of resamples for the bootstrap (default: 100000)" )
  8079. | Opt( config.benchmarkConfidenceInterval, "confidence interval" )
  8080. ["--benchmark-confidence-interval"]
  8081. ( "confidence interval for the bootstrap (between 0 and 1, default: 0.95)" )
  8082. | Opt( config.benchmarkNoAnalysis )
  8083. ["--benchmark-no-analysis"]
  8084. ( "perform only measurements; do not perform any analysis" )
  8085. | Opt( config.benchmarkWarmupTime, "benchmarkWarmupTime" )
  8086. ["--benchmark-warmup-time"]
  8087. ( "amount of time in milliseconds spent on warming up each test (default: 100)" )
  8088. | Arg( config.testsOrTags, "test name|pattern|tags" )
  8089. ( "which test or tests to use" );
  8090. return cli;
  8091. }
  8092. } // end namespace Catch
  8093. // end catch_commandline.cpp
  8094. // start catch_common.cpp
  8095. #include <cstring>
  8096. #include <ostream>
  8097. namespace Catch {
  8098. bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const noexcept {
  8099. return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0);
  8100. }
  8101. bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const noexcept {
  8102. // We can assume that the same file will usually have the same pointer.
  8103. // Thus, if the pointers are the same, there is no point in calling the strcmp
  8104. return line < other.line || ( line == other.line && file != other.file && (std::strcmp(file, other.file) < 0));
  8105. }
  8106. std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) {
  8107. #ifndef __GNUG__
  8108. os << info.file << '(' << info.line << ')';
  8109. #else
  8110. os << info.file << ':' << info.line;
  8111. #endif
  8112. return os;
  8113. }
  8114. std::string StreamEndStop::operator+() const {
  8115. return std::string();
  8116. }
  8117. NonCopyable::NonCopyable() = default;
  8118. NonCopyable::~NonCopyable() = default;
  8119. }
  8120. // end catch_common.cpp
  8121. // start catch_config.cpp
  8122. namespace Catch {
  8123. Config::Config( ConfigData const& data )
  8124. : m_data( data ),
  8125. m_stream( openStream() )
  8126. {
  8127. // We need to trim filter specs to avoid trouble with superfluous
  8128. // whitespace (esp. important for bdd macros, as those are manually
  8129. // aligned with whitespace).
  8130. for (auto& elem : m_data.testsOrTags) {
  8131. elem = trim(elem);
  8132. }
  8133. for (auto& elem : m_data.sectionsToRun) {
  8134. elem = trim(elem);
  8135. }
  8136. TestSpecParser parser(ITagAliasRegistry::get());
  8137. if (!m_data.testsOrTags.empty()) {
  8138. m_hasTestFilters = true;
  8139. for (auto const& testOrTags : m_data.testsOrTags) {
  8140. parser.parse(testOrTags);
  8141. }
  8142. }
  8143. m_testSpec = parser.testSpec();
  8144. }
  8145. std::string const& Config::getFilename() const {
  8146. return m_data.outputFilename ;
  8147. }
  8148. bool Config::listTests() const { return m_data.listTests; }
  8149. bool Config::listTestNamesOnly() const { return m_data.listTestNamesOnly; }
  8150. bool Config::listTags() const { return m_data.listTags; }
  8151. bool Config::listReporters() const { return m_data.listReporters; }
  8152. std::string Config::getProcessName() const { return m_data.processName; }
  8153. std::string const& Config::getReporterName() const { return m_data.reporterName; }
  8154. std::vector<std::string> const& Config::getTestsOrTags() const { return m_data.testsOrTags; }
  8155. std::vector<std::string> const& Config::getSectionsToRun() const { return m_data.sectionsToRun; }
  8156. TestSpec const& Config::testSpec() const { return m_testSpec; }
  8157. bool Config::hasTestFilters() const { return m_hasTestFilters; }
  8158. bool Config::showHelp() const { return m_data.showHelp; }
  8159. // IConfig interface
  8160. bool Config::allowThrows() const { return !m_data.noThrow; }
  8161. std::ostream& Config::stream() const { return m_stream->stream(); }
  8162. std::string Config::name() const { return m_data.name.empty() ? m_data.processName : m_data.name; }
  8163. bool Config::includeSuccessfulResults() const { return m_data.showSuccessfulTests; }
  8164. bool Config::warnAboutMissingAssertions() const { return !!(m_data.warnings & WarnAbout::NoAssertions); }
  8165. bool Config::warnAboutNoTests() const { return !!(m_data.warnings & WarnAbout::NoTests); }
  8166. ShowDurations::OrNot Config::showDurations() const { return m_data.showDurations; }
  8167. double Config::minDuration() const { return m_data.minDuration; }
  8168. RunTests::InWhatOrder Config::runOrder() const { return m_data.runOrder; }
  8169. unsigned int Config::rngSeed() const { return m_data.rngSeed; }
  8170. UseColour::YesOrNo Config::useColour() const { return m_data.useColour; }
  8171. bool Config::shouldDebugBreak() const { return m_data.shouldDebugBreak; }
  8172. int Config::abortAfter() const { return m_data.abortAfter; }
  8173. bool Config::showInvisibles() const { return m_data.showInvisibles; }
  8174. Verbosity Config::verbosity() const { return m_data.verbosity; }
  8175. bool Config::benchmarkNoAnalysis() const { return m_data.benchmarkNoAnalysis; }
  8176. int Config::benchmarkSamples() const { return m_data.benchmarkSamples; }
  8177. double Config::benchmarkConfidenceInterval() const { return m_data.benchmarkConfidenceInterval; }
  8178. unsigned int Config::benchmarkResamples() const { return m_data.benchmarkResamples; }
  8179. std::chrono::milliseconds Config::benchmarkWarmupTime() const { return std::chrono::milliseconds(m_data.benchmarkWarmupTime); }
  8180. IStream const* Config::openStream() {
  8181. return Catch::makeStream(m_data.outputFilename);
  8182. }
  8183. } // end namespace Catch
  8184. // end catch_config.cpp
  8185. // start catch_console_colour.cpp
  8186. #if defined(__clang__)
  8187. # pragma clang diagnostic push
  8188. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  8189. #endif
  8190. // start catch_errno_guard.h
  8191. namespace Catch {
  8192. class ErrnoGuard {
  8193. public:
  8194. ErrnoGuard();
  8195. ~ErrnoGuard();
  8196. private:
  8197. int m_oldErrno;
  8198. };
  8199. }
  8200. // end catch_errno_guard.h
  8201. // start catch_windows_h_proxy.h
  8202. #if defined(CATCH_PLATFORM_WINDOWS)
  8203. #if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX)
  8204. # define CATCH_DEFINED_NOMINMAX
  8205. # define NOMINMAX
  8206. #endif
  8207. #if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN)
  8208. # define CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  8209. # define WIN32_LEAN_AND_MEAN
  8210. #endif
  8211. #ifdef __AFXDLL
  8212. #include <AfxWin.h>
  8213. #else
  8214. #include <windows.h>
  8215. #endif
  8216. #ifdef CATCH_DEFINED_NOMINMAX
  8217. # undef NOMINMAX
  8218. #endif
  8219. #ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  8220. # undef WIN32_LEAN_AND_MEAN
  8221. #endif
  8222. #endif // defined(CATCH_PLATFORM_WINDOWS)
  8223. // end catch_windows_h_proxy.h
  8224. #include <sstream>
  8225. namespace Catch {
  8226. namespace {
  8227. struct IColourImpl {
  8228. virtual ~IColourImpl() = default;
  8229. virtual void use( Colour::Code _colourCode ) = 0;
  8230. };
  8231. struct NoColourImpl : IColourImpl {
  8232. void use( Colour::Code ) override {}
  8233. static IColourImpl* instance() {
  8234. static NoColourImpl s_instance;
  8235. return &s_instance;
  8236. }
  8237. };
  8238. } // anon namespace
  8239. } // namespace Catch
  8240. #if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI )
  8241. # ifdef CATCH_PLATFORM_WINDOWS
  8242. # define CATCH_CONFIG_COLOUR_WINDOWS
  8243. # else
  8244. # define CATCH_CONFIG_COLOUR_ANSI
  8245. # endif
  8246. #endif
  8247. #if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) /////////////////////////////////////////
  8248. namespace Catch {
  8249. namespace {
  8250. class Win32ColourImpl : public IColourImpl {
  8251. public:
  8252. Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) )
  8253. {
  8254. CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
  8255. GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo );
  8256. originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY );
  8257. originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY );
  8258. }
  8259. void use( Colour::Code _colourCode ) override {
  8260. switch( _colourCode ) {
  8261. case Colour::None: return setTextAttribute( originalForegroundAttributes );
  8262. case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  8263. case Colour::Red: return setTextAttribute( FOREGROUND_RED );
  8264. case Colour::Green: return setTextAttribute( FOREGROUND_GREEN );
  8265. case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE );
  8266. case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN );
  8267. case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN );
  8268. case Colour::Grey: return setTextAttribute( 0 );
  8269. case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY );
  8270. case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED );
  8271. case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN );
  8272. case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  8273. case Colour::BrightYellow: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN );
  8274. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  8275. default:
  8276. CATCH_ERROR( "Unknown colour requested" );
  8277. }
  8278. }
  8279. private:
  8280. void setTextAttribute( WORD _textAttribute ) {
  8281. SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes );
  8282. }
  8283. HANDLE stdoutHandle;
  8284. WORD originalForegroundAttributes;
  8285. WORD originalBackgroundAttributes;
  8286. };
  8287. IColourImpl* platformColourInstance() {
  8288. static Win32ColourImpl s_instance;
  8289. IConfigPtr config = getCurrentContext().getConfig();
  8290. UseColour::YesOrNo colourMode = config
  8291. ? config->useColour()
  8292. : UseColour::Auto;
  8293. if( colourMode == UseColour::Auto )
  8294. colourMode = UseColour::Yes;
  8295. return colourMode == UseColour::Yes
  8296. ? &s_instance
  8297. : NoColourImpl::instance();
  8298. }
  8299. } // end anon namespace
  8300. } // end namespace Catch
  8301. #elif defined( CATCH_CONFIG_COLOUR_ANSI ) //////////////////////////////////////
  8302. #include <unistd.h>
  8303. namespace Catch {
  8304. namespace {
  8305. // use POSIX/ ANSI console terminal codes
  8306. // Thanks to Adam Strzelecki for original contribution
  8307. // (http://github.com/nanoant)
  8308. // https://github.com/philsquared/Catch/pull/131
  8309. class PosixColourImpl : public IColourImpl {
  8310. public:
  8311. void use( Colour::Code _colourCode ) override {
  8312. switch( _colourCode ) {
  8313. case Colour::None:
  8314. case Colour::White: return setColour( "[0m" );
  8315. case Colour::Red: return setColour( "[0;31m" );
  8316. case Colour::Green: return setColour( "[0;32m" );
  8317. case Colour::Blue: return setColour( "[0;34m" );
  8318. case Colour::Cyan: return setColour( "[0;36m" );
  8319. case Colour::Yellow: return setColour( "[0;33m" );
  8320. case Colour::Grey: return setColour( "[1;30m" );
  8321. case Colour::LightGrey: return setColour( "[0;37m" );
  8322. case Colour::BrightRed: return setColour( "[1;31m" );
  8323. case Colour::BrightGreen: return setColour( "[1;32m" );
  8324. case Colour::BrightWhite: return setColour( "[1;37m" );
  8325. case Colour::BrightYellow: return setColour( "[1;33m" );
  8326. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  8327. default: CATCH_INTERNAL_ERROR( "Unknown colour requested" );
  8328. }
  8329. }
  8330. static IColourImpl* instance() {
  8331. static PosixColourImpl s_instance;
  8332. return &s_instance;
  8333. }
  8334. private:
  8335. void setColour( const char* _escapeCode ) {
  8336. getCurrentContext().getConfig()->stream()
  8337. << '\033' << _escapeCode;
  8338. }
  8339. };
  8340. bool useColourOnPlatform() {
  8341. return
  8342. #if defined(CATCH_PLATFORM_MAC) || defined(CATCH_PLATFORM_IPHONE)
  8343. !isDebuggerActive() &&
  8344. #endif
  8345. #if !(defined(__DJGPP__) && defined(__STRICT_ANSI__))
  8346. isatty(STDOUT_FILENO)
  8347. #else
  8348. false
  8349. #endif
  8350. ;
  8351. }
  8352. IColourImpl* platformColourInstance() {
  8353. ErrnoGuard guard;
  8354. IConfigPtr config = getCurrentContext().getConfig();
  8355. UseColour::YesOrNo colourMode = config
  8356. ? config->useColour()
  8357. : UseColour::Auto;
  8358. if( colourMode == UseColour::Auto )
  8359. colourMode = useColourOnPlatform()
  8360. ? UseColour::Yes
  8361. : UseColour::No;
  8362. return colourMode == UseColour::Yes
  8363. ? PosixColourImpl::instance()
  8364. : NoColourImpl::instance();
  8365. }
  8366. } // end anon namespace
  8367. } // end namespace Catch
  8368. #else // not Windows or ANSI ///////////////////////////////////////////////
  8369. namespace Catch {
  8370. static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); }
  8371. } // end namespace Catch
  8372. #endif // Windows/ ANSI/ None
  8373. namespace Catch {
  8374. Colour::Colour( Code _colourCode ) { use( _colourCode ); }
  8375. Colour::Colour( Colour&& other ) noexcept {
  8376. m_moved = other.m_moved;
  8377. other.m_moved = true;
  8378. }
  8379. Colour& Colour::operator=( Colour&& other ) noexcept {
  8380. m_moved = other.m_moved;
  8381. other.m_moved = true;
  8382. return *this;
  8383. }
  8384. Colour::~Colour(){ if( !m_moved ) use( None ); }
  8385. void Colour::use( Code _colourCode ) {
  8386. static IColourImpl* impl = platformColourInstance();
  8387. // Strictly speaking, this cannot possibly happen.
  8388. // However, under some conditions it does happen (see #1626),
  8389. // and this change is small enough that we can let practicality
  8390. // triumph over purity in this case.
  8391. if (impl != nullptr) {
  8392. impl->use( _colourCode );
  8393. }
  8394. }
  8395. std::ostream& operator << ( std::ostream& os, Colour const& ) {
  8396. return os;
  8397. }
  8398. } // end namespace Catch
  8399. #if defined(__clang__)
  8400. # pragma clang diagnostic pop
  8401. #endif
  8402. // end catch_console_colour.cpp
  8403. // start catch_context.cpp
  8404. namespace Catch {
  8405. class Context : public IMutableContext, NonCopyable {
  8406. public: // IContext
  8407. IResultCapture* getResultCapture() override {
  8408. return m_resultCapture;
  8409. }
  8410. IRunner* getRunner() override {
  8411. return m_runner;
  8412. }
  8413. IConfigPtr const& getConfig() const override {
  8414. return m_config;
  8415. }
  8416. ~Context() override;
  8417. public: // IMutableContext
  8418. void setResultCapture( IResultCapture* resultCapture ) override {
  8419. m_resultCapture = resultCapture;
  8420. }
  8421. void setRunner( IRunner* runner ) override {
  8422. m_runner = runner;
  8423. }
  8424. void setConfig( IConfigPtr const& config ) override {
  8425. m_config = config;
  8426. }
  8427. friend IMutableContext& getCurrentMutableContext();
  8428. private:
  8429. IConfigPtr m_config;
  8430. IRunner* m_runner = nullptr;
  8431. IResultCapture* m_resultCapture = nullptr;
  8432. };
  8433. IMutableContext *IMutableContext::currentContext = nullptr;
  8434. void IMutableContext::createContext()
  8435. {
  8436. currentContext = new Context();
  8437. }
  8438. void cleanUpContext() {
  8439. delete IMutableContext::currentContext;
  8440. IMutableContext::currentContext = nullptr;
  8441. }
  8442. IContext::~IContext() = default;
  8443. IMutableContext::~IMutableContext() = default;
  8444. Context::~Context() = default;
  8445. SimplePcg32& rng() {
  8446. static SimplePcg32 s_rng;
  8447. return s_rng;
  8448. }
  8449. }
  8450. // end catch_context.cpp
  8451. // start catch_debug_console.cpp
  8452. // start catch_debug_console.h
  8453. #include <string>
  8454. namespace Catch {
  8455. void writeToDebugConsole( std::string const& text );
  8456. }
  8457. // end catch_debug_console.h
  8458. #if defined(CATCH_CONFIG_ANDROID_LOGWRITE)
  8459. #include <android/log.h>
  8460. namespace Catch {
  8461. void writeToDebugConsole( std::string const& text ) {
  8462. __android_log_write( ANDROID_LOG_DEBUG, "Catch", text.c_str() );
  8463. }
  8464. }
  8465. #elif defined(CATCH_PLATFORM_WINDOWS)
  8466. namespace Catch {
  8467. void writeToDebugConsole( std::string const& text ) {
  8468. ::OutputDebugStringA( text.c_str() );
  8469. }
  8470. }
  8471. #else
  8472. namespace Catch {
  8473. void writeToDebugConsole( std::string const& text ) {
  8474. // !TBD: Need a version for Mac/ XCode and other IDEs
  8475. Catch::cout() << text;
  8476. }
  8477. }
  8478. #endif // Platform
  8479. // end catch_debug_console.cpp
  8480. // start catch_debugger.cpp
  8481. #if defined(CATCH_PLATFORM_MAC) || defined(CATCH_PLATFORM_IPHONE)
  8482. # include <cassert>
  8483. # include <sys/types.h>
  8484. # include <unistd.h>
  8485. # include <cstddef>
  8486. # include <ostream>
  8487. #ifdef __apple_build_version__
  8488. // These headers will only compile with AppleClang (XCode)
  8489. // For other compilers (Clang, GCC, ... ) we need to exclude them
  8490. # include <sys/sysctl.h>
  8491. #endif
  8492. namespace Catch {
  8493. #ifdef __apple_build_version__
  8494. // The following function is taken directly from the following technical note:
  8495. // https://developer.apple.com/library/archive/qa/qa1361/_index.html
  8496. // Returns true if the current process is being debugged (either
  8497. // running under the debugger or has a debugger attached post facto).
  8498. bool isDebuggerActive(){
  8499. int mib[4];
  8500. struct kinfo_proc info;
  8501. std::size_t size;
  8502. // Initialize the flags so that, if sysctl fails for some bizarre
  8503. // reason, we get a predictable result.
  8504. info.kp_proc.p_flag = 0;
  8505. // Initialize mib, which tells sysctl the info we want, in this case
  8506. // we're looking for information about a specific process ID.
  8507. mib[0] = CTL_KERN;
  8508. mib[1] = KERN_PROC;
  8509. mib[2] = KERN_PROC_PID;
  8510. mib[3] = getpid();
  8511. // Call sysctl.
  8512. size = sizeof(info);
  8513. if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0) != 0 ) {
  8514. Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl;
  8515. return false;
  8516. }
  8517. // We're being debugged if the P_TRACED flag is set.
  8518. return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
  8519. }
  8520. #else
  8521. bool isDebuggerActive() {
  8522. // We need to find another way to determine this for non-appleclang compilers on macOS
  8523. return false;
  8524. }
  8525. #endif
  8526. } // namespace Catch
  8527. #elif defined(CATCH_PLATFORM_LINUX)
  8528. #include <fstream>
  8529. #include <string>
  8530. namespace Catch{
  8531. // The standard POSIX way of detecting a debugger is to attempt to
  8532. // ptrace() the process, but this needs to be done from a child and not
  8533. // this process itself to still allow attaching to this process later
  8534. // if wanted, so is rather heavy. Under Linux we have the PID of the
  8535. // "debugger" (which doesn't need to be gdb, of course, it could also
  8536. // be strace, for example) in /proc/$PID/status, so just get it from
  8537. // there instead.
  8538. bool isDebuggerActive(){
  8539. // Libstdc++ has a bug, where std::ifstream sets errno to 0
  8540. // This way our users can properly assert over errno values
  8541. ErrnoGuard guard;
  8542. std::ifstream in("/proc/self/status");
  8543. for( std::string line; std::getline(in, line); ) {
  8544. static const int PREFIX_LEN = 11;
  8545. if( line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0 ) {
  8546. // We're traced if the PID is not 0 and no other PID starts
  8547. // with 0 digit, so it's enough to check for just a single
  8548. // character.
  8549. return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0';
  8550. }
  8551. }
  8552. return false;
  8553. }
  8554. } // namespace Catch
  8555. #elif defined(_MSC_VER)
  8556. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  8557. namespace Catch {
  8558. bool isDebuggerActive() {
  8559. return IsDebuggerPresent() != 0;
  8560. }
  8561. }
  8562. #elif defined(__MINGW32__)
  8563. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  8564. namespace Catch {
  8565. bool isDebuggerActive() {
  8566. return IsDebuggerPresent() != 0;
  8567. }
  8568. }
  8569. #else
  8570. namespace Catch {
  8571. bool isDebuggerActive() { return false; }
  8572. }
  8573. #endif // Platform
  8574. // end catch_debugger.cpp
  8575. // start catch_decomposer.cpp
  8576. namespace Catch {
  8577. ITransientExpression::~ITransientExpression() = default;
  8578. void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs ) {
  8579. if( lhs.size() + rhs.size() < 40 &&
  8580. lhs.find('\n') == std::string::npos &&
  8581. rhs.find('\n') == std::string::npos )
  8582. os << lhs << " " << op << " " << rhs;
  8583. else
  8584. os << lhs << "\n" << op << "\n" << rhs;
  8585. }
  8586. }
  8587. // end catch_decomposer.cpp
  8588. // start catch_enforce.cpp
  8589. #include <stdexcept>
  8590. namespace Catch {
  8591. #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS_CUSTOM_HANDLER)
  8592. [[noreturn]]
  8593. void throw_exception(std::exception const& e) {
  8594. Catch::cerr() << "Catch will terminate because it needed to throw an exception.\n"
  8595. << "The message was: " << e.what() << '\n';
  8596. std::terminate();
  8597. }
  8598. #endif
  8599. [[noreturn]]
  8600. void throw_logic_error(std::string const& msg) {
  8601. throw_exception(std::logic_error(msg));
  8602. }
  8603. [[noreturn]]
  8604. void throw_domain_error(std::string const& msg) {
  8605. throw_exception(std::domain_error(msg));
  8606. }
  8607. [[noreturn]]
  8608. void throw_runtime_error(std::string const& msg) {
  8609. throw_exception(std::runtime_error(msg));
  8610. }
  8611. } // namespace Catch;
  8612. // end catch_enforce.cpp
  8613. // start catch_enum_values_registry.cpp
  8614. // start catch_enum_values_registry.h
  8615. #include <vector>
  8616. #include <memory>
  8617. namespace Catch {
  8618. namespace Detail {
  8619. std::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int> const& values );
  8620. class EnumValuesRegistry : public IMutableEnumValuesRegistry {
  8621. std::vector<std::unique_ptr<EnumInfo>> m_enumInfos;
  8622. EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::vector<int> const& values) override;
  8623. };
  8624. std::vector<StringRef> parseEnums( StringRef enums );
  8625. } // Detail
  8626. } // Catch
  8627. // end catch_enum_values_registry.h
  8628. #include <map>
  8629. #include <cassert>
  8630. namespace Catch {
  8631. IMutableEnumValuesRegistry::~IMutableEnumValuesRegistry() {}
  8632. namespace Detail {
  8633. namespace {
  8634. // Extracts the actual name part of an enum instance
  8635. // In other words, it returns the Blue part of Bikeshed::Colour::Blue
  8636. StringRef extractInstanceName(StringRef enumInstance) {
  8637. // Find last occurrence of ":"
  8638. size_t name_start = enumInstance.size();
  8639. while (name_start > 0 && enumInstance[name_start - 1] != ':') {
  8640. --name_start;
  8641. }
  8642. return enumInstance.substr(name_start, enumInstance.size() - name_start);
  8643. }
  8644. }
  8645. std::vector<StringRef> parseEnums( StringRef enums ) {
  8646. auto enumValues = splitStringRef( enums, ',' );
  8647. std::vector<StringRef> parsed;
  8648. parsed.reserve( enumValues.size() );
  8649. for( auto const& enumValue : enumValues ) {
  8650. parsed.push_back(trim(extractInstanceName(enumValue)));
  8651. }
  8652. return parsed;
  8653. }
  8654. EnumInfo::~EnumInfo() {}
  8655. StringRef EnumInfo::lookup( int value ) const {
  8656. for( auto const& valueToName : m_values ) {
  8657. if( valueToName.first == value )
  8658. return valueToName.second;
  8659. }
  8660. return "{** unexpected enum value **}"_sr;
  8661. }
  8662. std::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ) {
  8663. std::unique_ptr<EnumInfo> enumInfo( new EnumInfo );
  8664. enumInfo->m_name = enumName;
  8665. enumInfo->m_values.reserve( values.size() );
  8666. const auto valueNames = Catch::Detail::parseEnums( allValueNames );
  8667. assert( valueNames.size() == values.size() );
  8668. std::size_t i = 0;
  8669. for( auto value : values )
  8670. enumInfo->m_values.emplace_back(value, valueNames[i++]);
  8671. return enumInfo;
  8672. }
  8673. EnumInfo const& EnumValuesRegistry::registerEnum( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ) {
  8674. m_enumInfos.push_back(makeEnumInfo(enumName, allValueNames, values));
  8675. return *m_enumInfos.back();
  8676. }
  8677. } // Detail
  8678. } // Catch
  8679. // end catch_enum_values_registry.cpp
  8680. // start catch_errno_guard.cpp
  8681. #include <cerrno>
  8682. namespace Catch {
  8683. ErrnoGuard::ErrnoGuard():m_oldErrno(errno){}
  8684. ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; }
  8685. }
  8686. // end catch_errno_guard.cpp
  8687. // start catch_exception_translator_registry.cpp
  8688. // start catch_exception_translator_registry.h
  8689. #include <vector>
  8690. #include <string>
  8691. #include <memory>
  8692. namespace Catch {
  8693. class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry {
  8694. public:
  8695. ~ExceptionTranslatorRegistry();
  8696. virtual void registerTranslator( const IExceptionTranslator* translator );
  8697. std::string translateActiveException() const override;
  8698. std::string tryTranslators() const;
  8699. private:
  8700. std::vector<std::unique_ptr<IExceptionTranslator const>> m_translators;
  8701. };
  8702. }
  8703. // end catch_exception_translator_registry.h
  8704. #ifdef __OBJC__
  8705. #import "Foundation/Foundation.h"
  8706. #endif
  8707. namespace Catch {
  8708. ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {
  8709. }
  8710. void ExceptionTranslatorRegistry::registerTranslator( const IExceptionTranslator* translator ) {
  8711. m_translators.push_back( std::unique_ptr<const IExceptionTranslator>( translator ) );
  8712. }
  8713. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  8714. std::string ExceptionTranslatorRegistry::translateActiveException() const {
  8715. try {
  8716. #ifdef __OBJC__
  8717. // In Objective-C try objective-c exceptions first
  8718. @try {
  8719. return tryTranslators();
  8720. }
  8721. @catch (NSException *exception) {
  8722. return Catch::Detail::stringify( [exception description] );
  8723. }
  8724. #else
  8725. // Compiling a mixed mode project with MSVC means that CLR
  8726. // exceptions will be caught in (...) as well. However, these
  8727. // do not fill-in std::current_exception and thus lead to crash
  8728. // when attempting rethrow.
  8729. // /EHa switch also causes structured exceptions to be caught
  8730. // here, but they fill-in current_exception properly, so
  8731. // at worst the output should be a little weird, instead of
  8732. // causing a crash.
  8733. if (std::current_exception() == nullptr) {
  8734. return "Non C++ exception. Possibly a CLR exception.";
  8735. }
  8736. return tryTranslators();
  8737. #endif
  8738. }
  8739. catch( TestFailureException& ) {
  8740. std::rethrow_exception(std::current_exception());
  8741. }
  8742. catch( std::exception& ex ) {
  8743. return ex.what();
  8744. }
  8745. catch( std::string& msg ) {
  8746. return msg;
  8747. }
  8748. catch( const char* msg ) {
  8749. return msg;
  8750. }
  8751. catch(...) {
  8752. return "Unknown exception";
  8753. }
  8754. }
  8755. std::string ExceptionTranslatorRegistry::tryTranslators() const {
  8756. if (m_translators.empty()) {
  8757. std::rethrow_exception(std::current_exception());
  8758. } else {
  8759. return m_translators[0]->translate(m_translators.begin() + 1, m_translators.end());
  8760. }
  8761. }
  8762. #else // ^^ Exceptions are enabled // Exceptions are disabled vv
  8763. std::string ExceptionTranslatorRegistry::translateActiveException() const {
  8764. CATCH_INTERNAL_ERROR("Attempted to translate active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
  8765. }
  8766. std::string ExceptionTranslatorRegistry::tryTranslators() const {
  8767. CATCH_INTERNAL_ERROR("Attempted to use exception translators under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
  8768. }
  8769. #endif
  8770. }
  8771. // end catch_exception_translator_registry.cpp
  8772. // start catch_fatal_condition.cpp
  8773. #include <algorithm>
  8774. #if !defined( CATCH_CONFIG_WINDOWS_SEH ) && !defined( CATCH_CONFIG_POSIX_SIGNALS )
  8775. namespace Catch {
  8776. // If neither SEH nor signal handling is required, the handler impls
  8777. // do not have to do anything, and can be empty.
  8778. void FatalConditionHandler::engage_platform() {}
  8779. void FatalConditionHandler::disengage_platform() {}
  8780. FatalConditionHandler::FatalConditionHandler() = default;
  8781. FatalConditionHandler::~FatalConditionHandler() = default;
  8782. } // end namespace Catch
  8783. #endif // !CATCH_CONFIG_WINDOWS_SEH && !CATCH_CONFIG_POSIX_SIGNALS
  8784. #if defined( CATCH_CONFIG_WINDOWS_SEH ) && defined( CATCH_CONFIG_POSIX_SIGNALS )
  8785. #error "Inconsistent configuration: Windows' SEH handling and POSIX signals cannot be enabled at the same time"
  8786. #endif // CATCH_CONFIG_WINDOWS_SEH && CATCH_CONFIG_POSIX_SIGNALS
  8787. #if defined( CATCH_CONFIG_WINDOWS_SEH ) || defined( CATCH_CONFIG_POSIX_SIGNALS )
  8788. namespace {
  8789. //! Signals fatal error message to the run context
  8790. void reportFatal( char const * const message ) {
  8791. Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition( message );
  8792. }
  8793. //! Minimal size Catch2 needs for its own fatal error handling.
  8794. //! Picked anecdotally, so it might not be sufficient on all
  8795. //! platforms, and for all configurations.
  8796. constexpr std::size_t minStackSizeForErrors = 32 * 1024;
  8797. } // end unnamed namespace
  8798. #endif // CATCH_CONFIG_WINDOWS_SEH || CATCH_CONFIG_POSIX_SIGNALS
  8799. #if defined( CATCH_CONFIG_WINDOWS_SEH )
  8800. namespace Catch {
  8801. struct SignalDefs { DWORD id; const char* name; };
  8802. // There is no 1-1 mapping between signals and windows exceptions.
  8803. // Windows can easily distinguish between SO and SigSegV,
  8804. // but SigInt, SigTerm, etc are handled differently.
  8805. static SignalDefs signalDefs[] = {
  8806. { static_cast<DWORD>(EXCEPTION_ILLEGAL_INSTRUCTION), "SIGILL - Illegal instruction signal" },
  8807. { static_cast<DWORD>(EXCEPTION_STACK_OVERFLOW), "SIGSEGV - Stack overflow" },
  8808. { static_cast<DWORD>(EXCEPTION_ACCESS_VIOLATION), "SIGSEGV - Segmentation violation signal" },
  8809. { static_cast<DWORD>(EXCEPTION_INT_DIVIDE_BY_ZERO), "Divide by zero error" },
  8810. };
  8811. static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {
  8812. for (auto const& def : signalDefs) {
  8813. if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) {
  8814. reportFatal(def.name);
  8815. }
  8816. }
  8817. // If its not an exception we care about, pass it along.
  8818. // This stops us from eating debugger breaks etc.
  8819. return EXCEPTION_CONTINUE_SEARCH;
  8820. }
  8821. // Since we do not support multiple instantiations, we put these
  8822. // into global variables and rely on cleaning them up in outlined
  8823. // constructors/destructors
  8824. static PVOID exceptionHandlerHandle = nullptr;
  8825. // For MSVC, we reserve part of the stack memory for handling
  8826. // memory overflow structured exception.
  8827. FatalConditionHandler::FatalConditionHandler() {
  8828. ULONG guaranteeSize = static_cast<ULONG>(minStackSizeForErrors);
  8829. if (!SetThreadStackGuarantee(&guaranteeSize)) {
  8830. // We do not want to fully error out, because needing
  8831. // the stack reserve should be rare enough anyway.
  8832. Catch::cerr()
  8833. << "Failed to reserve piece of stack."
  8834. << " Stack overflows will not be reported successfully.";
  8835. }
  8836. }
  8837. // We do not attempt to unset the stack guarantee, because
  8838. // Windows does not support lowering the stack size guarantee.
  8839. FatalConditionHandler::~FatalConditionHandler() = default;
  8840. void FatalConditionHandler::engage_platform() {
  8841. // Register as first handler in current chain
  8842. exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);
  8843. if (!exceptionHandlerHandle) {
  8844. CATCH_RUNTIME_ERROR("Could not register vectored exception handler");
  8845. }
  8846. }
  8847. void FatalConditionHandler::disengage_platform() {
  8848. if (!RemoveVectoredExceptionHandler(exceptionHandlerHandle)) {
  8849. CATCH_RUNTIME_ERROR("Could not unregister vectored exception handler");
  8850. }
  8851. exceptionHandlerHandle = nullptr;
  8852. }
  8853. } // end namespace Catch
  8854. #endif // CATCH_CONFIG_WINDOWS_SEH
  8855. #if defined( CATCH_CONFIG_POSIX_SIGNALS )
  8856. #include <signal.h>
  8857. namespace Catch {
  8858. struct SignalDefs {
  8859. int id;
  8860. const char* name;
  8861. };
  8862. static SignalDefs signalDefs[] = {
  8863. { SIGINT, "SIGINT - Terminal interrupt signal" },
  8864. { SIGILL, "SIGILL - Illegal instruction signal" },
  8865. { SIGFPE, "SIGFPE - Floating point error signal" },
  8866. { SIGSEGV, "SIGSEGV - Segmentation violation signal" },
  8867. { SIGTERM, "SIGTERM - Termination request signal" },
  8868. { SIGABRT, "SIGABRT - Abort (abnormal termination) signal" }
  8869. };
  8870. // Older GCCs trigger -Wmissing-field-initializers for T foo = {}
  8871. // which is zero initialization, but not explicit. We want to avoid
  8872. // that.
  8873. #if defined(__GNUC__)
  8874. # pragma GCC diagnostic push
  8875. # pragma GCC diagnostic ignored "-Wmissing-field-initializers"
  8876. #endif
  8877. static char* altStackMem = nullptr;
  8878. static std::size_t altStackSize = 0;
  8879. static stack_t oldSigStack{};
  8880. static struct sigaction oldSigActions[sizeof(signalDefs) / sizeof(SignalDefs)]{};
  8881. static void restorePreviousSignalHandlers() {
  8882. // We set signal handlers back to the previous ones. Hopefully
  8883. // nobody overwrote them in the meantime, and doesn't expect
  8884. // their signal handlers to live past ours given that they
  8885. // installed them after ours..
  8886. for (std::size_t i = 0; i < sizeof(signalDefs) / sizeof(SignalDefs); ++i) {
  8887. sigaction(signalDefs[i].id, &oldSigActions[i], nullptr);
  8888. }
  8889. // Return the old stack
  8890. sigaltstack(&oldSigStack, nullptr);
  8891. }
  8892. static void handleSignal( int sig ) {
  8893. char const * name = "<unknown signal>";
  8894. for (auto const& def : signalDefs) {
  8895. if (sig == def.id) {
  8896. name = def.name;
  8897. break;
  8898. }
  8899. }
  8900. // We need to restore previous signal handlers and let them do
  8901. // their thing, so that the users can have the debugger break
  8902. // when a signal is raised, and so on.
  8903. restorePreviousSignalHandlers();
  8904. reportFatal( name );
  8905. raise( sig );
  8906. }
  8907. FatalConditionHandler::FatalConditionHandler() {
  8908. assert(!altStackMem && "Cannot initialize POSIX signal handler when one already exists");
  8909. if (altStackSize == 0) {
  8910. altStackSize = std::max(static_cast<size_t>(SIGSTKSZ), minStackSizeForErrors);
  8911. }
  8912. altStackMem = new char[altStackSize]();
  8913. }
  8914. FatalConditionHandler::~FatalConditionHandler() {
  8915. delete[] altStackMem;
  8916. // We signal that another instance can be constructed by zeroing
  8917. // out the pointer.
  8918. altStackMem = nullptr;
  8919. }
  8920. void FatalConditionHandler::engage_platform() {
  8921. stack_t sigStack;
  8922. sigStack.ss_sp = altStackMem;
  8923. sigStack.ss_size = altStackSize;
  8924. sigStack.ss_flags = 0;
  8925. sigaltstack(&sigStack, &oldSigStack);
  8926. struct sigaction sa = { };
  8927. sa.sa_handler = handleSignal;
  8928. sa.sa_flags = SA_ONSTACK;
  8929. for (std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i) {
  8930. sigaction(signalDefs[i].id, &sa, &oldSigActions[i]);
  8931. }
  8932. }
  8933. #if defined(__GNUC__)
  8934. # pragma GCC diagnostic pop
  8935. #endif
  8936. void FatalConditionHandler::disengage_platform() {
  8937. restorePreviousSignalHandlers();
  8938. }
  8939. } // end namespace Catch
  8940. #endif // CATCH_CONFIG_POSIX_SIGNALS
  8941. // end catch_fatal_condition.cpp
  8942. // start catch_generators.cpp
  8943. #include <limits>
  8944. #include <set>
  8945. namespace Catch {
  8946. IGeneratorTracker::~IGeneratorTracker() {}
  8947. const char* GeneratorException::what() const noexcept {
  8948. return m_msg;
  8949. }
  8950. namespace Generators {
  8951. GeneratorUntypedBase::~GeneratorUntypedBase() {}
  8952. auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
  8953. return getResultCapture().acquireGeneratorTracker( generatorName, lineInfo );
  8954. }
  8955. } // namespace Generators
  8956. } // namespace Catch
  8957. // end catch_generators.cpp
  8958. // start catch_interfaces_capture.cpp
  8959. namespace Catch {
  8960. IResultCapture::~IResultCapture() = default;
  8961. }
  8962. // end catch_interfaces_capture.cpp
  8963. // start catch_interfaces_config.cpp
  8964. namespace Catch {
  8965. IConfig::~IConfig() = default;
  8966. }
  8967. // end catch_interfaces_config.cpp
  8968. // start catch_interfaces_exception.cpp
  8969. namespace Catch {
  8970. IExceptionTranslator::~IExceptionTranslator() = default;
  8971. IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() = default;
  8972. }
  8973. // end catch_interfaces_exception.cpp
  8974. // start catch_interfaces_registry_hub.cpp
  8975. namespace Catch {
  8976. IRegistryHub::~IRegistryHub() = default;
  8977. IMutableRegistryHub::~IMutableRegistryHub() = default;
  8978. }
  8979. // end catch_interfaces_registry_hub.cpp
  8980. // start catch_interfaces_reporter.cpp
  8981. // start catch_reporter_listening.h
  8982. namespace Catch {
  8983. class ListeningReporter : public IStreamingReporter {
  8984. using Reporters = std::vector<IStreamingReporterPtr>;
  8985. Reporters m_listeners;
  8986. IStreamingReporterPtr m_reporter = nullptr;
  8987. ReporterPreferences m_preferences;
  8988. public:
  8989. ListeningReporter();
  8990. void addListener( IStreamingReporterPtr&& listener );
  8991. void addReporter( IStreamingReporterPtr&& reporter );
  8992. public: // IStreamingReporter
  8993. ReporterPreferences getPreferences() const override;
  8994. void noMatchingTestCases( std::string const& spec ) override;
  8995. void reportInvalidArguments(std::string const&arg) override;
  8996. static std::set<Verbosity> getSupportedVerbosities();
  8997. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  8998. void benchmarkPreparing(std::string const& name) override;
  8999. void benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) override;
  9000. void benchmarkEnded( BenchmarkStats<> const& benchmarkStats ) override;
  9001. void benchmarkFailed(std::string const&) override;
  9002. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  9003. void testRunStarting( TestRunInfo const& testRunInfo ) override;
  9004. void testGroupStarting( GroupInfo const& groupInfo ) override;
  9005. void testCaseStarting( TestCaseInfo const& testInfo ) override;
  9006. void sectionStarting( SectionInfo const& sectionInfo ) override;
  9007. void assertionStarting( AssertionInfo const& assertionInfo ) override;
  9008. // The return value indicates if the messages buffer should be cleared:
  9009. bool assertionEnded( AssertionStats const& assertionStats ) override;
  9010. void sectionEnded( SectionStats const& sectionStats ) override;
  9011. void testCaseEnded( TestCaseStats const& testCaseStats ) override;
  9012. void testGroupEnded( TestGroupStats const& testGroupStats ) override;
  9013. void testRunEnded( TestRunStats const& testRunStats ) override;
  9014. void skipTest( TestCaseInfo const& testInfo ) override;
  9015. bool isMulti() const override;
  9016. };
  9017. } // end namespace Catch
  9018. // end catch_reporter_listening.h
  9019. namespace Catch {
  9020. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig )
  9021. : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {}
  9022. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream )
  9023. : m_stream( &_stream ), m_fullConfig( _fullConfig ) {}
  9024. std::ostream& ReporterConfig::stream() const { return *m_stream; }
  9025. IConfigPtr ReporterConfig::fullConfig() const { return m_fullConfig; }
  9026. TestRunInfo::TestRunInfo( std::string const& _name ) : name( _name ) {}
  9027. GroupInfo::GroupInfo( std::string const& _name,
  9028. std::size_t _groupIndex,
  9029. std::size_t _groupsCount )
  9030. : name( _name ),
  9031. groupIndex( _groupIndex ),
  9032. groupsCounts( _groupsCount )
  9033. {}
  9034. AssertionStats::AssertionStats( AssertionResult const& _assertionResult,
  9035. std::vector<MessageInfo> const& _infoMessages,
  9036. Totals const& _totals )
  9037. : assertionResult( _assertionResult ),
  9038. infoMessages( _infoMessages ),
  9039. totals( _totals )
  9040. {
  9041. assertionResult.m_resultData.lazyExpression.m_transientExpression = _assertionResult.m_resultData.lazyExpression.m_transientExpression;
  9042. if( assertionResult.hasMessage() ) {
  9043. // Copy message into messages list.
  9044. // !TBD This should have been done earlier, somewhere
  9045. MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() );
  9046. builder << assertionResult.getMessage();
  9047. builder.m_info.message = builder.m_stream.str();
  9048. infoMessages.push_back( builder.m_info );
  9049. }
  9050. }
  9051. AssertionStats::~AssertionStats() = default;
  9052. SectionStats::SectionStats( SectionInfo const& _sectionInfo,
  9053. Counts const& _assertions,
  9054. double _durationInSeconds,
  9055. bool _missingAssertions )
  9056. : sectionInfo( _sectionInfo ),
  9057. assertions( _assertions ),
  9058. durationInSeconds( _durationInSeconds ),
  9059. missingAssertions( _missingAssertions )
  9060. {}
  9061. SectionStats::~SectionStats() = default;
  9062. TestCaseStats::TestCaseStats( TestCaseInfo const& _testInfo,
  9063. Totals const& _totals,
  9064. std::string const& _stdOut,
  9065. std::string const& _stdErr,
  9066. bool _aborting )
  9067. : testInfo( _testInfo ),
  9068. totals( _totals ),
  9069. stdOut( _stdOut ),
  9070. stdErr( _stdErr ),
  9071. aborting( _aborting )
  9072. {}
  9073. TestCaseStats::~TestCaseStats() = default;
  9074. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo,
  9075. Totals const& _totals,
  9076. bool _aborting )
  9077. : groupInfo( _groupInfo ),
  9078. totals( _totals ),
  9079. aborting( _aborting )
  9080. {}
  9081. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo )
  9082. : groupInfo( _groupInfo ),
  9083. aborting( false )
  9084. {}
  9085. TestGroupStats::~TestGroupStats() = default;
  9086. TestRunStats::TestRunStats( TestRunInfo const& _runInfo,
  9087. Totals const& _totals,
  9088. bool _aborting )
  9089. : runInfo( _runInfo ),
  9090. totals( _totals ),
  9091. aborting( _aborting )
  9092. {}
  9093. TestRunStats::~TestRunStats() = default;
  9094. void IStreamingReporter::fatalErrorEncountered( StringRef ) {}
  9095. bool IStreamingReporter::isMulti() const { return false; }
  9096. IReporterFactory::~IReporterFactory() = default;
  9097. IReporterRegistry::~IReporterRegistry() = default;
  9098. } // end namespace Catch
  9099. // end catch_interfaces_reporter.cpp
  9100. // start catch_interfaces_runner.cpp
  9101. namespace Catch {
  9102. IRunner::~IRunner() = default;
  9103. }
  9104. // end catch_interfaces_runner.cpp
  9105. // start catch_interfaces_testcase.cpp
  9106. namespace Catch {
  9107. ITestInvoker::~ITestInvoker() = default;
  9108. ITestCaseRegistry::~ITestCaseRegistry() = default;
  9109. }
  9110. // end catch_interfaces_testcase.cpp
  9111. // start catch_leak_detector.cpp
  9112. #ifdef CATCH_CONFIG_WINDOWS_CRTDBG
  9113. #include <crtdbg.h>
  9114. namespace Catch {
  9115. LeakDetector::LeakDetector() {
  9116. int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
  9117. flag |= _CRTDBG_LEAK_CHECK_DF;
  9118. flag |= _CRTDBG_ALLOC_MEM_DF;
  9119. _CrtSetDbgFlag(flag);
  9120. _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
  9121. _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
  9122. // Change this to leaking allocation's number to break there
  9123. _CrtSetBreakAlloc(-1);
  9124. }
  9125. }
  9126. #else
  9127. Catch::LeakDetector::LeakDetector() {}
  9128. #endif
  9129. Catch::LeakDetector::~LeakDetector() {
  9130. Catch::cleanUp();
  9131. }
  9132. // end catch_leak_detector.cpp
  9133. // start catch_list.cpp
  9134. // start catch_list.h
  9135. #include <set>
  9136. namespace Catch {
  9137. std::size_t listTests( Config const& config );
  9138. std::size_t listTestsNamesOnly( Config const& config );
  9139. struct TagInfo {
  9140. void add( std::string const& spelling );
  9141. std::string all() const;
  9142. std::set<std::string> spellings;
  9143. std::size_t count = 0;
  9144. };
  9145. std::size_t listTags( Config const& config );
  9146. std::size_t listReporters();
  9147. Option<std::size_t> list( std::shared_ptr<Config> const& config );
  9148. } // end namespace Catch
  9149. // end catch_list.h
  9150. // start catch_text.h
  9151. namespace Catch {
  9152. using namespace clara::TextFlow;
  9153. }
  9154. // end catch_text.h
  9155. #include <limits>
  9156. #include <algorithm>
  9157. #include <iomanip>
  9158. namespace Catch {
  9159. std::size_t listTests( Config const& config ) {
  9160. TestSpec const& testSpec = config.testSpec();
  9161. if( config.hasTestFilters() )
  9162. Catch::cout() << "Matching test cases:\n";
  9163. else {
  9164. Catch::cout() << "All available test cases:\n";
  9165. }
  9166. auto matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  9167. for( auto const& testCaseInfo : matchedTestCases ) {
  9168. Colour::Code colour = testCaseInfo.isHidden()
  9169. ? Colour::SecondaryText
  9170. : Colour::None;
  9171. Colour colourGuard( colour );
  9172. Catch::cout() << Column( testCaseInfo.name ).initialIndent( 2 ).indent( 4 ) << "\n";
  9173. if( config.verbosity() >= Verbosity::High ) {
  9174. Catch::cout() << Column( Catch::Detail::stringify( testCaseInfo.lineInfo ) ).indent(4) << std::endl;
  9175. std::string description = testCaseInfo.description;
  9176. if( description.empty() )
  9177. description = "(NO DESCRIPTION)";
  9178. Catch::cout() << Column( description ).indent(4) << std::endl;
  9179. }
  9180. if( !testCaseInfo.tags.empty() )
  9181. Catch::cout() << Column( testCaseInfo.tagsAsString() ).indent( 6 ) << "\n";
  9182. }
  9183. if( !config.hasTestFilters() )
  9184. Catch::cout() << pluralise( matchedTestCases.size(), "test case" ) << '\n' << std::endl;
  9185. else
  9186. Catch::cout() << pluralise( matchedTestCases.size(), "matching test case" ) << '\n' << std::endl;
  9187. return matchedTestCases.size();
  9188. }
  9189. std::size_t listTestsNamesOnly( Config const& config ) {
  9190. TestSpec const& testSpec = config.testSpec();
  9191. std::size_t matchedTests = 0;
  9192. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  9193. for( auto const& testCaseInfo : matchedTestCases ) {
  9194. matchedTests++;
  9195. if( startsWith( testCaseInfo.name, '#' ) )
  9196. Catch::cout() << '"' << testCaseInfo.name << '"';
  9197. else
  9198. Catch::cout() << testCaseInfo.name;
  9199. if ( config.verbosity() >= Verbosity::High )
  9200. Catch::cout() << "\t@" << testCaseInfo.lineInfo;
  9201. Catch::cout() << std::endl;
  9202. }
  9203. return matchedTests;
  9204. }
  9205. void TagInfo::add( std::string const& spelling ) {
  9206. ++count;
  9207. spellings.insert( spelling );
  9208. }
  9209. std::string TagInfo::all() const {
  9210. size_t size = 0;
  9211. for (auto const& spelling : spellings) {
  9212. // Add 2 for the brackes
  9213. size += spelling.size() + 2;
  9214. }
  9215. std::string out; out.reserve(size);
  9216. for (auto const& spelling : spellings) {
  9217. out += '[';
  9218. out += spelling;
  9219. out += ']';
  9220. }
  9221. return out;
  9222. }
  9223. std::size_t listTags( Config const& config ) {
  9224. TestSpec const& testSpec = config.testSpec();
  9225. if( config.hasTestFilters() )
  9226. Catch::cout() << "Tags for matching test cases:\n";
  9227. else {
  9228. Catch::cout() << "All available tags:\n";
  9229. }
  9230. std::map<std::string, TagInfo> tagCounts;
  9231. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  9232. for( auto const& testCase : matchedTestCases ) {
  9233. for( auto const& tagName : testCase.getTestCaseInfo().tags ) {
  9234. std::string lcaseTagName = toLower( tagName );
  9235. auto countIt = tagCounts.find( lcaseTagName );
  9236. if( countIt == tagCounts.end() )
  9237. countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first;
  9238. countIt->second.add( tagName );
  9239. }
  9240. }
  9241. for( auto const& tagCount : tagCounts ) {
  9242. ReusableStringStream rss;
  9243. rss << " " << std::setw(2) << tagCount.second.count << " ";
  9244. auto str = rss.str();
  9245. auto wrapper = Column( tagCount.second.all() )
  9246. .initialIndent( 0 )
  9247. .indent( str.size() )
  9248. .width( CATCH_CONFIG_CONSOLE_WIDTH-10 );
  9249. Catch::cout() << str << wrapper << '\n';
  9250. }
  9251. Catch::cout() << pluralise( tagCounts.size(), "tag" ) << '\n' << std::endl;
  9252. return tagCounts.size();
  9253. }
  9254. std::size_t listReporters() {
  9255. Catch::cout() << "Available reporters:\n";
  9256. IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
  9257. std::size_t maxNameLen = 0;
  9258. for( auto const& factoryKvp : factories )
  9259. maxNameLen = (std::max)( maxNameLen, factoryKvp.first.size() );
  9260. for( auto const& factoryKvp : factories ) {
  9261. Catch::cout()
  9262. << Column( factoryKvp.first + ":" )
  9263. .indent(2)
  9264. .width( 5+maxNameLen )
  9265. + Column( factoryKvp.second->getDescription() )
  9266. .initialIndent(0)
  9267. .indent(2)
  9268. .width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 )
  9269. << "\n";
  9270. }
  9271. Catch::cout() << std::endl;
  9272. return factories.size();
  9273. }
  9274. Option<std::size_t> list( std::shared_ptr<Config> const& config ) {
  9275. Option<std::size_t> listedCount;
  9276. getCurrentMutableContext().setConfig( config );
  9277. if( config->listTests() )
  9278. listedCount = listedCount.valueOr(0) + listTests( *config );
  9279. if( config->listTestNamesOnly() )
  9280. listedCount = listedCount.valueOr(0) + listTestsNamesOnly( *config );
  9281. if( config->listTags() )
  9282. listedCount = listedCount.valueOr(0) + listTags( *config );
  9283. if( config->listReporters() )
  9284. listedCount = listedCount.valueOr(0) + listReporters();
  9285. return listedCount;
  9286. }
  9287. } // end namespace Catch
  9288. // end catch_list.cpp
  9289. // start catch_matchers.cpp
  9290. namespace Catch {
  9291. namespace Matchers {
  9292. namespace Impl {
  9293. std::string MatcherUntypedBase::toString() const {
  9294. if( m_cachedToString.empty() )
  9295. m_cachedToString = describe();
  9296. return m_cachedToString;
  9297. }
  9298. MatcherUntypedBase::~MatcherUntypedBase() = default;
  9299. } // namespace Impl
  9300. } // namespace Matchers
  9301. using namespace Matchers;
  9302. using Matchers::Impl::MatcherBase;
  9303. } // namespace Catch
  9304. // end catch_matchers.cpp
  9305. // start catch_matchers_exception.cpp
  9306. namespace Catch {
  9307. namespace Matchers {
  9308. namespace Exception {
  9309. bool ExceptionMessageMatcher::match(std::exception const& ex) const {
  9310. return ex.what() == m_message;
  9311. }
  9312. std::string ExceptionMessageMatcher::describe() const {
  9313. return "exception message matches \"" + m_message + "\"";
  9314. }
  9315. }
  9316. Exception::ExceptionMessageMatcher Message(std::string const& message) {
  9317. return Exception::ExceptionMessageMatcher(message);
  9318. }
  9319. // namespace Exception
  9320. } // namespace Matchers
  9321. } // namespace Catch
  9322. // end catch_matchers_exception.cpp
  9323. // start catch_matchers_floating.cpp
  9324. // start catch_polyfills.hpp
  9325. namespace Catch {
  9326. bool isnan(float f);
  9327. bool isnan(double d);
  9328. }
  9329. // end catch_polyfills.hpp
  9330. // start catch_to_string.hpp
  9331. #include <string>
  9332. namespace Catch {
  9333. template <typename T>
  9334. std::string to_string(T const& t) {
  9335. #if defined(CATCH_CONFIG_CPP11_TO_STRING)
  9336. return std::to_string(t);
  9337. #else
  9338. ReusableStringStream rss;
  9339. rss << t;
  9340. return rss.str();
  9341. #endif
  9342. }
  9343. } // end namespace Catch
  9344. // end catch_to_string.hpp
  9345. #include <algorithm>
  9346. #include <cmath>
  9347. #include <cstdlib>
  9348. #include <cstdint>
  9349. #include <cstring>
  9350. #include <sstream>
  9351. #include <type_traits>
  9352. #include <iomanip>
  9353. #include <limits>
  9354. namespace Catch {
  9355. namespace {
  9356. int32_t convert(float f) {
  9357. static_assert(sizeof(float) == sizeof(int32_t), "Important ULP matcher assumption violated");
  9358. int32_t i;
  9359. std::memcpy(&i, &f, sizeof(f));
  9360. return i;
  9361. }
  9362. int64_t convert(double d) {
  9363. static_assert(sizeof(double) == sizeof(int64_t), "Important ULP matcher assumption violated");
  9364. int64_t i;
  9365. std::memcpy(&i, &d, sizeof(d));
  9366. return i;
  9367. }
  9368. template <typename FP>
  9369. bool almostEqualUlps(FP lhs, FP rhs, uint64_t maxUlpDiff) {
  9370. // Comparison with NaN should always be false.
  9371. // This way we can rule it out before getting into the ugly details
  9372. if (Catch::isnan(lhs) || Catch::isnan(rhs)) {
  9373. return false;
  9374. }
  9375. auto lc = convert(lhs);
  9376. auto rc = convert(rhs);
  9377. if ((lc < 0) != (rc < 0)) {
  9378. // Potentially we can have +0 and -0
  9379. return lhs == rhs;
  9380. }
  9381. // static cast as a workaround for IBM XLC
  9382. auto ulpDiff = std::abs(static_cast<FP>(lc - rc));
  9383. return static_cast<uint64_t>(ulpDiff) <= maxUlpDiff;
  9384. }
  9385. #if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
  9386. float nextafter(float x, float y) {
  9387. return ::nextafterf(x, y);
  9388. }
  9389. double nextafter(double x, double y) {
  9390. return ::nextafter(x, y);
  9391. }
  9392. #endif // ^^^ CATCH_CONFIG_GLOBAL_NEXTAFTER ^^^
  9393. template <typename FP>
  9394. FP step(FP start, FP direction, uint64_t steps) {
  9395. for (uint64_t i = 0; i < steps; ++i) {
  9396. #if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
  9397. start = Catch::nextafter(start, direction);
  9398. #else
  9399. start = std::nextafter(start, direction);
  9400. #endif
  9401. }
  9402. return start;
  9403. }
  9404. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  9405. // But without the subtraction to allow for INFINITY in comparison
  9406. bool marginComparison(double lhs, double rhs, double margin) {
  9407. return (lhs + margin >= rhs) && (rhs + margin >= lhs);
  9408. }
  9409. template <typename FloatingPoint>
  9410. void write(std::ostream& out, FloatingPoint num) {
  9411. out << std::scientific
  9412. << std::setprecision(std::numeric_limits<FloatingPoint>::max_digits10 - 1)
  9413. << num;
  9414. }
  9415. } // end anonymous namespace
  9416. namespace Matchers {
  9417. namespace Floating {
  9418. enum class FloatingPointKind : uint8_t {
  9419. Float,
  9420. Double
  9421. };
  9422. WithinAbsMatcher::WithinAbsMatcher(double target, double margin)
  9423. :m_target{ target }, m_margin{ margin } {
  9424. CATCH_ENFORCE(margin >= 0, "Invalid margin: " << margin << '.'
  9425. << " Margin has to be non-negative.");
  9426. }
  9427. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  9428. // But without the subtraction to allow for INFINITY in comparison
  9429. bool WithinAbsMatcher::match(double const& matchee) const {
  9430. return (matchee + m_margin >= m_target) && (m_target + m_margin >= matchee);
  9431. }
  9432. std::string WithinAbsMatcher::describe() const {
  9433. return "is within " + ::Catch::Detail::stringify(m_margin) + " of " + ::Catch::Detail::stringify(m_target);
  9434. }
  9435. WithinUlpsMatcher::WithinUlpsMatcher(double target, uint64_t ulps, FloatingPointKind baseType)
  9436. :m_target{ target }, m_ulps{ ulps }, m_type{ baseType } {
  9437. CATCH_ENFORCE(m_type == FloatingPointKind::Double
  9438. || m_ulps < (std::numeric_limits<uint32_t>::max)(),
  9439. "Provided ULP is impossibly large for a float comparison.");
  9440. }
  9441. #if defined(__clang__)
  9442. #pragma clang diagnostic push
  9443. // Clang <3.5 reports on the default branch in the switch below
  9444. #pragma clang diagnostic ignored "-Wunreachable-code"
  9445. #endif
  9446. bool WithinUlpsMatcher::match(double const& matchee) const {
  9447. switch (m_type) {
  9448. case FloatingPointKind::Float:
  9449. return almostEqualUlps<float>(static_cast<float>(matchee), static_cast<float>(m_target), m_ulps);
  9450. case FloatingPointKind::Double:
  9451. return almostEqualUlps<double>(matchee, m_target, m_ulps);
  9452. default:
  9453. CATCH_INTERNAL_ERROR( "Unknown FloatingPointKind value" );
  9454. }
  9455. }
  9456. #if defined(__clang__)
  9457. #pragma clang diagnostic pop
  9458. #endif
  9459. std::string WithinUlpsMatcher::describe() const {
  9460. std::stringstream ret;
  9461. ret << "is within " << m_ulps << " ULPs of ";
  9462. if (m_type == FloatingPointKind::Float) {
  9463. write(ret, static_cast<float>(m_target));
  9464. ret << 'f';
  9465. } else {
  9466. write(ret, m_target);
  9467. }
  9468. ret << " ([";
  9469. if (m_type == FloatingPointKind::Double) {
  9470. write(ret, step(m_target, static_cast<double>(-INFINITY), m_ulps));
  9471. ret << ", ";
  9472. write(ret, step(m_target, static_cast<double>( INFINITY), m_ulps));
  9473. } else {
  9474. // We have to cast INFINITY to float because of MinGW, see #1782
  9475. write(ret, step(static_cast<float>(m_target), static_cast<float>(-INFINITY), m_ulps));
  9476. ret << ", ";
  9477. write(ret, step(static_cast<float>(m_target), static_cast<float>( INFINITY), m_ulps));
  9478. }
  9479. ret << "])";
  9480. return ret.str();
  9481. }
  9482. WithinRelMatcher::WithinRelMatcher(double target, double epsilon):
  9483. m_target(target),
  9484. m_epsilon(epsilon){
  9485. CATCH_ENFORCE(m_epsilon >= 0., "Relative comparison with epsilon < 0 does not make sense.");
  9486. CATCH_ENFORCE(m_epsilon < 1., "Relative comparison with epsilon >= 1 does not make sense.");
  9487. }
  9488. bool WithinRelMatcher::match(double const& matchee) const {
  9489. const auto relMargin = m_epsilon * (std::max)(std::fabs(matchee), std::fabs(m_target));
  9490. return marginComparison(matchee, m_target,
  9491. std::isinf(relMargin)? 0 : relMargin);
  9492. }
  9493. std::string WithinRelMatcher::describe() const {
  9494. Catch::ReusableStringStream sstr;
  9495. sstr << "and " << m_target << " are within " << m_epsilon * 100. << "% of each other";
  9496. return sstr.str();
  9497. }
  9498. }// namespace Floating
  9499. Floating::WithinUlpsMatcher WithinULP(double target, uint64_t maxUlpDiff) {
  9500. return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Double);
  9501. }
  9502. Floating::WithinUlpsMatcher WithinULP(float target, uint64_t maxUlpDiff) {
  9503. return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Float);
  9504. }
  9505. Floating::WithinAbsMatcher WithinAbs(double target, double margin) {
  9506. return Floating::WithinAbsMatcher(target, margin);
  9507. }
  9508. Floating::WithinRelMatcher WithinRel(double target, double eps) {
  9509. return Floating::WithinRelMatcher(target, eps);
  9510. }
  9511. Floating::WithinRelMatcher WithinRel(double target) {
  9512. return Floating::WithinRelMatcher(target, std::numeric_limits<double>::epsilon() * 100);
  9513. }
  9514. Floating::WithinRelMatcher WithinRel(float target, float eps) {
  9515. return Floating::WithinRelMatcher(target, eps);
  9516. }
  9517. Floating::WithinRelMatcher WithinRel(float target) {
  9518. return Floating::WithinRelMatcher(target, std::numeric_limits<float>::epsilon() * 100);
  9519. }
  9520. } // namespace Matchers
  9521. } // namespace Catch
  9522. // end catch_matchers_floating.cpp
  9523. // start catch_matchers_generic.cpp
  9524. std::string Catch::Matchers::Generic::Detail::finalizeDescription(const std::string& desc) {
  9525. if (desc.empty()) {
  9526. return "matches undescribed predicate";
  9527. } else {
  9528. return "matches predicate: \"" + desc + '"';
  9529. }
  9530. }
  9531. // end catch_matchers_generic.cpp
  9532. // start catch_matchers_string.cpp
  9533. #include <regex>
  9534. namespace Catch {
  9535. namespace Matchers {
  9536. namespace StdString {
  9537. CasedString::CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity )
  9538. : m_caseSensitivity( caseSensitivity ),
  9539. m_str( adjustString( str ) )
  9540. {}
  9541. std::string CasedString::adjustString( std::string const& str ) const {
  9542. return m_caseSensitivity == CaseSensitive::No
  9543. ? toLower( str )
  9544. : str;
  9545. }
  9546. std::string CasedString::caseSensitivitySuffix() const {
  9547. return m_caseSensitivity == CaseSensitive::No
  9548. ? " (case insensitive)"
  9549. : std::string();
  9550. }
  9551. StringMatcherBase::StringMatcherBase( std::string const& operation, CasedString const& comparator )
  9552. : m_comparator( comparator ),
  9553. m_operation( operation ) {
  9554. }
  9555. std::string StringMatcherBase::describe() const {
  9556. std::string description;
  9557. description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
  9558. m_comparator.caseSensitivitySuffix().size());
  9559. description += m_operation;
  9560. description += ": \"";
  9561. description += m_comparator.m_str;
  9562. description += "\"";
  9563. description += m_comparator.caseSensitivitySuffix();
  9564. return description;
  9565. }
  9566. EqualsMatcher::EqualsMatcher( CasedString const& comparator ) : StringMatcherBase( "equals", comparator ) {}
  9567. bool EqualsMatcher::match( std::string const& source ) const {
  9568. return m_comparator.adjustString( source ) == m_comparator.m_str;
  9569. }
  9570. ContainsMatcher::ContainsMatcher( CasedString const& comparator ) : StringMatcherBase( "contains", comparator ) {}
  9571. bool ContainsMatcher::match( std::string const& source ) const {
  9572. return contains( m_comparator.adjustString( source ), m_comparator.m_str );
  9573. }
  9574. StartsWithMatcher::StartsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "starts with", comparator ) {}
  9575. bool StartsWithMatcher::match( std::string const& source ) const {
  9576. return startsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  9577. }
  9578. EndsWithMatcher::EndsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "ends with", comparator ) {}
  9579. bool EndsWithMatcher::match( std::string const& source ) const {
  9580. return endsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  9581. }
  9582. RegexMatcher::RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity): m_regex(std::move(regex)), m_caseSensitivity(caseSensitivity) {}
  9583. bool RegexMatcher::match(std::string const& matchee) const {
  9584. auto flags = std::regex::ECMAScript; // ECMAScript is the default syntax option anyway
  9585. if (m_caseSensitivity == CaseSensitive::Choice::No) {
  9586. flags |= std::regex::icase;
  9587. }
  9588. auto reg = std::regex(m_regex, flags);
  9589. return std::regex_match(matchee, reg);
  9590. }
  9591. std::string RegexMatcher::describe() const {
  9592. return "matches " + ::Catch::Detail::stringify(m_regex) + ((m_caseSensitivity == CaseSensitive::Choice::Yes)? " case sensitively" : " case insensitively");
  9593. }
  9594. } // namespace StdString
  9595. StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  9596. return StdString::EqualsMatcher( StdString::CasedString( str, caseSensitivity) );
  9597. }
  9598. StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  9599. return StdString::ContainsMatcher( StdString::CasedString( str, caseSensitivity) );
  9600. }
  9601. StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  9602. return StdString::EndsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  9603. }
  9604. StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  9605. return StdString::StartsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  9606. }
  9607. StdString::RegexMatcher Matches(std::string const& regex, CaseSensitive::Choice caseSensitivity) {
  9608. return StdString::RegexMatcher(regex, caseSensitivity);
  9609. }
  9610. } // namespace Matchers
  9611. } // namespace Catch
  9612. // end catch_matchers_string.cpp
  9613. // start catch_message.cpp
  9614. // start catch_uncaught_exceptions.h
  9615. namespace Catch {
  9616. bool uncaught_exceptions();
  9617. } // end namespace Catch
  9618. // end catch_uncaught_exceptions.h
  9619. #include <cassert>
  9620. #include <stack>
  9621. namespace Catch {
  9622. MessageInfo::MessageInfo( StringRef const& _macroName,
  9623. SourceLineInfo const& _lineInfo,
  9624. ResultWas::OfType _type )
  9625. : macroName( _macroName ),
  9626. lineInfo( _lineInfo ),
  9627. type( _type ),
  9628. sequence( ++globalCount )
  9629. {}
  9630. bool MessageInfo::operator==( MessageInfo const& other ) const {
  9631. return sequence == other.sequence;
  9632. }
  9633. bool MessageInfo::operator<( MessageInfo const& other ) const {
  9634. return sequence < other.sequence;
  9635. }
  9636. // This may need protecting if threading support is added
  9637. unsigned int MessageInfo::globalCount = 0;
  9638. ////////////////////////////////////////////////////////////////////////////
  9639. Catch::MessageBuilder::MessageBuilder( StringRef const& macroName,
  9640. SourceLineInfo const& lineInfo,
  9641. ResultWas::OfType type )
  9642. :m_info(macroName, lineInfo, type) {}
  9643. ////////////////////////////////////////////////////////////////////////////
  9644. ScopedMessage::ScopedMessage( MessageBuilder const& builder )
  9645. : m_info( builder.m_info ), m_moved()
  9646. {
  9647. m_info.message = builder.m_stream.str();
  9648. getResultCapture().pushScopedMessage( m_info );
  9649. }
  9650. ScopedMessage::ScopedMessage( ScopedMessage&& old )
  9651. : m_info( old.m_info ), m_moved()
  9652. {
  9653. old.m_moved = true;
  9654. }
  9655. ScopedMessage::~ScopedMessage() {
  9656. if ( !uncaught_exceptions() && !m_moved ){
  9657. getResultCapture().popScopedMessage(m_info);
  9658. }
  9659. }
  9660. Capturer::Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names ) {
  9661. auto trimmed = [&] (size_t start, size_t end) {
  9662. while (names[start] == ',' || isspace(static_cast<unsigned char>(names[start]))) {
  9663. ++start;
  9664. }
  9665. while (names[end] == ',' || isspace(static_cast<unsigned char>(names[end]))) {
  9666. --end;
  9667. }
  9668. return names.substr(start, end - start + 1);
  9669. };
  9670. auto skipq = [&] (size_t start, char quote) {
  9671. for (auto i = start + 1; i < names.size() ; ++i) {
  9672. if (names[i] == quote)
  9673. return i;
  9674. if (names[i] == '\\')
  9675. ++i;
  9676. }
  9677. CATCH_INTERNAL_ERROR("CAPTURE parsing encountered unmatched quote");
  9678. };
  9679. size_t start = 0;
  9680. std::stack<char> openings;
  9681. for (size_t pos = 0; pos < names.size(); ++pos) {
  9682. char c = names[pos];
  9683. switch (c) {
  9684. case '[':
  9685. case '{':
  9686. case '(':
  9687. // It is basically impossible to disambiguate between
  9688. // comparison and start of template args in this context
  9689. // case '<':
  9690. openings.push(c);
  9691. break;
  9692. case ']':
  9693. case '}':
  9694. case ')':
  9695. // case '>':
  9696. openings.pop();
  9697. break;
  9698. case '"':
  9699. case '\'':
  9700. pos = skipq(pos, c);
  9701. break;
  9702. case ',':
  9703. if (start != pos && openings.empty()) {
  9704. m_messages.emplace_back(macroName, lineInfo, resultType);
  9705. m_messages.back().message = static_cast<std::string>(trimmed(start, pos));
  9706. m_messages.back().message += " := ";
  9707. start = pos;
  9708. }
  9709. }
  9710. }
  9711. assert(openings.empty() && "Mismatched openings");
  9712. m_messages.emplace_back(macroName, lineInfo, resultType);
  9713. m_messages.back().message = static_cast<std::string>(trimmed(start, names.size() - 1));
  9714. m_messages.back().message += " := ";
  9715. }
  9716. Capturer::~Capturer() {
  9717. if ( !uncaught_exceptions() ){
  9718. assert( m_captured == m_messages.size() );
  9719. for( size_t i = 0; i < m_captured; ++i )
  9720. m_resultCapture.popScopedMessage( m_messages[i] );
  9721. }
  9722. }
  9723. void Capturer::captureValue( size_t index, std::string const& value ) {
  9724. assert( index < m_messages.size() );
  9725. m_messages[index].message += value;
  9726. m_resultCapture.pushScopedMessage( m_messages[index] );
  9727. m_captured++;
  9728. }
  9729. } // end namespace Catch
  9730. // end catch_message.cpp
  9731. // start catch_output_redirect.cpp
  9732. // start catch_output_redirect.h
  9733. #ifndef TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  9734. #define TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  9735. #include <cstdio>
  9736. #include <iosfwd>
  9737. #include <string>
  9738. namespace Catch {
  9739. class RedirectedStream {
  9740. std::ostream& m_originalStream;
  9741. std::ostream& m_redirectionStream;
  9742. std::streambuf* m_prevBuf;
  9743. public:
  9744. RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream );
  9745. ~RedirectedStream();
  9746. };
  9747. class RedirectedStdOut {
  9748. ReusableStringStream m_rss;
  9749. RedirectedStream m_cout;
  9750. public:
  9751. RedirectedStdOut();
  9752. auto str() const -> std::string;
  9753. };
  9754. // StdErr has two constituent streams in C++, std::cerr and std::clog
  9755. // This means that we need to redirect 2 streams into 1 to keep proper
  9756. // order of writes
  9757. class RedirectedStdErr {
  9758. ReusableStringStream m_rss;
  9759. RedirectedStream m_cerr;
  9760. RedirectedStream m_clog;
  9761. public:
  9762. RedirectedStdErr();
  9763. auto str() const -> std::string;
  9764. };
  9765. class RedirectedStreams {
  9766. public:
  9767. RedirectedStreams(RedirectedStreams const&) = delete;
  9768. RedirectedStreams& operator=(RedirectedStreams const&) = delete;
  9769. RedirectedStreams(RedirectedStreams&&) = delete;
  9770. RedirectedStreams& operator=(RedirectedStreams&&) = delete;
  9771. RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr);
  9772. ~RedirectedStreams();
  9773. private:
  9774. std::string& m_redirectedCout;
  9775. std::string& m_redirectedCerr;
  9776. RedirectedStdOut m_redirectedStdOut;
  9777. RedirectedStdErr m_redirectedStdErr;
  9778. };
  9779. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  9780. // Windows's implementation of std::tmpfile is terrible (it tries
  9781. // to create a file inside system folder, thus requiring elevated
  9782. // privileges for the binary), so we have to use tmpnam(_s) and
  9783. // create the file ourselves there.
  9784. class TempFile {
  9785. public:
  9786. TempFile(TempFile const&) = delete;
  9787. TempFile& operator=(TempFile const&) = delete;
  9788. TempFile(TempFile&&) = delete;
  9789. TempFile& operator=(TempFile&&) = delete;
  9790. TempFile();
  9791. ~TempFile();
  9792. std::FILE* getFile();
  9793. std::string getContents();
  9794. private:
  9795. std::FILE* m_file = nullptr;
  9796. #if defined(_MSC_VER)
  9797. char m_buffer[L_tmpnam] = { 0 };
  9798. #endif
  9799. };
  9800. class OutputRedirect {
  9801. public:
  9802. OutputRedirect(OutputRedirect const&) = delete;
  9803. OutputRedirect& operator=(OutputRedirect const&) = delete;
  9804. OutputRedirect(OutputRedirect&&) = delete;
  9805. OutputRedirect& operator=(OutputRedirect&&) = delete;
  9806. OutputRedirect(std::string& stdout_dest, std::string& stderr_dest);
  9807. ~OutputRedirect();
  9808. private:
  9809. int m_originalStdout = -1;
  9810. int m_originalStderr = -1;
  9811. TempFile m_stdoutFile;
  9812. TempFile m_stderrFile;
  9813. std::string& m_stdoutDest;
  9814. std::string& m_stderrDest;
  9815. };
  9816. #endif
  9817. } // end namespace Catch
  9818. #endif // TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  9819. // end catch_output_redirect.h
  9820. #include <cstdio>
  9821. #include <cstring>
  9822. #include <fstream>
  9823. #include <sstream>
  9824. #include <stdexcept>
  9825. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  9826. #if defined(_MSC_VER)
  9827. #include <io.h> //_dup and _dup2
  9828. #define dup _dup
  9829. #define dup2 _dup2
  9830. #define fileno _fileno
  9831. #else
  9832. #include <unistd.h> // dup and dup2
  9833. #endif
  9834. #endif
  9835. namespace Catch {
  9836. RedirectedStream::RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream )
  9837. : m_originalStream( originalStream ),
  9838. m_redirectionStream( redirectionStream ),
  9839. m_prevBuf( m_originalStream.rdbuf() )
  9840. {
  9841. m_originalStream.rdbuf( m_redirectionStream.rdbuf() );
  9842. }
  9843. RedirectedStream::~RedirectedStream() {
  9844. m_originalStream.rdbuf( m_prevBuf );
  9845. }
  9846. RedirectedStdOut::RedirectedStdOut() : m_cout( Catch::cout(), m_rss.get() ) {}
  9847. auto RedirectedStdOut::str() const -> std::string { return m_rss.str(); }
  9848. RedirectedStdErr::RedirectedStdErr()
  9849. : m_cerr( Catch::cerr(), m_rss.get() ),
  9850. m_clog( Catch::clog(), m_rss.get() )
  9851. {}
  9852. auto RedirectedStdErr::str() const -> std::string { return m_rss.str(); }
  9853. RedirectedStreams::RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr)
  9854. : m_redirectedCout(redirectedCout),
  9855. m_redirectedCerr(redirectedCerr)
  9856. {}
  9857. RedirectedStreams::~RedirectedStreams() {
  9858. m_redirectedCout += m_redirectedStdOut.str();
  9859. m_redirectedCerr += m_redirectedStdErr.str();
  9860. }
  9861. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  9862. #if defined(_MSC_VER)
  9863. TempFile::TempFile() {
  9864. if (tmpnam_s(m_buffer)) {
  9865. CATCH_RUNTIME_ERROR("Could not get a temp filename");
  9866. }
  9867. if (fopen_s(&m_file, m_buffer, "w+")) {
  9868. char buffer[100];
  9869. if (strerror_s(buffer, errno)) {
  9870. CATCH_RUNTIME_ERROR("Could not translate errno to a string");
  9871. }
  9872. CATCH_RUNTIME_ERROR("Could not open the temp file: '" << m_buffer << "' because: " << buffer);
  9873. }
  9874. }
  9875. #else
  9876. TempFile::TempFile() {
  9877. m_file = std::tmpfile();
  9878. if (!m_file) {
  9879. CATCH_RUNTIME_ERROR("Could not create a temp file.");
  9880. }
  9881. }
  9882. #endif
  9883. TempFile::~TempFile() {
  9884. // TBD: What to do about errors here?
  9885. std::fclose(m_file);
  9886. // We manually create the file on Windows only, on Linux
  9887. // it will be autodeleted
  9888. #if defined(_MSC_VER)
  9889. std::remove(m_buffer);
  9890. #endif
  9891. }
  9892. FILE* TempFile::getFile() {
  9893. return m_file;
  9894. }
  9895. std::string TempFile::getContents() {
  9896. std::stringstream sstr;
  9897. char buffer[100] = {};
  9898. std::rewind(m_file);
  9899. while (std::fgets(buffer, sizeof(buffer), m_file)) {
  9900. sstr << buffer;
  9901. }
  9902. return sstr.str();
  9903. }
  9904. OutputRedirect::OutputRedirect(std::string& stdout_dest, std::string& stderr_dest) :
  9905. m_originalStdout(dup(1)),
  9906. m_originalStderr(dup(2)),
  9907. m_stdoutDest(stdout_dest),
  9908. m_stderrDest(stderr_dest) {
  9909. dup2(fileno(m_stdoutFile.getFile()), 1);
  9910. dup2(fileno(m_stderrFile.getFile()), 2);
  9911. }
  9912. OutputRedirect::~OutputRedirect() {
  9913. Catch::cout() << std::flush;
  9914. fflush(stdout);
  9915. // Since we support overriding these streams, we flush cerr
  9916. // even though std::cerr is unbuffered
  9917. Catch::cerr() << std::flush;
  9918. Catch::clog() << std::flush;
  9919. fflush(stderr);
  9920. dup2(m_originalStdout, 1);
  9921. dup2(m_originalStderr, 2);
  9922. m_stdoutDest += m_stdoutFile.getContents();
  9923. m_stderrDest += m_stderrFile.getContents();
  9924. }
  9925. #endif // CATCH_CONFIG_NEW_CAPTURE
  9926. } // namespace Catch
  9927. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  9928. #if defined(_MSC_VER)
  9929. #undef dup
  9930. #undef dup2
  9931. #undef fileno
  9932. #endif
  9933. #endif
  9934. // end catch_output_redirect.cpp
  9935. // start catch_polyfills.cpp
  9936. #include <cmath>
  9937. namespace Catch {
  9938. #if !defined(CATCH_CONFIG_POLYFILL_ISNAN)
  9939. bool isnan(float f) {
  9940. return std::isnan(f);
  9941. }
  9942. bool isnan(double d) {
  9943. return std::isnan(d);
  9944. }
  9945. #else
  9946. // For now we only use this for embarcadero
  9947. bool isnan(float f) {
  9948. return std::_isnan(f);
  9949. }
  9950. bool isnan(double d) {
  9951. return std::_isnan(d);
  9952. }
  9953. #endif
  9954. } // end namespace Catch
  9955. // end catch_polyfills.cpp
  9956. // start catch_random_number_generator.cpp
  9957. namespace Catch {
  9958. namespace {
  9959. #if defined(_MSC_VER)
  9960. #pragma warning(push)
  9961. #pragma warning(disable:4146) // we negate uint32 during the rotate
  9962. #endif
  9963. // Safe rotr implementation thanks to John Regehr
  9964. uint32_t rotate_right(uint32_t val, uint32_t count) {
  9965. const uint32_t mask = 31;
  9966. count &= mask;
  9967. return (val >> count) | (val << (-count & mask));
  9968. }
  9969. #if defined(_MSC_VER)
  9970. #pragma warning(pop)
  9971. #endif
  9972. }
  9973. SimplePcg32::SimplePcg32(result_type seed_) {
  9974. seed(seed_);
  9975. }
  9976. void SimplePcg32::seed(result_type seed_) {
  9977. m_state = 0;
  9978. (*this)();
  9979. m_state += seed_;
  9980. (*this)();
  9981. }
  9982. void SimplePcg32::discard(uint64_t skip) {
  9983. // We could implement this to run in O(log n) steps, but this
  9984. // should suffice for our use case.
  9985. for (uint64_t s = 0; s < skip; ++s) {
  9986. static_cast<void>((*this)());
  9987. }
  9988. }
  9989. SimplePcg32::result_type SimplePcg32::operator()() {
  9990. // prepare the output value
  9991. const uint32_t xorshifted = static_cast<uint32_t>(((m_state >> 18u) ^ m_state) >> 27u);
  9992. const auto output = rotate_right(xorshifted, m_state >> 59u);
  9993. // advance state
  9994. m_state = m_state * 6364136223846793005ULL + s_inc;
  9995. return output;
  9996. }
  9997. bool operator==(SimplePcg32 const& lhs, SimplePcg32 const& rhs) {
  9998. return lhs.m_state == rhs.m_state;
  9999. }
  10000. bool operator!=(SimplePcg32 const& lhs, SimplePcg32 const& rhs) {
  10001. return lhs.m_state != rhs.m_state;
  10002. }
  10003. }
  10004. // end catch_random_number_generator.cpp
  10005. // start catch_registry_hub.cpp
  10006. // start catch_test_case_registry_impl.h
  10007. #include <vector>
  10008. #include <set>
  10009. #include <algorithm>
  10010. #include <ios>
  10011. namespace Catch {
  10012. class TestCase;
  10013. struct IConfig;
  10014. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases );
  10015. bool isThrowSafe( TestCase const& testCase, IConfig const& config );
  10016. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
  10017. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions );
  10018. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
  10019. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
  10020. class TestRegistry : public ITestCaseRegistry {
  10021. public:
  10022. virtual ~TestRegistry() = default;
  10023. virtual void registerTest( TestCase const& testCase );
  10024. std::vector<TestCase> const& getAllTests() const override;
  10025. std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const override;
  10026. private:
  10027. std::vector<TestCase> m_functions;
  10028. mutable RunTests::InWhatOrder m_currentSortOrder = RunTests::InDeclarationOrder;
  10029. mutable std::vector<TestCase> m_sortedFunctions;
  10030. std::size_t m_unnamedCount = 0;
  10031. std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised
  10032. };
  10033. ///////////////////////////////////////////////////////////////////////////
  10034. class TestInvokerAsFunction : public ITestInvoker {
  10035. void(*m_testAsFunction)();
  10036. public:
  10037. TestInvokerAsFunction( void(*testAsFunction)() ) noexcept;
  10038. void invoke() const override;
  10039. };
  10040. std::string extractClassName( StringRef const& classOrQualifiedMethodName );
  10041. ///////////////////////////////////////////////////////////////////////////
  10042. } // end namespace Catch
  10043. // end catch_test_case_registry_impl.h
  10044. // start catch_reporter_registry.h
  10045. #include <map>
  10046. namespace Catch {
  10047. class ReporterRegistry : public IReporterRegistry {
  10048. public:
  10049. ~ReporterRegistry() override;
  10050. IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const override;
  10051. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory );
  10052. void registerListener( IReporterFactoryPtr const& factory );
  10053. FactoryMap const& getFactories() const override;
  10054. Listeners const& getListeners() const override;
  10055. private:
  10056. FactoryMap m_factories;
  10057. Listeners m_listeners;
  10058. };
  10059. }
  10060. // end catch_reporter_registry.h
  10061. // start catch_tag_alias_registry.h
  10062. // start catch_tag_alias.h
  10063. #include <string>
  10064. namespace Catch {
  10065. struct TagAlias {
  10066. TagAlias(std::string const& _tag, SourceLineInfo _lineInfo);
  10067. std::string tag;
  10068. SourceLineInfo lineInfo;
  10069. };
  10070. } // end namespace Catch
  10071. // end catch_tag_alias.h
  10072. #include <map>
  10073. namespace Catch {
  10074. class TagAliasRegistry : public ITagAliasRegistry {
  10075. public:
  10076. ~TagAliasRegistry() override;
  10077. TagAlias const* find( std::string const& alias ) const override;
  10078. std::string expandAliases( std::string const& unexpandedTestSpec ) const override;
  10079. void add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo );
  10080. private:
  10081. std::map<std::string, TagAlias> m_registry;
  10082. };
  10083. } // end namespace Catch
  10084. // end catch_tag_alias_registry.h
  10085. // start catch_startup_exception_registry.h
  10086. #include <vector>
  10087. #include <exception>
  10088. namespace Catch {
  10089. class StartupExceptionRegistry {
  10090. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  10091. public:
  10092. void add(std::exception_ptr const& exception) noexcept;
  10093. std::vector<std::exception_ptr> const& getExceptions() const noexcept;
  10094. private:
  10095. std::vector<std::exception_ptr> m_exceptions;
  10096. #endif
  10097. };
  10098. } // end namespace Catch
  10099. // end catch_startup_exception_registry.h
  10100. // start catch_singletons.hpp
  10101. namespace Catch {
  10102. struct ISingleton {
  10103. virtual ~ISingleton();
  10104. };
  10105. void addSingleton( ISingleton* singleton );
  10106. void cleanupSingletons();
  10107. template<typename SingletonImplT, typename InterfaceT = SingletonImplT, typename MutableInterfaceT = InterfaceT>
  10108. class Singleton : SingletonImplT, public ISingleton {
  10109. static auto getInternal() -> Singleton* {
  10110. static Singleton* s_instance = nullptr;
  10111. if( !s_instance ) {
  10112. s_instance = new Singleton;
  10113. addSingleton( s_instance );
  10114. }
  10115. return s_instance;
  10116. }
  10117. public:
  10118. static auto get() -> InterfaceT const& {
  10119. return *getInternal();
  10120. }
  10121. static auto getMutable() -> MutableInterfaceT& {
  10122. return *getInternal();
  10123. }
  10124. };
  10125. } // namespace Catch
  10126. // end catch_singletons.hpp
  10127. namespace Catch {
  10128. namespace {
  10129. class RegistryHub : public IRegistryHub, public IMutableRegistryHub,
  10130. private NonCopyable {
  10131. public: // IRegistryHub
  10132. RegistryHub() = default;
  10133. IReporterRegistry const& getReporterRegistry() const override {
  10134. return m_reporterRegistry;
  10135. }
  10136. ITestCaseRegistry const& getTestCaseRegistry() const override {
  10137. return m_testCaseRegistry;
  10138. }
  10139. IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const override {
  10140. return m_exceptionTranslatorRegistry;
  10141. }
  10142. ITagAliasRegistry const& getTagAliasRegistry() const override {
  10143. return m_tagAliasRegistry;
  10144. }
  10145. StartupExceptionRegistry const& getStartupExceptionRegistry() const override {
  10146. return m_exceptionRegistry;
  10147. }
  10148. public: // IMutableRegistryHub
  10149. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) override {
  10150. m_reporterRegistry.registerReporter( name, factory );
  10151. }
  10152. void registerListener( IReporterFactoryPtr const& factory ) override {
  10153. m_reporterRegistry.registerListener( factory );
  10154. }
  10155. void registerTest( TestCase const& testInfo ) override {
  10156. m_testCaseRegistry.registerTest( testInfo );
  10157. }
  10158. void registerTranslator( const IExceptionTranslator* translator ) override {
  10159. m_exceptionTranslatorRegistry.registerTranslator( translator );
  10160. }
  10161. void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) override {
  10162. m_tagAliasRegistry.add( alias, tag, lineInfo );
  10163. }
  10164. void registerStartupException() noexcept override {
  10165. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  10166. m_exceptionRegistry.add(std::current_exception());
  10167. #else
  10168. CATCH_INTERNAL_ERROR("Attempted to register active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
  10169. #endif
  10170. }
  10171. IMutableEnumValuesRegistry& getMutableEnumValuesRegistry() override {
  10172. return m_enumValuesRegistry;
  10173. }
  10174. private:
  10175. TestRegistry m_testCaseRegistry;
  10176. ReporterRegistry m_reporterRegistry;
  10177. ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
  10178. TagAliasRegistry m_tagAliasRegistry;
  10179. StartupExceptionRegistry m_exceptionRegistry;
  10180. Detail::EnumValuesRegistry m_enumValuesRegistry;
  10181. };
  10182. }
  10183. using RegistryHubSingleton = Singleton<RegistryHub, IRegistryHub, IMutableRegistryHub>;
  10184. IRegistryHub const& getRegistryHub() {
  10185. return RegistryHubSingleton::get();
  10186. }
  10187. IMutableRegistryHub& getMutableRegistryHub() {
  10188. return RegistryHubSingleton::getMutable();
  10189. }
  10190. void cleanUp() {
  10191. cleanupSingletons();
  10192. cleanUpContext();
  10193. }
  10194. std::string translateActiveException() {
  10195. return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException();
  10196. }
  10197. } // end namespace Catch
  10198. // end catch_registry_hub.cpp
  10199. // start catch_reporter_registry.cpp
  10200. namespace Catch {
  10201. ReporterRegistry::~ReporterRegistry() = default;
  10202. IStreamingReporterPtr ReporterRegistry::create( std::string const& name, IConfigPtr const& config ) const {
  10203. auto it = m_factories.find( name );
  10204. if( it == m_factories.end() )
  10205. return nullptr;
  10206. return it->second->create( ReporterConfig( config ) );
  10207. }
  10208. void ReporterRegistry::registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) {
  10209. m_factories.emplace(name, factory);
  10210. }
  10211. void ReporterRegistry::registerListener( IReporterFactoryPtr const& factory ) {
  10212. m_listeners.push_back( factory );
  10213. }
  10214. IReporterRegistry::FactoryMap const& ReporterRegistry::getFactories() const {
  10215. return m_factories;
  10216. }
  10217. IReporterRegistry::Listeners const& ReporterRegistry::getListeners() const {
  10218. return m_listeners;
  10219. }
  10220. }
  10221. // end catch_reporter_registry.cpp
  10222. // start catch_result_type.cpp
  10223. namespace Catch {
  10224. bool isOk( ResultWas::OfType resultType ) {
  10225. return ( resultType & ResultWas::FailureBit ) == 0;
  10226. }
  10227. bool isJustInfo( int flags ) {
  10228. return flags == ResultWas::Info;
  10229. }
  10230. ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) {
  10231. return static_cast<ResultDisposition::Flags>( static_cast<int>( lhs ) | static_cast<int>( rhs ) );
  10232. }
  10233. bool shouldContinueOnFailure( int flags ) { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; }
  10234. bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; }
  10235. } // end namespace Catch
  10236. // end catch_result_type.cpp
  10237. // start catch_run_context.cpp
  10238. #include <cassert>
  10239. #include <algorithm>
  10240. #include <sstream>
  10241. namespace Catch {
  10242. namespace Generators {
  10243. struct GeneratorTracker : TestCaseTracking::TrackerBase, IGeneratorTracker {
  10244. GeneratorBasePtr m_generator;
  10245. GeneratorTracker( TestCaseTracking::NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  10246. : TrackerBase( nameAndLocation, ctx, parent )
  10247. {}
  10248. ~GeneratorTracker();
  10249. static GeneratorTracker& acquire( TrackerContext& ctx, TestCaseTracking::NameAndLocation const& nameAndLocation ) {
  10250. std::shared_ptr<GeneratorTracker> tracker;
  10251. ITracker& currentTracker = ctx.currentTracker();
  10252. // Under specific circumstances, the generator we want
  10253. // to acquire is also the current tracker. If this is
  10254. // the case, we have to avoid looking through current
  10255. // tracker's children, and instead return the current
  10256. // tracker.
  10257. // A case where this check is important is e.g.
  10258. // for (int i = 0; i < 5; ++i) {
  10259. // int n = GENERATE(1, 2);
  10260. // }
  10261. //
  10262. // without it, the code above creates 5 nested generators.
  10263. if (currentTracker.nameAndLocation() == nameAndLocation) {
  10264. auto thisTracker = currentTracker.parent().findChild(nameAndLocation);
  10265. assert(thisTracker);
  10266. assert(thisTracker->isGeneratorTracker());
  10267. tracker = std::static_pointer_cast<GeneratorTracker>(thisTracker);
  10268. } else if ( TestCaseTracking::ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  10269. assert( childTracker );
  10270. assert( childTracker->isGeneratorTracker() );
  10271. tracker = std::static_pointer_cast<GeneratorTracker>( childTracker );
  10272. } else {
  10273. tracker = std::make_shared<GeneratorTracker>( nameAndLocation, ctx, &currentTracker );
  10274. currentTracker.addChild( tracker );
  10275. }
  10276. if( !tracker->isComplete() ) {
  10277. tracker->open();
  10278. }
  10279. return *tracker;
  10280. }
  10281. // TrackerBase interface
  10282. bool isGeneratorTracker() const override { return true; }
  10283. auto hasGenerator() const -> bool override {
  10284. return !!m_generator;
  10285. }
  10286. void close() override {
  10287. TrackerBase::close();
  10288. // If a generator has a child (it is followed by a section)
  10289. // and none of its children have started, then we must wait
  10290. // until later to start consuming its values.
  10291. // This catches cases where `GENERATE` is placed between two
  10292. // `SECTION`s.
  10293. // **The check for m_children.empty cannot be removed**.
  10294. // doing so would break `GENERATE` _not_ followed by `SECTION`s.
  10295. const bool should_wait_for_child = [&]() {
  10296. // No children -> nobody to wait for
  10297. if ( m_children.empty() ) {
  10298. return false;
  10299. }
  10300. // If at least one child started executing, don't wait
  10301. if ( std::find_if(
  10302. m_children.begin(),
  10303. m_children.end(),
  10304. []( TestCaseTracking::ITrackerPtr tracker ) {
  10305. return tracker->hasStarted();
  10306. } ) != m_children.end() ) {
  10307. return false;
  10308. }
  10309. // No children have started. We need to check if they _can_
  10310. // start, and thus we should wait for them, or they cannot
  10311. // start (due to filters), and we shouldn't wait for them
  10312. auto* parent = m_parent;
  10313. // This is safe: there is always at least one section
  10314. // tracker in a test case tracking tree
  10315. while ( !parent->isSectionTracker() ) {
  10316. parent = &( parent->parent() );
  10317. }
  10318. assert( parent &&
  10319. "Missing root (test case) level section" );
  10320. auto const& parentSection =
  10321. static_cast<SectionTracker&>( *parent );
  10322. auto const& filters = parentSection.getFilters();
  10323. // No filters -> no restrictions on running sections
  10324. if ( filters.empty() ) {
  10325. return true;
  10326. }
  10327. for ( auto const& child : m_children ) {
  10328. if ( child->isSectionTracker() &&
  10329. std::find( filters.begin(),
  10330. filters.end(),
  10331. static_cast<SectionTracker&>( *child )
  10332. .trimmedName() ) !=
  10333. filters.end() ) {
  10334. return true;
  10335. }
  10336. }
  10337. return false;
  10338. }();
  10339. // This check is a bit tricky, because m_generator->next()
  10340. // has a side-effect, where it consumes generator's current
  10341. // value, but we do not want to invoke the side-effect if
  10342. // this generator is still waiting for any child to start.
  10343. if ( should_wait_for_child ||
  10344. ( m_runState == CompletedSuccessfully &&
  10345. m_generator->next() ) ) {
  10346. m_children.clear();
  10347. m_runState = Executing;
  10348. }
  10349. }
  10350. // IGeneratorTracker interface
  10351. auto getGenerator() const -> GeneratorBasePtr const& override {
  10352. return m_generator;
  10353. }
  10354. void setGenerator( GeneratorBasePtr&& generator ) override {
  10355. m_generator = std::move( generator );
  10356. }
  10357. };
  10358. GeneratorTracker::~GeneratorTracker() {}
  10359. }
  10360. RunContext::RunContext(IConfigPtr const& _config, IStreamingReporterPtr&& reporter)
  10361. : m_runInfo(_config->name()),
  10362. m_context(getCurrentMutableContext()),
  10363. m_config(_config),
  10364. m_reporter(std::move(reporter)),
  10365. m_lastAssertionInfo{ StringRef(), SourceLineInfo("",0), StringRef(), ResultDisposition::Normal },
  10366. m_includeSuccessfulResults( m_config->includeSuccessfulResults() || m_reporter->getPreferences().shouldReportAllAssertions )
  10367. {
  10368. m_context.setRunner(this);
  10369. m_context.setConfig(m_config);
  10370. m_context.setResultCapture(this);
  10371. m_reporter->testRunStarting(m_runInfo);
  10372. }
  10373. RunContext::~RunContext() {
  10374. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting()));
  10375. }
  10376. void RunContext::testGroupStarting(std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount) {
  10377. m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount));
  10378. }
  10379. void RunContext::testGroupEnded(std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount) {
  10380. m_reporter->testGroupEnded(TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting()));
  10381. }
  10382. Totals RunContext::runTest(TestCase const& testCase) {
  10383. Totals prevTotals = m_totals;
  10384. std::string redirectedCout;
  10385. std::string redirectedCerr;
  10386. auto const& testInfo = testCase.getTestCaseInfo();
  10387. m_reporter->testCaseStarting(testInfo);
  10388. m_activeTestCase = &testCase;
  10389. ITracker& rootTracker = m_trackerContext.startRun();
  10390. assert(rootTracker.isSectionTracker());
  10391. static_cast<SectionTracker&>(rootTracker).addInitialFilters(m_config->getSectionsToRun());
  10392. do {
  10393. m_trackerContext.startCycle();
  10394. m_testCaseTracker = &SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo));
  10395. runCurrentTest(redirectedCout, redirectedCerr);
  10396. } while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting());
  10397. Totals deltaTotals = m_totals.delta(prevTotals);
  10398. if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) {
  10399. deltaTotals.assertions.failed++;
  10400. deltaTotals.testCases.passed--;
  10401. deltaTotals.testCases.failed++;
  10402. }
  10403. m_totals.testCases += deltaTotals.testCases;
  10404. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  10405. deltaTotals,
  10406. redirectedCout,
  10407. redirectedCerr,
  10408. aborting()));
  10409. m_activeTestCase = nullptr;
  10410. m_testCaseTracker = nullptr;
  10411. return deltaTotals;
  10412. }
  10413. IConfigPtr RunContext::config() const {
  10414. return m_config;
  10415. }
  10416. IStreamingReporter& RunContext::reporter() const {
  10417. return *m_reporter;
  10418. }
  10419. void RunContext::assertionEnded(AssertionResult const & result) {
  10420. if (result.getResultType() == ResultWas::Ok) {
  10421. m_totals.assertions.passed++;
  10422. m_lastAssertionPassed = true;
  10423. } else if (!result.isOk()) {
  10424. m_lastAssertionPassed = false;
  10425. if( m_activeTestCase->getTestCaseInfo().okToFail() )
  10426. m_totals.assertions.failedButOk++;
  10427. else
  10428. m_totals.assertions.failed++;
  10429. }
  10430. else {
  10431. m_lastAssertionPassed = true;
  10432. }
  10433. // We have no use for the return value (whether messages should be cleared), because messages were made scoped
  10434. // and should be let to clear themselves out.
  10435. static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals)));
  10436. if (result.getResultType() != ResultWas::Warning)
  10437. m_messageScopes.clear();
  10438. // Reset working state
  10439. resetAssertionInfo();
  10440. m_lastResult = result;
  10441. }
  10442. void RunContext::resetAssertionInfo() {
  10443. m_lastAssertionInfo.macroName = StringRef();
  10444. m_lastAssertionInfo.capturedExpression = "{Unknown expression after the reported line}"_sr;
  10445. }
  10446. bool RunContext::sectionStarted(SectionInfo const & sectionInfo, Counts & assertions) {
  10447. ITracker& sectionTracker = SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(sectionInfo.name, sectionInfo.lineInfo));
  10448. if (!sectionTracker.isOpen())
  10449. return false;
  10450. m_activeSections.push_back(&sectionTracker);
  10451. m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;
  10452. m_reporter->sectionStarting(sectionInfo);
  10453. assertions = m_totals.assertions;
  10454. return true;
  10455. }
  10456. auto RunContext::acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
  10457. using namespace Generators;
  10458. GeneratorTracker& tracker = GeneratorTracker::acquire(m_trackerContext,
  10459. TestCaseTracking::NameAndLocation( static_cast<std::string>(generatorName), lineInfo ) );
  10460. m_lastAssertionInfo.lineInfo = lineInfo;
  10461. return tracker;
  10462. }
  10463. bool RunContext::testForMissingAssertions(Counts& assertions) {
  10464. if (assertions.total() != 0)
  10465. return false;
  10466. if (!m_config->warnAboutMissingAssertions())
  10467. return false;
  10468. if (m_trackerContext.currentTracker().hasChildren())
  10469. return false;
  10470. m_totals.assertions.failed++;
  10471. assertions.failed++;
  10472. return true;
  10473. }
  10474. void RunContext::sectionEnded(SectionEndInfo const & endInfo) {
  10475. Counts assertions = m_totals.assertions - endInfo.prevAssertions;
  10476. bool missingAssertions = testForMissingAssertions(assertions);
  10477. if (!m_activeSections.empty()) {
  10478. m_activeSections.back()->close();
  10479. m_activeSections.pop_back();
  10480. }
  10481. m_reporter->sectionEnded(SectionStats(endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions));
  10482. m_messages.clear();
  10483. m_messageScopes.clear();
  10484. }
  10485. void RunContext::sectionEndedEarly(SectionEndInfo const & endInfo) {
  10486. if (m_unfinishedSections.empty())
  10487. m_activeSections.back()->fail();
  10488. else
  10489. m_activeSections.back()->close();
  10490. m_activeSections.pop_back();
  10491. m_unfinishedSections.push_back(endInfo);
  10492. }
  10493. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  10494. void RunContext::benchmarkPreparing(std::string const& name) {
  10495. m_reporter->benchmarkPreparing(name);
  10496. }
  10497. void RunContext::benchmarkStarting( BenchmarkInfo const& info ) {
  10498. m_reporter->benchmarkStarting( info );
  10499. }
  10500. void RunContext::benchmarkEnded( BenchmarkStats<> const& stats ) {
  10501. m_reporter->benchmarkEnded( stats );
  10502. }
  10503. void RunContext::benchmarkFailed(std::string const & error) {
  10504. m_reporter->benchmarkFailed(error);
  10505. }
  10506. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  10507. void RunContext::pushScopedMessage(MessageInfo const & message) {
  10508. m_messages.push_back(message);
  10509. }
  10510. void RunContext::popScopedMessage(MessageInfo const & message) {
  10511. m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end());
  10512. }
  10513. void RunContext::emplaceUnscopedMessage( MessageBuilder const& builder ) {
  10514. m_messageScopes.emplace_back( builder );
  10515. }
  10516. std::string RunContext::getCurrentTestName() const {
  10517. return m_activeTestCase
  10518. ? m_activeTestCase->getTestCaseInfo().name
  10519. : std::string();
  10520. }
  10521. const AssertionResult * RunContext::getLastResult() const {
  10522. return &(*m_lastResult);
  10523. }
  10524. void RunContext::exceptionEarlyReported() {
  10525. m_shouldReportUnexpected = false;
  10526. }
  10527. void RunContext::handleFatalErrorCondition( StringRef message ) {
  10528. // First notify reporter that bad things happened
  10529. m_reporter->fatalErrorEncountered(message);
  10530. // Don't rebuild the result -- the stringification itself can cause more fatal errors
  10531. // Instead, fake a result data.
  10532. AssertionResultData tempResult( ResultWas::FatalErrorCondition, { false } );
  10533. tempResult.message = static_cast<std::string>(message);
  10534. AssertionResult result(m_lastAssertionInfo, tempResult);
  10535. assertionEnded(result);
  10536. handleUnfinishedSections();
  10537. // Recreate section for test case (as we will lose the one that was in scope)
  10538. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  10539. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
  10540. Counts assertions;
  10541. assertions.failed = 1;
  10542. SectionStats testCaseSectionStats(testCaseSection, assertions, 0, false);
  10543. m_reporter->sectionEnded(testCaseSectionStats);
  10544. auto const& testInfo = m_activeTestCase->getTestCaseInfo();
  10545. Totals deltaTotals;
  10546. deltaTotals.testCases.failed = 1;
  10547. deltaTotals.assertions.failed = 1;
  10548. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  10549. deltaTotals,
  10550. std::string(),
  10551. std::string(),
  10552. false));
  10553. m_totals.testCases.failed++;
  10554. testGroupEnded(std::string(), m_totals, 1, 1);
  10555. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, false));
  10556. }
  10557. bool RunContext::lastAssertionPassed() {
  10558. return m_lastAssertionPassed;
  10559. }
  10560. void RunContext::assertionPassed() {
  10561. m_lastAssertionPassed = true;
  10562. ++m_totals.assertions.passed;
  10563. resetAssertionInfo();
  10564. m_messageScopes.clear();
  10565. }
  10566. bool RunContext::aborting() const {
  10567. return m_totals.assertions.failed >= static_cast<std::size_t>(m_config->abortAfter());
  10568. }
  10569. void RunContext::runCurrentTest(std::string & redirectedCout, std::string & redirectedCerr) {
  10570. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  10571. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
  10572. m_reporter->sectionStarting(testCaseSection);
  10573. Counts prevAssertions = m_totals.assertions;
  10574. double duration = 0;
  10575. m_shouldReportUnexpected = true;
  10576. m_lastAssertionInfo = { "TEST_CASE"_sr, testCaseInfo.lineInfo, StringRef(), ResultDisposition::Normal };
  10577. seedRng(*m_config);
  10578. Timer timer;
  10579. CATCH_TRY {
  10580. if (m_reporter->getPreferences().shouldRedirectStdOut) {
  10581. #if !defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
  10582. RedirectedStreams redirectedStreams(redirectedCout, redirectedCerr);
  10583. timer.start();
  10584. invokeActiveTestCase();
  10585. #else
  10586. OutputRedirect r(redirectedCout, redirectedCerr);
  10587. timer.start();
  10588. invokeActiveTestCase();
  10589. #endif
  10590. } else {
  10591. timer.start();
  10592. invokeActiveTestCase();
  10593. }
  10594. duration = timer.getElapsedSeconds();
  10595. } CATCH_CATCH_ANON (TestFailureException&) {
  10596. // This just means the test was aborted due to failure
  10597. } CATCH_CATCH_ALL {
  10598. // Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under REQUIRE assertions
  10599. // are reported without translation at the point of origin.
  10600. if( m_shouldReportUnexpected ) {
  10601. AssertionReaction dummyReaction;
  10602. handleUnexpectedInflightException( m_lastAssertionInfo, translateActiveException(), dummyReaction );
  10603. }
  10604. }
  10605. Counts assertions = m_totals.assertions - prevAssertions;
  10606. bool missingAssertions = testForMissingAssertions(assertions);
  10607. m_testCaseTracker->close();
  10608. handleUnfinishedSections();
  10609. m_messages.clear();
  10610. m_messageScopes.clear();
  10611. SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions);
  10612. m_reporter->sectionEnded(testCaseSectionStats);
  10613. }
  10614. void RunContext::invokeActiveTestCase() {
  10615. FatalConditionHandlerGuard _(&m_fatalConditionhandler);
  10616. m_activeTestCase->invoke();
  10617. }
  10618. void RunContext::handleUnfinishedSections() {
  10619. // If sections ended prematurely due to an exception we stored their
  10620. // infos here so we can tear them down outside the unwind process.
  10621. for (auto it = m_unfinishedSections.rbegin(),
  10622. itEnd = m_unfinishedSections.rend();
  10623. it != itEnd;
  10624. ++it)
  10625. sectionEnded(*it);
  10626. m_unfinishedSections.clear();
  10627. }
  10628. void RunContext::handleExpr(
  10629. AssertionInfo const& info,
  10630. ITransientExpression const& expr,
  10631. AssertionReaction& reaction
  10632. ) {
  10633. m_reporter->assertionStarting( info );
  10634. bool negated = isFalseTest( info.resultDisposition );
  10635. bool result = expr.getResult() != negated;
  10636. if( result ) {
  10637. if (!m_includeSuccessfulResults) {
  10638. assertionPassed();
  10639. }
  10640. else {
  10641. reportExpr(info, ResultWas::Ok, &expr, negated);
  10642. }
  10643. }
  10644. else {
  10645. reportExpr(info, ResultWas::ExpressionFailed, &expr, negated );
  10646. populateReaction( reaction );
  10647. }
  10648. }
  10649. void RunContext::reportExpr(
  10650. AssertionInfo const &info,
  10651. ResultWas::OfType resultType,
  10652. ITransientExpression const *expr,
  10653. bool negated ) {
  10654. m_lastAssertionInfo = info;
  10655. AssertionResultData data( resultType, LazyExpression( negated ) );
  10656. AssertionResult assertionResult{ info, data };
  10657. assertionResult.m_resultData.lazyExpression.m_transientExpression = expr;
  10658. assertionEnded( assertionResult );
  10659. }
  10660. void RunContext::handleMessage(
  10661. AssertionInfo const& info,
  10662. ResultWas::OfType resultType,
  10663. StringRef const& message,
  10664. AssertionReaction& reaction
  10665. ) {
  10666. m_reporter->assertionStarting( info );
  10667. m_lastAssertionInfo = info;
  10668. AssertionResultData data( resultType, LazyExpression( false ) );
  10669. data.message = static_cast<std::string>(message);
  10670. AssertionResult assertionResult{ m_lastAssertionInfo, data };
  10671. assertionEnded( assertionResult );
  10672. if( !assertionResult.isOk() )
  10673. populateReaction( reaction );
  10674. }
  10675. void RunContext::handleUnexpectedExceptionNotThrown(
  10676. AssertionInfo const& info,
  10677. AssertionReaction& reaction
  10678. ) {
  10679. handleNonExpr(info, Catch::ResultWas::DidntThrowException, reaction);
  10680. }
  10681. void RunContext::handleUnexpectedInflightException(
  10682. AssertionInfo const& info,
  10683. std::string const& message,
  10684. AssertionReaction& reaction
  10685. ) {
  10686. m_lastAssertionInfo = info;
  10687. AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
  10688. data.message = message;
  10689. AssertionResult assertionResult{ info, data };
  10690. assertionEnded( assertionResult );
  10691. populateReaction( reaction );
  10692. }
  10693. void RunContext::populateReaction( AssertionReaction& reaction ) {
  10694. reaction.shouldDebugBreak = m_config->shouldDebugBreak();
  10695. reaction.shouldThrow = aborting() || (m_lastAssertionInfo.resultDisposition & ResultDisposition::Normal);
  10696. }
  10697. void RunContext::handleIncomplete(
  10698. AssertionInfo const& info
  10699. ) {
  10700. m_lastAssertionInfo = info;
  10701. AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
  10702. data.message = "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE";
  10703. AssertionResult assertionResult{ info, data };
  10704. assertionEnded( assertionResult );
  10705. }
  10706. void RunContext::handleNonExpr(
  10707. AssertionInfo const &info,
  10708. ResultWas::OfType resultType,
  10709. AssertionReaction &reaction
  10710. ) {
  10711. m_lastAssertionInfo = info;
  10712. AssertionResultData data( resultType, LazyExpression( false ) );
  10713. AssertionResult assertionResult{ info, data };
  10714. assertionEnded( assertionResult );
  10715. if( !assertionResult.isOk() )
  10716. populateReaction( reaction );
  10717. }
  10718. IResultCapture& getResultCapture() {
  10719. if (auto* capture = getCurrentContext().getResultCapture())
  10720. return *capture;
  10721. else
  10722. CATCH_INTERNAL_ERROR("No result capture instance");
  10723. }
  10724. void seedRng(IConfig const& config) {
  10725. if (config.rngSeed() != 0) {
  10726. std::srand(config.rngSeed());
  10727. rng().seed(config.rngSeed());
  10728. }
  10729. }
  10730. unsigned int rngSeed() {
  10731. return getCurrentContext().getConfig()->rngSeed();
  10732. }
  10733. }
  10734. // end catch_run_context.cpp
  10735. // start catch_section.cpp
  10736. namespace Catch {
  10737. Section::Section( SectionInfo const& info )
  10738. : m_info( info ),
  10739. m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) )
  10740. {
  10741. m_timer.start();
  10742. }
  10743. Section::~Section() {
  10744. if( m_sectionIncluded ) {
  10745. SectionEndInfo endInfo{ m_info, m_assertions, m_timer.getElapsedSeconds() };
  10746. if( uncaught_exceptions() )
  10747. getResultCapture().sectionEndedEarly( endInfo );
  10748. else
  10749. getResultCapture().sectionEnded( endInfo );
  10750. }
  10751. }
  10752. // This indicates whether the section should be executed or not
  10753. Section::operator bool() const {
  10754. return m_sectionIncluded;
  10755. }
  10756. } // end namespace Catch
  10757. // end catch_section.cpp
  10758. // start catch_section_info.cpp
  10759. namespace Catch {
  10760. SectionInfo::SectionInfo
  10761. ( SourceLineInfo const& _lineInfo,
  10762. std::string const& _name )
  10763. : name( _name ),
  10764. lineInfo( _lineInfo )
  10765. {}
  10766. } // end namespace Catch
  10767. // end catch_section_info.cpp
  10768. // start catch_session.cpp
  10769. // start catch_session.h
  10770. #include <memory>
  10771. namespace Catch {
  10772. class Session : NonCopyable {
  10773. public:
  10774. Session();
  10775. ~Session() override;
  10776. void showHelp() const;
  10777. void libIdentify();
  10778. int applyCommandLine( int argc, char const * const * argv );
  10779. #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)
  10780. int applyCommandLine( int argc, wchar_t const * const * argv );
  10781. #endif
  10782. void useConfigData( ConfigData const& configData );
  10783. template<typename CharT>
  10784. int run(int argc, CharT const * const argv[]) {
  10785. if (m_startupExceptions)
  10786. return 1;
  10787. int returnCode = applyCommandLine(argc, argv);
  10788. if (returnCode == 0)
  10789. returnCode = run();
  10790. return returnCode;
  10791. }
  10792. int run();
  10793. clara::Parser const& cli() const;
  10794. void cli( clara::Parser const& newParser );
  10795. ConfigData& configData();
  10796. Config& config();
  10797. private:
  10798. int runInternal();
  10799. clara::Parser m_cli;
  10800. ConfigData m_configData;
  10801. std::shared_ptr<Config> m_config;
  10802. bool m_startupExceptions = false;
  10803. };
  10804. } // end namespace Catch
  10805. // end catch_session.h
  10806. // start catch_version.h
  10807. #include <iosfwd>
  10808. namespace Catch {
  10809. // Versioning information
  10810. struct Version {
  10811. Version( Version const& ) = delete;
  10812. Version& operator=( Version const& ) = delete;
  10813. Version( unsigned int _majorVersion,
  10814. unsigned int _minorVersion,
  10815. unsigned int _patchNumber,
  10816. char const * const _branchName,
  10817. unsigned int _buildNumber );
  10818. unsigned int const majorVersion;
  10819. unsigned int const minorVersion;
  10820. unsigned int const patchNumber;
  10821. // buildNumber is only used if branchName is not null
  10822. char const * const branchName;
  10823. unsigned int const buildNumber;
  10824. friend std::ostream& operator << ( std::ostream& os, Version const& version );
  10825. };
  10826. Version const& libraryVersion();
  10827. }
  10828. // end catch_version.h
  10829. #include <cstdlib>
  10830. #include <iomanip>
  10831. #include <set>
  10832. #include <iterator>
  10833. namespace Catch {
  10834. namespace {
  10835. const int MaxExitCode = 255;
  10836. IStreamingReporterPtr createReporter(std::string const& reporterName, IConfigPtr const& config) {
  10837. auto reporter = Catch::getRegistryHub().getReporterRegistry().create(reporterName, config);
  10838. CATCH_ENFORCE(reporter, "No reporter registered with name: '" << reporterName << "'");
  10839. return reporter;
  10840. }
  10841. IStreamingReporterPtr makeReporter(std::shared_ptr<Config> const& config) {
  10842. if (Catch::getRegistryHub().getReporterRegistry().getListeners().empty()) {
  10843. return createReporter(config->getReporterName(), config);
  10844. }
  10845. // On older platforms, returning std::unique_ptr<ListeningReporter>
  10846. // when the return type is std::unique_ptr<IStreamingReporter>
  10847. // doesn't compile without a std::move call. However, this causes
  10848. // a warning on newer platforms. Thus, we have to work around
  10849. // it a bit and downcast the pointer manually.
  10850. auto ret = std::unique_ptr<IStreamingReporter>(new ListeningReporter);
  10851. auto& multi = static_cast<ListeningReporter&>(*ret);
  10852. auto const& listeners = Catch::getRegistryHub().getReporterRegistry().getListeners();
  10853. for (auto const& listener : listeners) {
  10854. multi.addListener(listener->create(Catch::ReporterConfig(config)));
  10855. }
  10856. multi.addReporter(createReporter(config->getReporterName(), config));
  10857. return ret;
  10858. }
  10859. class TestGroup {
  10860. public:
  10861. explicit TestGroup(std::shared_ptr<Config> const& config)
  10862. : m_config{config}
  10863. , m_context{config, makeReporter(config)}
  10864. {
  10865. auto const& allTestCases = getAllTestCasesSorted(*m_config);
  10866. m_matches = m_config->testSpec().matchesByFilter(allTestCases, *m_config);
  10867. auto const& invalidArgs = m_config->testSpec().getInvalidArgs();
  10868. if (m_matches.empty() && invalidArgs.empty()) {
  10869. for (auto const& test : allTestCases)
  10870. if (!test.isHidden())
  10871. m_tests.emplace(&test);
  10872. } else {
  10873. for (auto const& match : m_matches)
  10874. m_tests.insert(match.tests.begin(), match.tests.end());
  10875. }
  10876. }
  10877. Totals execute() {
  10878. auto const& invalidArgs = m_config->testSpec().getInvalidArgs();
  10879. Totals totals;
  10880. m_context.testGroupStarting(m_config->name(), 1, 1);
  10881. for (auto const& testCase : m_tests) {
  10882. if (!m_context.aborting())
  10883. totals += m_context.runTest(*testCase);
  10884. else
  10885. m_context.reporter().skipTest(*testCase);
  10886. }
  10887. for (auto const& match : m_matches) {
  10888. if (match.tests.empty()) {
  10889. m_context.reporter().noMatchingTestCases(match.name);
  10890. totals.error = -1;
  10891. }
  10892. }
  10893. if (!invalidArgs.empty()) {
  10894. for (auto const& invalidArg: invalidArgs)
  10895. m_context.reporter().reportInvalidArguments(invalidArg);
  10896. }
  10897. m_context.testGroupEnded(m_config->name(), totals, 1, 1);
  10898. return totals;
  10899. }
  10900. private:
  10901. using Tests = std::set<TestCase const*>;
  10902. std::shared_ptr<Config> m_config;
  10903. RunContext m_context;
  10904. Tests m_tests;
  10905. TestSpec::Matches m_matches;
  10906. };
  10907. void applyFilenamesAsTags(Catch::IConfig const& config) {
  10908. auto& tests = const_cast<std::vector<TestCase>&>(getAllTestCasesSorted(config));
  10909. for (auto& testCase : tests) {
  10910. auto tags = testCase.tags;
  10911. std::string filename = testCase.lineInfo.file;
  10912. auto lastSlash = filename.find_last_of("\\/");
  10913. if (lastSlash != std::string::npos) {
  10914. filename.erase(0, lastSlash);
  10915. filename[0] = '#';
  10916. }
  10917. else
  10918. {
  10919. filename.insert(0, "#");
  10920. }
  10921. auto lastDot = filename.find_last_of('.');
  10922. if (lastDot != std::string::npos) {
  10923. filename.erase(lastDot);
  10924. }
  10925. tags.push_back(std::move(filename));
  10926. setTags(testCase, tags);
  10927. }
  10928. }
  10929. } // anon namespace
  10930. Session::Session() {
  10931. static bool alreadyInstantiated = false;
  10932. if( alreadyInstantiated ) {
  10933. CATCH_TRY { CATCH_INTERNAL_ERROR( "Only one instance of Catch::Session can ever be used" ); }
  10934. CATCH_CATCH_ALL { getMutableRegistryHub().registerStartupException(); }
  10935. }
  10936. // There cannot be exceptions at startup in no-exception mode.
  10937. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  10938. const auto& exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions();
  10939. if ( !exceptions.empty() ) {
  10940. config();
  10941. getCurrentMutableContext().setConfig(m_config);
  10942. m_startupExceptions = true;
  10943. Colour colourGuard( Colour::Red );
  10944. Catch::cerr() << "Errors occurred during startup!" << '\n';
  10945. // iterate over all exceptions and notify user
  10946. for ( const auto& ex_ptr : exceptions ) {
  10947. try {
  10948. std::rethrow_exception(ex_ptr);
  10949. } catch ( std::exception const& ex ) {
  10950. Catch::cerr() << Column( ex.what() ).indent(2) << '\n';
  10951. }
  10952. }
  10953. }
  10954. #endif
  10955. alreadyInstantiated = true;
  10956. m_cli = makeCommandLineParser( m_configData );
  10957. }
  10958. Session::~Session() {
  10959. Catch::cleanUp();
  10960. }
  10961. void Session::showHelp() const {
  10962. Catch::cout()
  10963. << "\nCatch v" << libraryVersion() << "\n"
  10964. << m_cli << std::endl
  10965. << "For more detailed usage please see the project docs\n" << std::endl;
  10966. }
  10967. void Session::libIdentify() {
  10968. Catch::cout()
  10969. << std::left << std::setw(16) << "description: " << "A Catch2 test executable\n"
  10970. << std::left << std::setw(16) << "category: " << "testframework\n"
  10971. << std::left << std::setw(16) << "framework: " << "Catch Test\n"
  10972. << std::left << std::setw(16) << "version: " << libraryVersion() << std::endl;
  10973. }
  10974. int Session::applyCommandLine( int argc, char const * const * argv ) {
  10975. if( m_startupExceptions )
  10976. return 1;
  10977. auto result = m_cli.parse( clara::Args( argc, argv ) );
  10978. if( !result ) {
  10979. config();
  10980. getCurrentMutableContext().setConfig(m_config);
  10981. Catch::cerr()
  10982. << Colour( Colour::Red )
  10983. << "\nError(s) in input:\n"
  10984. << Column( result.errorMessage() ).indent( 2 )
  10985. << "\n\n";
  10986. Catch::cerr() << "Run with -? for usage\n" << std::endl;
  10987. return MaxExitCode;
  10988. }
  10989. if( m_configData.showHelp )
  10990. showHelp();
  10991. if( m_configData.libIdentify )
  10992. libIdentify();
  10993. m_config.reset();
  10994. return 0;
  10995. }
  10996. #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)
  10997. int Session::applyCommandLine( int argc, wchar_t const * const * argv ) {
  10998. char **utf8Argv = new char *[ argc ];
  10999. for ( int i = 0; i < argc; ++i ) {
  11000. int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, nullptr, 0, nullptr, nullptr );
  11001. utf8Argv[ i ] = new char[ bufSize ];
  11002. WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, nullptr, nullptr );
  11003. }
  11004. int returnCode = applyCommandLine( argc, utf8Argv );
  11005. for ( int i = 0; i < argc; ++i )
  11006. delete [] utf8Argv[ i ];
  11007. delete [] utf8Argv;
  11008. return returnCode;
  11009. }
  11010. #endif
  11011. void Session::useConfigData( ConfigData const& configData ) {
  11012. m_configData = configData;
  11013. m_config.reset();
  11014. }
  11015. int Session::run() {
  11016. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeStart ) != 0 ) {
  11017. Catch::cout() << "...waiting for enter/ return before starting" << std::endl;
  11018. static_cast<void>(std::getchar());
  11019. }
  11020. int exitCode = runInternal();
  11021. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeExit ) != 0 ) {
  11022. Catch::cout() << "...waiting for enter/ return before exiting, with code: " << exitCode << std::endl;
  11023. static_cast<void>(std::getchar());
  11024. }
  11025. return exitCode;
  11026. }
  11027. clara::Parser const& Session::cli() const {
  11028. return m_cli;
  11029. }
  11030. void Session::cli( clara::Parser const& newParser ) {
  11031. m_cli = newParser;
  11032. }
  11033. ConfigData& Session::configData() {
  11034. return m_configData;
  11035. }
  11036. Config& Session::config() {
  11037. if( !m_config )
  11038. m_config = std::make_shared<Config>( m_configData );
  11039. return *m_config;
  11040. }
  11041. int Session::runInternal() {
  11042. if( m_startupExceptions )
  11043. return 1;
  11044. if (m_configData.showHelp || m_configData.libIdentify) {
  11045. return 0;
  11046. }
  11047. CATCH_TRY {
  11048. config(); // Force config to be constructed
  11049. seedRng( *m_config );
  11050. if( m_configData.filenamesAsTags )
  11051. applyFilenamesAsTags( *m_config );
  11052. // Handle list request
  11053. if( Option<std::size_t> listed = list( m_config ) )
  11054. return static_cast<int>( *listed );
  11055. TestGroup tests { m_config };
  11056. auto const totals = tests.execute();
  11057. if( m_config->warnAboutNoTests() && totals.error == -1 )
  11058. return 2;
  11059. // Note that on unices only the lower 8 bits are usually used, clamping
  11060. // the return value to 255 prevents false negative when some multiple
  11061. // of 256 tests has failed
  11062. return (std::min) (MaxExitCode, (std::max) (totals.error, static_cast<int>(totals.assertions.failed)));
  11063. }
  11064. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  11065. catch( std::exception& ex ) {
  11066. Catch::cerr() << ex.what() << std::endl;
  11067. return MaxExitCode;
  11068. }
  11069. #endif
  11070. }
  11071. } // end namespace Catch
  11072. // end catch_session.cpp
  11073. // start catch_singletons.cpp
  11074. #include <vector>
  11075. namespace Catch {
  11076. namespace {
  11077. static auto getSingletons() -> std::vector<ISingleton*>*& {
  11078. static std::vector<ISingleton*>* g_singletons = nullptr;
  11079. if( !g_singletons )
  11080. g_singletons = new std::vector<ISingleton*>();
  11081. return g_singletons;
  11082. }
  11083. }
  11084. ISingleton::~ISingleton() {}
  11085. void addSingleton(ISingleton* singleton ) {
  11086. getSingletons()->push_back( singleton );
  11087. }
  11088. void cleanupSingletons() {
  11089. auto& singletons = getSingletons();
  11090. for( auto singleton : *singletons )
  11091. delete singleton;
  11092. delete singletons;
  11093. singletons = nullptr;
  11094. }
  11095. } // namespace Catch
  11096. // end catch_singletons.cpp
  11097. // start catch_startup_exception_registry.cpp
  11098. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  11099. namespace Catch {
  11100. void StartupExceptionRegistry::add( std::exception_ptr const& exception ) noexcept {
  11101. CATCH_TRY {
  11102. m_exceptions.push_back(exception);
  11103. } CATCH_CATCH_ALL {
  11104. // If we run out of memory during start-up there's really not a lot more we can do about it
  11105. std::terminate();
  11106. }
  11107. }
  11108. std::vector<std::exception_ptr> const& StartupExceptionRegistry::getExceptions() const noexcept {
  11109. return m_exceptions;
  11110. }
  11111. } // end namespace Catch
  11112. #endif
  11113. // end catch_startup_exception_registry.cpp
  11114. // start catch_stream.cpp
  11115. #include <cstdio>
  11116. #include <iostream>
  11117. #include <fstream>
  11118. #include <sstream>
  11119. #include <vector>
  11120. #include <memory>
  11121. namespace Catch {
  11122. Catch::IStream::~IStream() = default;
  11123. namespace Detail { namespace {
  11124. template<typename WriterF, std::size_t bufferSize=256>
  11125. class StreamBufImpl : public std::streambuf {
  11126. char data[bufferSize];
  11127. WriterF m_writer;
  11128. public:
  11129. StreamBufImpl() {
  11130. setp( data, data + sizeof(data) );
  11131. }
  11132. ~StreamBufImpl() noexcept {
  11133. StreamBufImpl::sync();
  11134. }
  11135. private:
  11136. int overflow( int c ) override {
  11137. sync();
  11138. if( c != EOF ) {
  11139. if( pbase() == epptr() )
  11140. m_writer( std::string( 1, static_cast<char>( c ) ) );
  11141. else
  11142. sputc( static_cast<char>( c ) );
  11143. }
  11144. return 0;
  11145. }
  11146. int sync() override {
  11147. if( pbase() != pptr() ) {
  11148. m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) );
  11149. setp( pbase(), epptr() );
  11150. }
  11151. return 0;
  11152. }
  11153. };
  11154. ///////////////////////////////////////////////////////////////////////////
  11155. struct OutputDebugWriter {
  11156. void operator()( std::string const&str ) {
  11157. writeToDebugConsole( str );
  11158. }
  11159. };
  11160. ///////////////////////////////////////////////////////////////////////////
  11161. class FileStream : public IStream {
  11162. mutable std::ofstream m_ofs;
  11163. public:
  11164. FileStream( StringRef filename ) {
  11165. m_ofs.open( filename.c_str() );
  11166. CATCH_ENFORCE( !m_ofs.fail(), "Unable to open file: '" << filename << "'" );
  11167. }
  11168. ~FileStream() override = default;
  11169. public: // IStream
  11170. std::ostream& stream() const override {
  11171. return m_ofs;
  11172. }
  11173. };
  11174. ///////////////////////////////////////////////////////////////////////////
  11175. class CoutStream : public IStream {
  11176. mutable std::ostream m_os;
  11177. public:
  11178. // Store the streambuf from cout up-front because
  11179. // cout may get redirected when running tests
  11180. CoutStream() : m_os( Catch::cout().rdbuf() ) {}
  11181. ~CoutStream() override = default;
  11182. public: // IStream
  11183. std::ostream& stream() const override { return m_os; }
  11184. };
  11185. ///////////////////////////////////////////////////////////////////////////
  11186. class DebugOutStream : public IStream {
  11187. std::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf;
  11188. mutable std::ostream m_os;
  11189. public:
  11190. DebugOutStream()
  11191. : m_streamBuf( new StreamBufImpl<OutputDebugWriter>() ),
  11192. m_os( m_streamBuf.get() )
  11193. {}
  11194. ~DebugOutStream() override = default;
  11195. public: // IStream
  11196. std::ostream& stream() const override { return m_os; }
  11197. };
  11198. }} // namespace anon::detail
  11199. ///////////////////////////////////////////////////////////////////////////
  11200. auto makeStream( StringRef const &filename ) -> IStream const* {
  11201. if( filename.empty() )
  11202. return new Detail::CoutStream();
  11203. else if( filename[0] == '%' ) {
  11204. if( filename == "%debug" )
  11205. return new Detail::DebugOutStream();
  11206. else
  11207. CATCH_ERROR( "Unrecognised stream: '" << filename << "'" );
  11208. }
  11209. else
  11210. return new Detail::FileStream( filename );
  11211. }
  11212. // This class encapsulates the idea of a pool of ostringstreams that can be reused.
  11213. struct StringStreams {
  11214. std::vector<std::unique_ptr<std::ostringstream>> m_streams;
  11215. std::vector<std::size_t> m_unused;
  11216. std::ostringstream m_referenceStream; // Used for copy state/ flags from
  11217. auto add() -> std::size_t {
  11218. if( m_unused.empty() ) {
  11219. m_streams.push_back( std::unique_ptr<std::ostringstream>( new std::ostringstream ) );
  11220. return m_streams.size()-1;
  11221. }
  11222. else {
  11223. auto index = m_unused.back();
  11224. m_unused.pop_back();
  11225. return index;
  11226. }
  11227. }
  11228. void release( std::size_t index ) {
  11229. m_streams[index]->copyfmt( m_referenceStream ); // Restore initial flags and other state
  11230. m_unused.push_back(index);
  11231. }
  11232. };
  11233. ReusableStringStream::ReusableStringStream()
  11234. : m_index( Singleton<StringStreams>::getMutable().add() ),
  11235. m_oss( Singleton<StringStreams>::getMutable().m_streams[m_index].get() )
  11236. {}
  11237. ReusableStringStream::~ReusableStringStream() {
  11238. static_cast<std::ostringstream*>( m_oss )->str("");
  11239. m_oss->clear();
  11240. Singleton<StringStreams>::getMutable().release( m_index );
  11241. }
  11242. auto ReusableStringStream::str() const -> std::string {
  11243. return static_cast<std::ostringstream*>( m_oss )->str();
  11244. }
  11245. ///////////////////////////////////////////////////////////////////////////
  11246. #ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions
  11247. std::ostream& cout() { return std::cout; }
  11248. std::ostream& cerr() { return std::cerr; }
  11249. std::ostream& clog() { return std::clog; }
  11250. #endif
  11251. }
  11252. // end catch_stream.cpp
  11253. // start catch_string_manip.cpp
  11254. #include <algorithm>
  11255. #include <ostream>
  11256. #include <cstring>
  11257. #include <cctype>
  11258. #include <vector>
  11259. namespace Catch {
  11260. namespace {
  11261. char toLowerCh(char c) {
  11262. return static_cast<char>( std::tolower( static_cast<unsigned char>(c) ) );
  11263. }
  11264. }
  11265. bool startsWith( std::string const& s, std::string const& prefix ) {
  11266. return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
  11267. }
  11268. bool startsWith( std::string const& s, char prefix ) {
  11269. return !s.empty() && s[0] == prefix;
  11270. }
  11271. bool endsWith( std::string const& s, std::string const& suffix ) {
  11272. return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
  11273. }
  11274. bool endsWith( std::string const& s, char suffix ) {
  11275. return !s.empty() && s[s.size()-1] == suffix;
  11276. }
  11277. bool contains( std::string const& s, std::string const& infix ) {
  11278. return s.find( infix ) != std::string::npos;
  11279. }
  11280. void toLowerInPlace( std::string& s ) {
  11281. std::transform( s.begin(), s.end(), s.begin(), toLowerCh );
  11282. }
  11283. std::string toLower( std::string const& s ) {
  11284. std::string lc = s;
  11285. toLowerInPlace( lc );
  11286. return lc;
  11287. }
  11288. std::string trim( std::string const& str ) {
  11289. static char const* whitespaceChars = "\n\r\t ";
  11290. std::string::size_type start = str.find_first_not_of( whitespaceChars );
  11291. std::string::size_type end = str.find_last_not_of( whitespaceChars );
  11292. return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string();
  11293. }
  11294. StringRef trim(StringRef ref) {
  11295. const auto is_ws = [](char c) {
  11296. return c == ' ' || c == '\t' || c == '\n' || c == '\r';
  11297. };
  11298. size_t real_begin = 0;
  11299. while (real_begin < ref.size() && is_ws(ref[real_begin])) { ++real_begin; }
  11300. size_t real_end = ref.size();
  11301. while (real_end > real_begin && is_ws(ref[real_end - 1])) { --real_end; }
  11302. return ref.substr(real_begin, real_end - real_begin);
  11303. }
  11304. bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) {
  11305. bool replaced = false;
  11306. std::size_t i = str.find( replaceThis );
  11307. while( i != std::string::npos ) {
  11308. replaced = true;
  11309. str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() );
  11310. if( i < str.size()-withThis.size() )
  11311. i = str.find( replaceThis, i+withThis.size() );
  11312. else
  11313. i = std::string::npos;
  11314. }
  11315. return replaced;
  11316. }
  11317. std::vector<StringRef> splitStringRef( StringRef str, char delimiter ) {
  11318. std::vector<StringRef> subStrings;
  11319. std::size_t start = 0;
  11320. for(std::size_t pos = 0; pos < str.size(); ++pos ) {
  11321. if( str[pos] == delimiter ) {
  11322. if( pos - start > 1 )
  11323. subStrings.push_back( str.substr( start, pos-start ) );
  11324. start = pos+1;
  11325. }
  11326. }
  11327. if( start < str.size() )
  11328. subStrings.push_back( str.substr( start, str.size()-start ) );
  11329. return subStrings;
  11330. }
  11331. pluralise::pluralise( std::size_t count, std::string const& label )
  11332. : m_count( count ),
  11333. m_label( label )
  11334. {}
  11335. std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) {
  11336. os << pluraliser.m_count << ' ' << pluraliser.m_label;
  11337. if( pluraliser.m_count != 1 )
  11338. os << 's';
  11339. return os;
  11340. }
  11341. }
  11342. // end catch_string_manip.cpp
  11343. // start catch_stringref.cpp
  11344. #include <algorithm>
  11345. #include <ostream>
  11346. #include <cstring>
  11347. #include <cstdint>
  11348. namespace Catch {
  11349. StringRef::StringRef( char const* rawChars ) noexcept
  11350. : StringRef( rawChars, static_cast<StringRef::size_type>(std::strlen(rawChars) ) )
  11351. {}
  11352. auto StringRef::c_str() const -> char const* {
  11353. CATCH_ENFORCE(isNullTerminated(), "Called StringRef::c_str() on a non-null-terminated instance");
  11354. return m_start;
  11355. }
  11356. auto StringRef::data() const noexcept -> char const* {
  11357. return m_start;
  11358. }
  11359. auto StringRef::substr( size_type start, size_type size ) const noexcept -> StringRef {
  11360. if (start < m_size) {
  11361. return StringRef(m_start + start, (std::min)(m_size - start, size));
  11362. } else {
  11363. return StringRef();
  11364. }
  11365. }
  11366. auto StringRef::operator == ( StringRef const& other ) const noexcept -> bool {
  11367. return m_size == other.m_size
  11368. && (std::memcmp( m_start, other.m_start, m_size ) == 0);
  11369. }
  11370. auto operator << ( std::ostream& os, StringRef const& str ) -> std::ostream& {
  11371. return os.write(str.data(), str.size());
  11372. }
  11373. auto operator+=( std::string& lhs, StringRef const& rhs ) -> std::string& {
  11374. lhs.append(rhs.data(), rhs.size());
  11375. return lhs;
  11376. }
  11377. } // namespace Catch
  11378. // end catch_stringref.cpp
  11379. // start catch_tag_alias.cpp
  11380. namespace Catch {
  11381. TagAlias::TagAlias(std::string const & _tag, SourceLineInfo _lineInfo): tag(_tag), lineInfo(_lineInfo) {}
  11382. }
  11383. // end catch_tag_alias.cpp
  11384. // start catch_tag_alias_autoregistrar.cpp
  11385. namespace Catch {
  11386. RegistrarForTagAliases::RegistrarForTagAliases(char const* alias, char const* tag, SourceLineInfo const& lineInfo) {
  11387. CATCH_TRY {
  11388. getMutableRegistryHub().registerTagAlias(alias, tag, lineInfo);
  11389. } CATCH_CATCH_ALL {
  11390. // Do not throw when constructing global objects, instead register the exception to be processed later
  11391. getMutableRegistryHub().registerStartupException();
  11392. }
  11393. }
  11394. }
  11395. // end catch_tag_alias_autoregistrar.cpp
  11396. // start catch_tag_alias_registry.cpp
  11397. #include <sstream>
  11398. namespace Catch {
  11399. TagAliasRegistry::~TagAliasRegistry() {}
  11400. TagAlias const* TagAliasRegistry::find( std::string const& alias ) const {
  11401. auto it = m_registry.find( alias );
  11402. if( it != m_registry.end() )
  11403. return &(it->second);
  11404. else
  11405. return nullptr;
  11406. }
  11407. std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const {
  11408. std::string expandedTestSpec = unexpandedTestSpec;
  11409. for( auto const& registryKvp : m_registry ) {
  11410. std::size_t pos = expandedTestSpec.find( registryKvp.first );
  11411. if( pos != std::string::npos ) {
  11412. expandedTestSpec = expandedTestSpec.substr( 0, pos ) +
  11413. registryKvp.second.tag +
  11414. expandedTestSpec.substr( pos + registryKvp.first.size() );
  11415. }
  11416. }
  11417. return expandedTestSpec;
  11418. }
  11419. void TagAliasRegistry::add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) {
  11420. CATCH_ENFORCE( startsWith(alias, "[@") && endsWith(alias, ']'),
  11421. "error: tag alias, '" << alias << "' is not of the form [@alias name].\n" << lineInfo );
  11422. CATCH_ENFORCE( m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second,
  11423. "error: tag alias, '" << alias << "' already registered.\n"
  11424. << "\tFirst seen at: " << find(alias)->lineInfo << "\n"
  11425. << "\tRedefined at: " << lineInfo );
  11426. }
  11427. ITagAliasRegistry::~ITagAliasRegistry() {}
  11428. ITagAliasRegistry const& ITagAliasRegistry::get() {
  11429. return getRegistryHub().getTagAliasRegistry();
  11430. }
  11431. } // end namespace Catch
  11432. // end catch_tag_alias_registry.cpp
  11433. // start catch_test_case_info.cpp
  11434. #include <cctype>
  11435. #include <exception>
  11436. #include <algorithm>
  11437. #include <sstream>
  11438. namespace Catch {
  11439. namespace {
  11440. TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) {
  11441. if( startsWith( tag, '.' ) ||
  11442. tag == "!hide" )
  11443. return TestCaseInfo::IsHidden;
  11444. else if( tag == "!throws" )
  11445. return TestCaseInfo::Throws;
  11446. else if( tag == "!shouldfail" )
  11447. return TestCaseInfo::ShouldFail;
  11448. else if( tag == "!mayfail" )
  11449. return TestCaseInfo::MayFail;
  11450. else if( tag == "!nonportable" )
  11451. return TestCaseInfo::NonPortable;
  11452. else if( tag == "!benchmark" )
  11453. return static_cast<TestCaseInfo::SpecialProperties>( TestCaseInfo::Benchmark | TestCaseInfo::IsHidden );
  11454. else
  11455. return TestCaseInfo::None;
  11456. }
  11457. bool isReservedTag( std::string const& tag ) {
  11458. return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !std::isalnum( static_cast<unsigned char>(tag[0]) );
  11459. }
  11460. void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) {
  11461. CATCH_ENFORCE( !isReservedTag(tag),
  11462. "Tag name: [" << tag << "] is not allowed.\n"
  11463. << "Tag names starting with non alphanumeric characters are reserved\n"
  11464. << _lineInfo );
  11465. }
  11466. }
  11467. TestCase makeTestCase( ITestInvoker* _testCase,
  11468. std::string const& _className,
  11469. NameAndTags const& nameAndTags,
  11470. SourceLineInfo const& _lineInfo )
  11471. {
  11472. bool isHidden = false;
  11473. // Parse out tags
  11474. std::vector<std::string> tags;
  11475. std::string desc, tag;
  11476. bool inTag = false;
  11477. for (char c : nameAndTags.tags) {
  11478. if( !inTag ) {
  11479. if( c == '[' )
  11480. inTag = true;
  11481. else
  11482. desc += c;
  11483. }
  11484. else {
  11485. if( c == ']' ) {
  11486. TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag );
  11487. if( ( prop & TestCaseInfo::IsHidden ) != 0 )
  11488. isHidden = true;
  11489. else if( prop == TestCaseInfo::None )
  11490. enforceNotReservedTag( tag, _lineInfo );
  11491. // Merged hide tags like `[.approvals]` should be added as
  11492. // `[.][approvals]`. The `[.]` is added at later point, so
  11493. // we only strip the prefix
  11494. if (startsWith(tag, '.') && tag.size() > 1) {
  11495. tag.erase(0, 1);
  11496. }
  11497. tags.push_back( tag );
  11498. tag.clear();
  11499. inTag = false;
  11500. }
  11501. else
  11502. tag += c;
  11503. }
  11504. }
  11505. if( isHidden ) {
  11506. // Add all "hidden" tags to make them behave identically
  11507. tags.insert( tags.end(), { ".", "!hide" } );
  11508. }
  11509. TestCaseInfo info( static_cast<std::string>(nameAndTags.name), _className, desc, tags, _lineInfo );
  11510. return TestCase( _testCase, std::move(info) );
  11511. }
  11512. void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags ) {
  11513. std::sort(begin(tags), end(tags));
  11514. tags.erase(std::unique(begin(tags), end(tags)), end(tags));
  11515. testCaseInfo.lcaseTags.clear();
  11516. for( auto const& tag : tags ) {
  11517. std::string lcaseTag = toLower( tag );
  11518. testCaseInfo.properties = static_cast<TestCaseInfo::SpecialProperties>( testCaseInfo.properties | parseSpecialTag( lcaseTag ) );
  11519. testCaseInfo.lcaseTags.push_back( lcaseTag );
  11520. }
  11521. testCaseInfo.tags = std::move(tags);
  11522. }
  11523. TestCaseInfo::TestCaseInfo( std::string const& _name,
  11524. std::string const& _className,
  11525. std::string const& _description,
  11526. std::vector<std::string> const& _tags,
  11527. SourceLineInfo const& _lineInfo )
  11528. : name( _name ),
  11529. className( _className ),
  11530. description( _description ),
  11531. lineInfo( _lineInfo ),
  11532. properties( None )
  11533. {
  11534. setTags( *this, _tags );
  11535. }
  11536. bool TestCaseInfo::isHidden() const {
  11537. return ( properties & IsHidden ) != 0;
  11538. }
  11539. bool TestCaseInfo::throws() const {
  11540. return ( properties & Throws ) != 0;
  11541. }
  11542. bool TestCaseInfo::okToFail() const {
  11543. return ( properties & (ShouldFail | MayFail ) ) != 0;
  11544. }
  11545. bool TestCaseInfo::expectedToFail() const {
  11546. return ( properties & (ShouldFail ) ) != 0;
  11547. }
  11548. std::string TestCaseInfo::tagsAsString() const {
  11549. std::string ret;
  11550. // '[' and ']' per tag
  11551. std::size_t full_size = 2 * tags.size();
  11552. for (const auto& tag : tags) {
  11553. full_size += tag.size();
  11554. }
  11555. ret.reserve(full_size);
  11556. for (const auto& tag : tags) {
  11557. ret.push_back('[');
  11558. ret.append(tag);
  11559. ret.push_back(']');
  11560. }
  11561. return ret;
  11562. }
  11563. TestCase::TestCase( ITestInvoker* testCase, TestCaseInfo&& info ) : TestCaseInfo( std::move(info) ), test( testCase ) {}
  11564. TestCase TestCase::withName( std::string const& _newName ) const {
  11565. TestCase other( *this );
  11566. other.name = _newName;
  11567. return other;
  11568. }
  11569. void TestCase::invoke() const {
  11570. test->invoke();
  11571. }
  11572. bool TestCase::operator == ( TestCase const& other ) const {
  11573. return test.get() == other.test.get() &&
  11574. name == other.name &&
  11575. className == other.className;
  11576. }
  11577. bool TestCase::operator < ( TestCase const& other ) const {
  11578. return name < other.name;
  11579. }
  11580. TestCaseInfo const& TestCase::getTestCaseInfo() const
  11581. {
  11582. return *this;
  11583. }
  11584. } // end namespace Catch
  11585. // end catch_test_case_info.cpp
  11586. // start catch_test_case_registry_impl.cpp
  11587. #include <algorithm>
  11588. #include <sstream>
  11589. namespace Catch {
  11590. namespace {
  11591. struct TestHasher {
  11592. using hash_t = uint64_t;
  11593. explicit TestHasher( hash_t hashSuffix ):
  11594. m_hashSuffix{ hashSuffix } {}
  11595. uint32_t operator()( TestCase const& t ) const {
  11596. // FNV-1a hash with multiplication fold.
  11597. const hash_t prime = 1099511628211u;
  11598. hash_t hash = 14695981039346656037u;
  11599. for ( const char c : t.name ) {
  11600. hash ^= c;
  11601. hash *= prime;
  11602. }
  11603. hash ^= m_hashSuffix;
  11604. hash *= prime;
  11605. const uint32_t low{ static_cast<uint32_t>( hash ) };
  11606. const uint32_t high{ static_cast<uint32_t>( hash >> 32 ) };
  11607. return low * high;
  11608. }
  11609. private:
  11610. hash_t m_hashSuffix;
  11611. };
  11612. } // end unnamed namespace
  11613. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases ) {
  11614. switch( config.runOrder() ) {
  11615. case RunTests::InDeclarationOrder:
  11616. // already in declaration order
  11617. break;
  11618. case RunTests::InLexicographicalOrder: {
  11619. std::vector<TestCase> sorted = unsortedTestCases;
  11620. std::sort( sorted.begin(), sorted.end() );
  11621. return sorted;
  11622. }
  11623. case RunTests::InRandomOrder: {
  11624. seedRng( config );
  11625. TestHasher h{ config.rngSeed() };
  11626. using hashedTest = std::pair<TestHasher::hash_t, TestCase const*>;
  11627. std::vector<hashedTest> indexed_tests;
  11628. indexed_tests.reserve( unsortedTestCases.size() );
  11629. for (auto const& testCase : unsortedTestCases) {
  11630. indexed_tests.emplace_back(h(testCase), &testCase);
  11631. }
  11632. std::sort(indexed_tests.begin(), indexed_tests.end(),
  11633. [](hashedTest const& lhs, hashedTest const& rhs) {
  11634. if (lhs.first == rhs.first) {
  11635. return lhs.second->name < rhs.second->name;
  11636. }
  11637. return lhs.first < rhs.first;
  11638. });
  11639. std::vector<TestCase> sorted;
  11640. sorted.reserve( indexed_tests.size() );
  11641. for (auto const& hashed : indexed_tests) {
  11642. sorted.emplace_back(*hashed.second);
  11643. }
  11644. return sorted;
  11645. }
  11646. }
  11647. return unsortedTestCases;
  11648. }
  11649. bool isThrowSafe( TestCase const& testCase, IConfig const& config ) {
  11650. return !testCase.throws() || config.allowThrows();
  11651. }
  11652. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ) {
  11653. return testSpec.matches( testCase ) && isThrowSafe( testCase, config );
  11654. }
  11655. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions ) {
  11656. std::set<TestCase> seenFunctions;
  11657. for( auto const& function : functions ) {
  11658. auto prev = seenFunctions.insert( function );
  11659. CATCH_ENFORCE( prev.second,
  11660. "error: TEST_CASE( \"" << function.name << "\" ) already defined.\n"
  11661. << "\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo << "\n"
  11662. << "\tRedefined at " << function.getTestCaseInfo().lineInfo );
  11663. }
  11664. }
  11665. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config ) {
  11666. std::vector<TestCase> filtered;
  11667. filtered.reserve( testCases.size() );
  11668. for (auto const& testCase : testCases) {
  11669. if ((!testSpec.hasFilters() && !testCase.isHidden()) ||
  11670. (testSpec.hasFilters() && matchTest(testCase, testSpec, config))) {
  11671. filtered.push_back(testCase);
  11672. }
  11673. }
  11674. return filtered;
  11675. }
  11676. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config ) {
  11677. return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config );
  11678. }
  11679. void TestRegistry::registerTest( TestCase const& testCase ) {
  11680. std::string name = testCase.getTestCaseInfo().name;
  11681. if( name.empty() ) {
  11682. ReusableStringStream rss;
  11683. rss << "Anonymous test case " << ++m_unnamedCount;
  11684. return registerTest( testCase.withName( rss.str() ) );
  11685. }
  11686. m_functions.push_back( testCase );
  11687. }
  11688. std::vector<TestCase> const& TestRegistry::getAllTests() const {
  11689. return m_functions;
  11690. }
  11691. std::vector<TestCase> const& TestRegistry::getAllTestsSorted( IConfig const& config ) const {
  11692. if( m_sortedFunctions.empty() )
  11693. enforceNoDuplicateTestCases( m_functions );
  11694. if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) {
  11695. m_sortedFunctions = sortTests( config, m_functions );
  11696. m_currentSortOrder = config.runOrder();
  11697. }
  11698. return m_sortedFunctions;
  11699. }
  11700. ///////////////////////////////////////////////////////////////////////////
  11701. TestInvokerAsFunction::TestInvokerAsFunction( void(*testAsFunction)() ) noexcept : m_testAsFunction( testAsFunction ) {}
  11702. void TestInvokerAsFunction::invoke() const {
  11703. m_testAsFunction();
  11704. }
  11705. std::string extractClassName( StringRef const& classOrQualifiedMethodName ) {
  11706. std::string className(classOrQualifiedMethodName);
  11707. if( startsWith( className, '&' ) )
  11708. {
  11709. std::size_t lastColons = className.rfind( "::" );
  11710. std::size_t penultimateColons = className.rfind( "::", lastColons-1 );
  11711. if( penultimateColons == std::string::npos )
  11712. penultimateColons = 1;
  11713. className = className.substr( penultimateColons, lastColons-penultimateColons );
  11714. }
  11715. return className;
  11716. }
  11717. } // end namespace Catch
  11718. // end catch_test_case_registry_impl.cpp
  11719. // start catch_test_case_tracker.cpp
  11720. #include <algorithm>
  11721. #include <cassert>
  11722. #include <stdexcept>
  11723. #include <memory>
  11724. #include <sstream>
  11725. #if defined(__clang__)
  11726. # pragma clang diagnostic push
  11727. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  11728. #endif
  11729. namespace Catch {
  11730. namespace TestCaseTracking {
  11731. NameAndLocation::NameAndLocation( std::string const& _name, SourceLineInfo const& _location )
  11732. : name( _name ),
  11733. location( _location )
  11734. {}
  11735. ITracker::~ITracker() = default;
  11736. ITracker& TrackerContext::startRun() {
  11737. m_rootTracker = std::make_shared<SectionTracker>( NameAndLocation( "{root}", CATCH_INTERNAL_LINEINFO ), *this, nullptr );
  11738. m_currentTracker = nullptr;
  11739. m_runState = Executing;
  11740. return *m_rootTracker;
  11741. }
  11742. void TrackerContext::endRun() {
  11743. m_rootTracker.reset();
  11744. m_currentTracker = nullptr;
  11745. m_runState = NotStarted;
  11746. }
  11747. void TrackerContext::startCycle() {
  11748. m_currentTracker = m_rootTracker.get();
  11749. m_runState = Executing;
  11750. }
  11751. void TrackerContext::completeCycle() {
  11752. m_runState = CompletedCycle;
  11753. }
  11754. bool TrackerContext::completedCycle() const {
  11755. return m_runState == CompletedCycle;
  11756. }
  11757. ITracker& TrackerContext::currentTracker() {
  11758. return *m_currentTracker;
  11759. }
  11760. void TrackerContext::setCurrentTracker( ITracker* tracker ) {
  11761. m_currentTracker = tracker;
  11762. }
  11763. TrackerBase::TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent ):
  11764. ITracker(nameAndLocation),
  11765. m_ctx( ctx ),
  11766. m_parent( parent )
  11767. {}
  11768. bool TrackerBase::isComplete() const {
  11769. return m_runState == CompletedSuccessfully || m_runState == Failed;
  11770. }
  11771. bool TrackerBase::isSuccessfullyCompleted() const {
  11772. return m_runState == CompletedSuccessfully;
  11773. }
  11774. bool TrackerBase::isOpen() const {
  11775. return m_runState != NotStarted && !isComplete();
  11776. }
  11777. bool TrackerBase::hasChildren() const {
  11778. return !m_children.empty();
  11779. }
  11780. void TrackerBase::addChild( ITrackerPtr const& child ) {
  11781. m_children.push_back( child );
  11782. }
  11783. ITrackerPtr TrackerBase::findChild( NameAndLocation const& nameAndLocation ) {
  11784. auto it = std::find_if( m_children.begin(), m_children.end(),
  11785. [&nameAndLocation]( ITrackerPtr const& tracker ){
  11786. return
  11787. tracker->nameAndLocation().location == nameAndLocation.location &&
  11788. tracker->nameAndLocation().name == nameAndLocation.name;
  11789. } );
  11790. return( it != m_children.end() )
  11791. ? *it
  11792. : nullptr;
  11793. }
  11794. ITracker& TrackerBase::parent() {
  11795. assert( m_parent ); // Should always be non-null except for root
  11796. return *m_parent;
  11797. }
  11798. void TrackerBase::openChild() {
  11799. if( m_runState != ExecutingChildren ) {
  11800. m_runState = ExecutingChildren;
  11801. if( m_parent )
  11802. m_parent->openChild();
  11803. }
  11804. }
  11805. bool TrackerBase::isSectionTracker() const { return false; }
  11806. bool TrackerBase::isGeneratorTracker() const { return false; }
  11807. void TrackerBase::open() {
  11808. m_runState = Executing;
  11809. moveToThis();
  11810. if( m_parent )
  11811. m_parent->openChild();
  11812. }
  11813. void TrackerBase::close() {
  11814. // Close any still open children (e.g. generators)
  11815. while( &m_ctx.currentTracker() != this )
  11816. m_ctx.currentTracker().close();
  11817. switch( m_runState ) {
  11818. case NeedsAnotherRun:
  11819. break;
  11820. case Executing:
  11821. m_runState = CompletedSuccessfully;
  11822. break;
  11823. case ExecutingChildren:
  11824. if( std::all_of(m_children.begin(), m_children.end(), [](ITrackerPtr const& t){ return t->isComplete(); }) )
  11825. m_runState = CompletedSuccessfully;
  11826. break;
  11827. case NotStarted:
  11828. case CompletedSuccessfully:
  11829. case Failed:
  11830. CATCH_INTERNAL_ERROR( "Illogical state: " << m_runState );
  11831. default:
  11832. CATCH_INTERNAL_ERROR( "Unknown state: " << m_runState );
  11833. }
  11834. moveToParent();
  11835. m_ctx.completeCycle();
  11836. }
  11837. void TrackerBase::fail() {
  11838. m_runState = Failed;
  11839. if( m_parent )
  11840. m_parent->markAsNeedingAnotherRun();
  11841. moveToParent();
  11842. m_ctx.completeCycle();
  11843. }
  11844. void TrackerBase::markAsNeedingAnotherRun() {
  11845. m_runState = NeedsAnotherRun;
  11846. }
  11847. void TrackerBase::moveToParent() {
  11848. assert( m_parent );
  11849. m_ctx.setCurrentTracker( m_parent );
  11850. }
  11851. void TrackerBase::moveToThis() {
  11852. m_ctx.setCurrentTracker( this );
  11853. }
  11854. SectionTracker::SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  11855. : TrackerBase( nameAndLocation, ctx, parent ),
  11856. m_trimmed_name(trim(nameAndLocation.name))
  11857. {
  11858. if( parent ) {
  11859. while( !parent->isSectionTracker() )
  11860. parent = &parent->parent();
  11861. SectionTracker& parentSection = static_cast<SectionTracker&>( *parent );
  11862. addNextFilters( parentSection.m_filters );
  11863. }
  11864. }
  11865. bool SectionTracker::isComplete() const {
  11866. bool complete = true;
  11867. if (m_filters.empty()
  11868. || m_filters[0] == ""
  11869. || std::find(m_filters.begin(), m_filters.end(), m_trimmed_name) != m_filters.end()) {
  11870. complete = TrackerBase::isComplete();
  11871. }
  11872. return complete;
  11873. }
  11874. bool SectionTracker::isSectionTracker() const { return true; }
  11875. SectionTracker& SectionTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ) {
  11876. std::shared_ptr<SectionTracker> section;
  11877. ITracker& currentTracker = ctx.currentTracker();
  11878. if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  11879. assert( childTracker );
  11880. assert( childTracker->isSectionTracker() );
  11881. section = std::static_pointer_cast<SectionTracker>( childTracker );
  11882. }
  11883. else {
  11884. section = std::make_shared<SectionTracker>( nameAndLocation, ctx, &currentTracker );
  11885. currentTracker.addChild( section );
  11886. }
  11887. if( !ctx.completedCycle() )
  11888. section->tryOpen();
  11889. return *section;
  11890. }
  11891. void SectionTracker::tryOpen() {
  11892. if( !isComplete() )
  11893. open();
  11894. }
  11895. void SectionTracker::addInitialFilters( std::vector<std::string> const& filters ) {
  11896. if( !filters.empty() ) {
  11897. m_filters.reserve( m_filters.size() + filters.size() + 2 );
  11898. m_filters.emplace_back(""); // Root - should never be consulted
  11899. m_filters.emplace_back(""); // Test Case - not a section filter
  11900. m_filters.insert( m_filters.end(), filters.begin(), filters.end() );
  11901. }
  11902. }
  11903. void SectionTracker::addNextFilters( std::vector<std::string> const& filters ) {
  11904. if( filters.size() > 1 )
  11905. m_filters.insert( m_filters.end(), filters.begin()+1, filters.end() );
  11906. }
  11907. std::vector<std::string> const& SectionTracker::getFilters() const {
  11908. return m_filters;
  11909. }
  11910. std::string const& SectionTracker::trimmedName() const {
  11911. return m_trimmed_name;
  11912. }
  11913. } // namespace TestCaseTracking
  11914. using TestCaseTracking::ITracker;
  11915. using TestCaseTracking::TrackerContext;
  11916. using TestCaseTracking::SectionTracker;
  11917. } // namespace Catch
  11918. #if defined(__clang__)
  11919. # pragma clang diagnostic pop
  11920. #endif
  11921. // end catch_test_case_tracker.cpp
  11922. // start catch_test_registry.cpp
  11923. namespace Catch {
  11924. auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker* {
  11925. return new(std::nothrow) TestInvokerAsFunction( testAsFunction );
  11926. }
  11927. NameAndTags::NameAndTags( StringRef const& name_ , StringRef const& tags_ ) noexcept : name( name_ ), tags( tags_ ) {}
  11928. AutoReg::AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept {
  11929. CATCH_TRY {
  11930. getMutableRegistryHub()
  11931. .registerTest(
  11932. makeTestCase(
  11933. invoker,
  11934. extractClassName( classOrMethod ),
  11935. nameAndTags,
  11936. lineInfo));
  11937. } CATCH_CATCH_ALL {
  11938. // Do not throw when constructing global objects, instead register the exception to be processed later
  11939. getMutableRegistryHub().registerStartupException();
  11940. }
  11941. }
  11942. AutoReg::~AutoReg() = default;
  11943. }
  11944. // end catch_test_registry.cpp
  11945. // start catch_test_spec.cpp
  11946. #include <algorithm>
  11947. #include <string>
  11948. #include <vector>
  11949. #include <memory>
  11950. namespace Catch {
  11951. TestSpec::Pattern::Pattern( std::string const& name )
  11952. : m_name( name )
  11953. {}
  11954. TestSpec::Pattern::~Pattern() = default;
  11955. std::string const& TestSpec::Pattern::name() const {
  11956. return m_name;
  11957. }
  11958. TestSpec::NamePattern::NamePattern( std::string const& name, std::string const& filterString )
  11959. : Pattern( filterString )
  11960. , m_wildcardPattern( toLower( name ), CaseSensitive::No )
  11961. {}
  11962. bool TestSpec::NamePattern::matches( TestCaseInfo const& testCase ) const {
  11963. return m_wildcardPattern.matches( testCase.name );
  11964. }
  11965. TestSpec::TagPattern::TagPattern( std::string const& tag, std::string const& filterString )
  11966. : Pattern( filterString )
  11967. , m_tag( toLower( tag ) )
  11968. {}
  11969. bool TestSpec::TagPattern::matches( TestCaseInfo const& testCase ) const {
  11970. return std::find(begin(testCase.lcaseTags),
  11971. end(testCase.lcaseTags),
  11972. m_tag) != end(testCase.lcaseTags);
  11973. }
  11974. TestSpec::ExcludedPattern::ExcludedPattern( PatternPtr const& underlyingPattern )
  11975. : Pattern( underlyingPattern->name() )
  11976. , m_underlyingPattern( underlyingPattern )
  11977. {}
  11978. bool TestSpec::ExcludedPattern::matches( TestCaseInfo const& testCase ) const {
  11979. return !m_underlyingPattern->matches( testCase );
  11980. }
  11981. bool TestSpec::Filter::matches( TestCaseInfo const& testCase ) const {
  11982. return std::all_of( m_patterns.begin(), m_patterns.end(), [&]( PatternPtr const& p ){ return p->matches( testCase ); } );
  11983. }
  11984. std::string TestSpec::Filter::name() const {
  11985. std::string name;
  11986. for( auto const& p : m_patterns )
  11987. name += p->name();
  11988. return name;
  11989. }
  11990. bool TestSpec::hasFilters() const {
  11991. return !m_filters.empty();
  11992. }
  11993. bool TestSpec::matches( TestCaseInfo const& testCase ) const {
  11994. return std::any_of( m_filters.begin(), m_filters.end(), [&]( Filter const& f ){ return f.matches( testCase ); } );
  11995. }
  11996. TestSpec::Matches TestSpec::matchesByFilter( std::vector<TestCase> const& testCases, IConfig const& config ) const
  11997. {
  11998. Matches matches( m_filters.size() );
  11999. std::transform( m_filters.begin(), m_filters.end(), matches.begin(), [&]( Filter const& filter ){
  12000. std::vector<TestCase const*> currentMatches;
  12001. for( auto const& test : testCases )
  12002. if( isThrowSafe( test, config ) && filter.matches( test ) )
  12003. currentMatches.emplace_back( &test );
  12004. return FilterMatch{ filter.name(), currentMatches };
  12005. } );
  12006. return matches;
  12007. }
  12008. const TestSpec::vectorStrings& TestSpec::getInvalidArgs() const{
  12009. return (m_invalidArgs);
  12010. }
  12011. }
  12012. // end catch_test_spec.cpp
  12013. // start catch_test_spec_parser.cpp
  12014. namespace Catch {
  12015. TestSpecParser::TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {}
  12016. TestSpecParser& TestSpecParser::parse( std::string const& arg ) {
  12017. m_mode = None;
  12018. m_exclusion = false;
  12019. m_arg = m_tagAliases->expandAliases( arg );
  12020. m_escapeChars.clear();
  12021. m_substring.reserve(m_arg.size());
  12022. m_patternName.reserve(m_arg.size());
  12023. m_realPatternPos = 0;
  12024. for( m_pos = 0; m_pos < m_arg.size(); ++m_pos )
  12025. //if visitChar fails
  12026. if( !visitChar( m_arg[m_pos] ) ){
  12027. m_testSpec.m_invalidArgs.push_back(arg);
  12028. break;
  12029. }
  12030. endMode();
  12031. return *this;
  12032. }
  12033. TestSpec TestSpecParser::testSpec() {
  12034. addFilter();
  12035. return m_testSpec;
  12036. }
  12037. bool TestSpecParser::visitChar( char c ) {
  12038. if( (m_mode != EscapedName) && (c == '\\') ) {
  12039. escape();
  12040. addCharToPattern(c);
  12041. return true;
  12042. }else if((m_mode != EscapedName) && (c == ',') ) {
  12043. return separate();
  12044. }
  12045. switch( m_mode ) {
  12046. case None:
  12047. if( processNoneChar( c ) )
  12048. return true;
  12049. break;
  12050. case Name:
  12051. processNameChar( c );
  12052. break;
  12053. case EscapedName:
  12054. endMode();
  12055. addCharToPattern(c);
  12056. return true;
  12057. default:
  12058. case Tag:
  12059. case QuotedName:
  12060. if( processOtherChar( c ) )
  12061. return true;
  12062. break;
  12063. }
  12064. m_substring += c;
  12065. if( !isControlChar( c ) ) {
  12066. m_patternName += c;
  12067. m_realPatternPos++;
  12068. }
  12069. return true;
  12070. }
  12071. // Two of the processing methods return true to signal the caller to return
  12072. // without adding the given character to the current pattern strings
  12073. bool TestSpecParser::processNoneChar( char c ) {
  12074. switch( c ) {
  12075. case ' ':
  12076. return true;
  12077. case '~':
  12078. m_exclusion = true;
  12079. return false;
  12080. case '[':
  12081. startNewMode( Tag );
  12082. return false;
  12083. case '"':
  12084. startNewMode( QuotedName );
  12085. return false;
  12086. default:
  12087. startNewMode( Name );
  12088. return false;
  12089. }
  12090. }
  12091. void TestSpecParser::processNameChar( char c ) {
  12092. if( c == '[' ) {
  12093. if( m_substring == "exclude:" )
  12094. m_exclusion = true;
  12095. else
  12096. endMode();
  12097. startNewMode( Tag );
  12098. }
  12099. }
  12100. bool TestSpecParser::processOtherChar( char c ) {
  12101. if( !isControlChar( c ) )
  12102. return false;
  12103. m_substring += c;
  12104. endMode();
  12105. return true;
  12106. }
  12107. void TestSpecParser::startNewMode( Mode mode ) {
  12108. m_mode = mode;
  12109. }
  12110. void TestSpecParser::endMode() {
  12111. switch( m_mode ) {
  12112. case Name:
  12113. case QuotedName:
  12114. return addNamePattern();
  12115. case Tag:
  12116. return addTagPattern();
  12117. case EscapedName:
  12118. revertBackToLastMode();
  12119. return;
  12120. case None:
  12121. default:
  12122. return startNewMode( None );
  12123. }
  12124. }
  12125. void TestSpecParser::escape() {
  12126. saveLastMode();
  12127. m_mode = EscapedName;
  12128. m_escapeChars.push_back(m_realPatternPos);
  12129. }
  12130. bool TestSpecParser::isControlChar( char c ) const {
  12131. switch( m_mode ) {
  12132. default:
  12133. return false;
  12134. case None:
  12135. return c == '~';
  12136. case Name:
  12137. return c == '[';
  12138. case EscapedName:
  12139. return true;
  12140. case QuotedName:
  12141. return c == '"';
  12142. case Tag:
  12143. return c == '[' || c == ']';
  12144. }
  12145. }
  12146. void TestSpecParser::addFilter() {
  12147. if( !m_currentFilter.m_patterns.empty() ) {
  12148. m_testSpec.m_filters.push_back( m_currentFilter );
  12149. m_currentFilter = TestSpec::Filter();
  12150. }
  12151. }
  12152. void TestSpecParser::saveLastMode() {
  12153. lastMode = m_mode;
  12154. }
  12155. void TestSpecParser::revertBackToLastMode() {
  12156. m_mode = lastMode;
  12157. }
  12158. bool TestSpecParser::separate() {
  12159. if( (m_mode==QuotedName) || (m_mode==Tag) ){
  12160. //invalid argument, signal failure to previous scope.
  12161. m_mode = None;
  12162. m_pos = m_arg.size();
  12163. m_substring.clear();
  12164. m_patternName.clear();
  12165. m_realPatternPos = 0;
  12166. return false;
  12167. }
  12168. endMode();
  12169. addFilter();
  12170. return true; //success
  12171. }
  12172. std::string TestSpecParser::preprocessPattern() {
  12173. std::string token = m_patternName;
  12174. for (std::size_t i = 0; i < m_escapeChars.size(); ++i)
  12175. token = token.substr(0, m_escapeChars[i] - i) + token.substr(m_escapeChars[i] - i + 1);
  12176. m_escapeChars.clear();
  12177. if (startsWith(token, "exclude:")) {
  12178. m_exclusion = true;
  12179. token = token.substr(8);
  12180. }
  12181. m_patternName.clear();
  12182. m_realPatternPos = 0;
  12183. return token;
  12184. }
  12185. void TestSpecParser::addNamePattern() {
  12186. auto token = preprocessPattern();
  12187. if (!token.empty()) {
  12188. TestSpec::PatternPtr pattern = std::make_shared<TestSpec::NamePattern>(token, m_substring);
  12189. if (m_exclusion)
  12190. pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
  12191. m_currentFilter.m_patterns.push_back(pattern);
  12192. }
  12193. m_substring.clear();
  12194. m_exclusion = false;
  12195. m_mode = None;
  12196. }
  12197. void TestSpecParser::addTagPattern() {
  12198. auto token = preprocessPattern();
  12199. if (!token.empty()) {
  12200. // If the tag pattern is the "hide and tag" shorthand (e.g. [.foo])
  12201. // we have to create a separate hide tag and shorten the real one
  12202. if (token.size() > 1 && token[0] == '.') {
  12203. token.erase(token.begin());
  12204. TestSpec::PatternPtr pattern = std::make_shared<TestSpec::TagPattern>(".", m_substring);
  12205. if (m_exclusion) {
  12206. pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
  12207. }
  12208. m_currentFilter.m_patterns.push_back(pattern);
  12209. }
  12210. TestSpec::PatternPtr pattern = std::make_shared<TestSpec::TagPattern>(token, m_substring);
  12211. if (m_exclusion) {
  12212. pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
  12213. }
  12214. m_currentFilter.m_patterns.push_back(pattern);
  12215. }
  12216. m_substring.clear();
  12217. m_exclusion = false;
  12218. m_mode = None;
  12219. }
  12220. TestSpec parseTestSpec( std::string const& arg ) {
  12221. return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec();
  12222. }
  12223. } // namespace Catch
  12224. // end catch_test_spec_parser.cpp
  12225. // start catch_timer.cpp
  12226. #include <chrono>
  12227. static const uint64_t nanosecondsInSecond = 1000000000;
  12228. namespace Catch {
  12229. auto getCurrentNanosecondsSinceEpoch() -> uint64_t {
  12230. return std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::high_resolution_clock::now().time_since_epoch() ).count();
  12231. }
  12232. namespace {
  12233. auto estimateClockResolution() -> uint64_t {
  12234. uint64_t sum = 0;
  12235. static const uint64_t iterations = 1000000;
  12236. auto startTime = getCurrentNanosecondsSinceEpoch();
  12237. for( std::size_t i = 0; i < iterations; ++i ) {
  12238. uint64_t ticks;
  12239. uint64_t baseTicks = getCurrentNanosecondsSinceEpoch();
  12240. do {
  12241. ticks = getCurrentNanosecondsSinceEpoch();
  12242. } while( ticks == baseTicks );
  12243. auto delta = ticks - baseTicks;
  12244. sum += delta;
  12245. // If we have been calibrating for over 3 seconds -- the clock
  12246. // is terrible and we should move on.
  12247. // TBD: How to signal that the measured resolution is probably wrong?
  12248. if (ticks > startTime + 3 * nanosecondsInSecond) {
  12249. return sum / ( i + 1u );
  12250. }
  12251. }
  12252. // We're just taking the mean, here. To do better we could take the std. dev and exclude outliers
  12253. // - and potentially do more iterations if there's a high variance.
  12254. return sum/iterations;
  12255. }
  12256. }
  12257. auto getEstimatedClockResolution() -> uint64_t {
  12258. static auto s_resolution = estimateClockResolution();
  12259. return s_resolution;
  12260. }
  12261. void Timer::start() {
  12262. m_nanoseconds = getCurrentNanosecondsSinceEpoch();
  12263. }
  12264. auto Timer::getElapsedNanoseconds() const -> uint64_t {
  12265. return getCurrentNanosecondsSinceEpoch() - m_nanoseconds;
  12266. }
  12267. auto Timer::getElapsedMicroseconds() const -> uint64_t {
  12268. return getElapsedNanoseconds()/1000;
  12269. }
  12270. auto Timer::getElapsedMilliseconds() const -> unsigned int {
  12271. return static_cast<unsigned int>(getElapsedMicroseconds()/1000);
  12272. }
  12273. auto Timer::getElapsedSeconds() const -> double {
  12274. return getElapsedMicroseconds()/1000000.0;
  12275. }
  12276. } // namespace Catch
  12277. // end catch_timer.cpp
  12278. // start catch_tostring.cpp
  12279. #if defined(__clang__)
  12280. # pragma clang diagnostic push
  12281. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  12282. # pragma clang diagnostic ignored "-Wglobal-constructors"
  12283. #endif
  12284. // Enable specific decls locally
  12285. #if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  12286. #define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  12287. #endif
  12288. #include <cmath>
  12289. #include <iomanip>
  12290. namespace Catch {
  12291. namespace Detail {
  12292. const std::string unprintableString = "{?}";
  12293. namespace {
  12294. const int hexThreshold = 255;
  12295. struct Endianness {
  12296. enum Arch { Big, Little };
  12297. static Arch which() {
  12298. int one = 1;
  12299. // If the lowest byte we read is non-zero, we can assume
  12300. // that little endian format is used.
  12301. auto value = *reinterpret_cast<char*>(&one);
  12302. return value ? Little : Big;
  12303. }
  12304. };
  12305. }
  12306. std::string rawMemoryToString( const void *object, std::size_t size ) {
  12307. // Reverse order for little endian architectures
  12308. int i = 0, end = static_cast<int>( size ), inc = 1;
  12309. if( Endianness::which() == Endianness::Little ) {
  12310. i = end-1;
  12311. end = inc = -1;
  12312. }
  12313. unsigned char const *bytes = static_cast<unsigned char const *>(object);
  12314. ReusableStringStream rss;
  12315. rss << "0x" << std::setfill('0') << std::hex;
  12316. for( ; i != end; i += inc )
  12317. rss << std::setw(2) << static_cast<unsigned>(bytes[i]);
  12318. return rss.str();
  12319. }
  12320. }
  12321. template<typename T>
  12322. std::string fpToString( T value, int precision ) {
  12323. if (Catch::isnan(value)) {
  12324. return "nan";
  12325. }
  12326. ReusableStringStream rss;
  12327. rss << std::setprecision( precision )
  12328. << std::fixed
  12329. << value;
  12330. std::string d = rss.str();
  12331. std::size_t i = d.find_last_not_of( '0' );
  12332. if( i != std::string::npos && i != d.size()-1 ) {
  12333. if( d[i] == '.' )
  12334. i++;
  12335. d = d.substr( 0, i+1 );
  12336. }
  12337. return d;
  12338. }
  12339. //// ======================================================= ////
  12340. //
  12341. // Out-of-line defs for full specialization of StringMaker
  12342. //
  12343. //// ======================================================= ////
  12344. std::string StringMaker<std::string>::convert(const std::string& str) {
  12345. if (!getCurrentContext().getConfig()->showInvisibles()) {
  12346. return '"' + str + '"';
  12347. }
  12348. std::string s("\"");
  12349. for (char c : str) {
  12350. switch (c) {
  12351. case '\n':
  12352. s.append("\\n");
  12353. break;
  12354. case '\t':
  12355. s.append("\\t");
  12356. break;
  12357. default:
  12358. s.push_back(c);
  12359. break;
  12360. }
  12361. }
  12362. s.append("\"");
  12363. return s;
  12364. }
  12365. #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  12366. std::string StringMaker<std::string_view>::convert(std::string_view str) {
  12367. return ::Catch::Detail::stringify(std::string{ str });
  12368. }
  12369. #endif
  12370. std::string StringMaker<char const*>::convert(char const* str) {
  12371. if (str) {
  12372. return ::Catch::Detail::stringify(std::string{ str });
  12373. } else {
  12374. return{ "{null string}" };
  12375. }
  12376. }
  12377. std::string StringMaker<char*>::convert(char* str) {
  12378. if (str) {
  12379. return ::Catch::Detail::stringify(std::string{ str });
  12380. } else {
  12381. return{ "{null string}" };
  12382. }
  12383. }
  12384. #ifdef CATCH_CONFIG_WCHAR
  12385. std::string StringMaker<std::wstring>::convert(const std::wstring& wstr) {
  12386. std::string s;
  12387. s.reserve(wstr.size());
  12388. for (auto c : wstr) {
  12389. s += (c <= 0xff) ? static_cast<char>(c) : '?';
  12390. }
  12391. return ::Catch::Detail::stringify(s);
  12392. }
  12393. # ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  12394. std::string StringMaker<std::wstring_view>::convert(std::wstring_view str) {
  12395. return StringMaker<std::wstring>::convert(std::wstring(str));
  12396. }
  12397. # endif
  12398. std::string StringMaker<wchar_t const*>::convert(wchar_t const * str) {
  12399. if (str) {
  12400. return ::Catch::Detail::stringify(std::wstring{ str });
  12401. } else {
  12402. return{ "{null string}" };
  12403. }
  12404. }
  12405. std::string StringMaker<wchar_t *>::convert(wchar_t * str) {
  12406. if (str) {
  12407. return ::Catch::Detail::stringify(std::wstring{ str });
  12408. } else {
  12409. return{ "{null string}" };
  12410. }
  12411. }
  12412. #endif
  12413. #if defined(CATCH_CONFIG_CPP17_BYTE)
  12414. #include <cstddef>
  12415. std::string StringMaker<std::byte>::convert(std::byte value) {
  12416. return ::Catch::Detail::stringify(std::to_integer<unsigned long long>(value));
  12417. }
  12418. #endif // defined(CATCH_CONFIG_CPP17_BYTE)
  12419. std::string StringMaker<int>::convert(int value) {
  12420. return ::Catch::Detail::stringify(static_cast<long long>(value));
  12421. }
  12422. std::string StringMaker<long>::convert(long value) {
  12423. return ::Catch::Detail::stringify(static_cast<long long>(value));
  12424. }
  12425. std::string StringMaker<long long>::convert(long long value) {
  12426. ReusableStringStream rss;
  12427. rss << value;
  12428. if (value > Detail::hexThreshold) {
  12429. rss << " (0x" << std::hex << value << ')';
  12430. }
  12431. return rss.str();
  12432. }
  12433. std::string StringMaker<unsigned int>::convert(unsigned int value) {
  12434. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  12435. }
  12436. std::string StringMaker<unsigned long>::convert(unsigned long value) {
  12437. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  12438. }
  12439. std::string StringMaker<unsigned long long>::convert(unsigned long long value) {
  12440. ReusableStringStream rss;
  12441. rss << value;
  12442. if (value > Detail::hexThreshold) {
  12443. rss << " (0x" << std::hex << value << ')';
  12444. }
  12445. return rss.str();
  12446. }
  12447. std::string StringMaker<bool>::convert(bool b) {
  12448. return b ? "true" : "false";
  12449. }
  12450. std::string StringMaker<signed char>::convert(signed char value) {
  12451. if (value == '\r') {
  12452. return "'\\r'";
  12453. } else if (value == '\f') {
  12454. return "'\\f'";
  12455. } else if (value == '\n') {
  12456. return "'\\n'";
  12457. } else if (value == '\t') {
  12458. return "'\\t'";
  12459. } else if ('\0' <= value && value < ' ') {
  12460. return ::Catch::Detail::stringify(static_cast<unsigned int>(value));
  12461. } else {
  12462. char chstr[] = "' '";
  12463. chstr[1] = value;
  12464. return chstr;
  12465. }
  12466. }
  12467. std::string StringMaker<char>::convert(char c) {
  12468. return ::Catch::Detail::stringify(static_cast<signed char>(c));
  12469. }
  12470. std::string StringMaker<unsigned char>::convert(unsigned char c) {
  12471. return ::Catch::Detail::stringify(static_cast<char>(c));
  12472. }
  12473. std::string StringMaker<std::nullptr_t>::convert(std::nullptr_t) {
  12474. return "nullptr";
  12475. }
  12476. int StringMaker<float>::precision = 5;
  12477. std::string StringMaker<float>::convert(float value) {
  12478. return fpToString(value, precision) + 'f';
  12479. }
  12480. int StringMaker<double>::precision = 10;
  12481. std::string StringMaker<double>::convert(double value) {
  12482. return fpToString(value, precision);
  12483. }
  12484. std::string ratio_string<std::atto>::symbol() { return "a"; }
  12485. std::string ratio_string<std::femto>::symbol() { return "f"; }
  12486. std::string ratio_string<std::pico>::symbol() { return "p"; }
  12487. std::string ratio_string<std::nano>::symbol() { return "n"; }
  12488. std::string ratio_string<std::micro>::symbol() { return "u"; }
  12489. std::string ratio_string<std::milli>::symbol() { return "m"; }
  12490. } // end namespace Catch
  12491. #if defined(__clang__)
  12492. # pragma clang diagnostic pop
  12493. #endif
  12494. // end catch_tostring.cpp
  12495. // start catch_totals.cpp
  12496. namespace Catch {
  12497. Counts Counts::operator - ( Counts const& other ) const {
  12498. Counts diff;
  12499. diff.passed = passed - other.passed;
  12500. diff.failed = failed - other.failed;
  12501. diff.failedButOk = failedButOk - other.failedButOk;
  12502. return diff;
  12503. }
  12504. Counts& Counts::operator += ( Counts const& other ) {
  12505. passed += other.passed;
  12506. failed += other.failed;
  12507. failedButOk += other.failedButOk;
  12508. return *this;
  12509. }
  12510. std::size_t Counts::total() const {
  12511. return passed + failed + failedButOk;
  12512. }
  12513. bool Counts::allPassed() const {
  12514. return failed == 0 && failedButOk == 0;
  12515. }
  12516. bool Counts::allOk() const {
  12517. return failed == 0;
  12518. }
  12519. Totals Totals::operator - ( Totals const& other ) const {
  12520. Totals diff;
  12521. diff.assertions = assertions - other.assertions;
  12522. diff.testCases = testCases - other.testCases;
  12523. return diff;
  12524. }
  12525. Totals& Totals::operator += ( Totals const& other ) {
  12526. assertions += other.assertions;
  12527. testCases += other.testCases;
  12528. return *this;
  12529. }
  12530. Totals Totals::delta( Totals const& prevTotals ) const {
  12531. Totals diff = *this - prevTotals;
  12532. if( diff.assertions.failed > 0 )
  12533. ++diff.testCases.failed;
  12534. else if( diff.assertions.failedButOk > 0 )
  12535. ++diff.testCases.failedButOk;
  12536. else
  12537. ++diff.testCases.passed;
  12538. return diff;
  12539. }
  12540. }
  12541. // end catch_totals.cpp
  12542. // start catch_uncaught_exceptions.cpp
  12543. // start catch_config_uncaught_exceptions.hpp
  12544. // Copyright Catch2 Authors
  12545. // Distributed under the Boost Software License, Version 1.0.
  12546. // (See accompanying file LICENSE_1_0.txt or copy at
  12547. // https://www.boost.org/LICENSE_1_0.txt)
  12548. // SPDX-License-Identifier: BSL-1.0
  12549. #ifndef CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP
  12550. #define CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP
  12551. #if defined(_MSC_VER)
  12552. # if _MSC_VER >= 1900 // Visual Studio 2015 or newer
  12553. # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
  12554. # endif
  12555. #endif
  12556. #include <exception>
  12557. #if defined(__cpp_lib_uncaught_exceptions) \
  12558. && !defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
  12559. # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
  12560. #endif // __cpp_lib_uncaught_exceptions
  12561. #if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) \
  12562. && !defined(CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) \
  12563. && !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
  12564. # define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
  12565. #endif
  12566. #endif // CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP
  12567. // end catch_config_uncaught_exceptions.hpp
  12568. #include <exception>
  12569. namespace Catch {
  12570. bool uncaught_exceptions() {
  12571. #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  12572. return false;
  12573. #elif defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
  12574. return std::uncaught_exceptions() > 0;
  12575. #else
  12576. return std::uncaught_exception();
  12577. #endif
  12578. }
  12579. } // end namespace Catch
  12580. // end catch_uncaught_exceptions.cpp
  12581. // start catch_version.cpp
  12582. #include <ostream>
  12583. namespace Catch {
  12584. Version::Version
  12585. ( unsigned int _majorVersion,
  12586. unsigned int _minorVersion,
  12587. unsigned int _patchNumber,
  12588. char const * const _branchName,
  12589. unsigned int _buildNumber )
  12590. : majorVersion( _majorVersion ),
  12591. minorVersion( _minorVersion ),
  12592. patchNumber( _patchNumber ),
  12593. branchName( _branchName ),
  12594. buildNumber( _buildNumber )
  12595. {}
  12596. std::ostream& operator << ( std::ostream& os, Version const& version ) {
  12597. os << version.majorVersion << '.'
  12598. << version.minorVersion << '.'
  12599. << version.patchNumber;
  12600. // branchName is never null -> 0th char is \0 if it is empty
  12601. if (version.branchName[0]) {
  12602. os << '-' << version.branchName
  12603. << '.' << version.buildNumber;
  12604. }
  12605. return os;
  12606. }
  12607. Version const& libraryVersion() {
  12608. static Version version( 2, 13, 9, "", 0 );
  12609. return version;
  12610. }
  12611. }
  12612. // end catch_version.cpp
  12613. // start catch_wildcard_pattern.cpp
  12614. namespace Catch {
  12615. WildcardPattern::WildcardPattern( std::string const& pattern,
  12616. CaseSensitive::Choice caseSensitivity )
  12617. : m_caseSensitivity( caseSensitivity ),
  12618. m_pattern( normaliseString( pattern ) )
  12619. {
  12620. if( startsWith( m_pattern, '*' ) ) {
  12621. m_pattern = m_pattern.substr( 1 );
  12622. m_wildcard = WildcardAtStart;
  12623. }
  12624. if( endsWith( m_pattern, '*' ) ) {
  12625. m_pattern = m_pattern.substr( 0, m_pattern.size()-1 );
  12626. m_wildcard = static_cast<WildcardPosition>( m_wildcard | WildcardAtEnd );
  12627. }
  12628. }
  12629. bool WildcardPattern::matches( std::string const& str ) const {
  12630. switch( m_wildcard ) {
  12631. case NoWildcard:
  12632. return m_pattern == normaliseString( str );
  12633. case WildcardAtStart:
  12634. return endsWith( normaliseString( str ), m_pattern );
  12635. case WildcardAtEnd:
  12636. return startsWith( normaliseString( str ), m_pattern );
  12637. case WildcardAtBothEnds:
  12638. return contains( normaliseString( str ), m_pattern );
  12639. default:
  12640. CATCH_INTERNAL_ERROR( "Unknown enum" );
  12641. }
  12642. }
  12643. std::string WildcardPattern::normaliseString( std::string const& str ) const {
  12644. return trim( m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str );
  12645. }
  12646. }
  12647. // end catch_wildcard_pattern.cpp
  12648. // start catch_xmlwriter.cpp
  12649. #include <iomanip>
  12650. #include <type_traits>
  12651. namespace Catch {
  12652. namespace {
  12653. size_t trailingBytes(unsigned char c) {
  12654. if ((c & 0xE0) == 0xC0) {
  12655. return 2;
  12656. }
  12657. if ((c & 0xF0) == 0xE0) {
  12658. return 3;
  12659. }
  12660. if ((c & 0xF8) == 0xF0) {
  12661. return 4;
  12662. }
  12663. CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
  12664. }
  12665. uint32_t headerValue(unsigned char c) {
  12666. if ((c & 0xE0) == 0xC0) {
  12667. return c & 0x1F;
  12668. }
  12669. if ((c & 0xF0) == 0xE0) {
  12670. return c & 0x0F;
  12671. }
  12672. if ((c & 0xF8) == 0xF0) {
  12673. return c & 0x07;
  12674. }
  12675. CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
  12676. }
  12677. void hexEscapeChar(std::ostream& os, unsigned char c) {
  12678. std::ios_base::fmtflags f(os.flags());
  12679. os << "\\x"
  12680. << std::uppercase << std::hex << std::setfill('0') << std::setw(2)
  12681. << static_cast<int>(c);
  12682. os.flags(f);
  12683. }
  12684. bool shouldNewline(XmlFormatting fmt) {
  12685. return !!(static_cast<std::underlying_type<XmlFormatting>::type>(fmt & XmlFormatting::Newline));
  12686. }
  12687. bool shouldIndent(XmlFormatting fmt) {
  12688. return !!(static_cast<std::underlying_type<XmlFormatting>::type>(fmt & XmlFormatting::Indent));
  12689. }
  12690. } // anonymous namespace
  12691. XmlFormatting operator | (XmlFormatting lhs, XmlFormatting rhs) {
  12692. return static_cast<XmlFormatting>(
  12693. static_cast<std::underlying_type<XmlFormatting>::type>(lhs) |
  12694. static_cast<std::underlying_type<XmlFormatting>::type>(rhs)
  12695. );
  12696. }
  12697. XmlFormatting operator & (XmlFormatting lhs, XmlFormatting rhs) {
  12698. return static_cast<XmlFormatting>(
  12699. static_cast<std::underlying_type<XmlFormatting>::type>(lhs) &
  12700. static_cast<std::underlying_type<XmlFormatting>::type>(rhs)
  12701. );
  12702. }
  12703. XmlEncode::XmlEncode( std::string const& str, ForWhat forWhat )
  12704. : m_str( str ),
  12705. m_forWhat( forWhat )
  12706. {}
  12707. void XmlEncode::encodeTo( std::ostream& os ) const {
  12708. // Apostrophe escaping not necessary if we always use " to write attributes
  12709. // (see: http://www.w3.org/TR/xml/#syntax)
  12710. for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) {
  12711. unsigned char c = m_str[idx];
  12712. switch (c) {
  12713. case '<': os << "&lt;"; break;
  12714. case '&': os << "&amp;"; break;
  12715. case '>':
  12716. // See: http://www.w3.org/TR/xml/#syntax
  12717. if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']')
  12718. os << "&gt;";
  12719. else
  12720. os << c;
  12721. break;
  12722. case '\"':
  12723. if (m_forWhat == ForAttributes)
  12724. os << "&quot;";
  12725. else
  12726. os << c;
  12727. break;
  12728. default:
  12729. // Check for control characters and invalid utf-8
  12730. // Escape control characters in standard ascii
  12731. // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0
  12732. if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) {
  12733. hexEscapeChar(os, c);
  12734. break;
  12735. }
  12736. // Plain ASCII: Write it to stream
  12737. if (c < 0x7F) {
  12738. os << c;
  12739. break;
  12740. }
  12741. // UTF-8 territory
  12742. // Check if the encoding is valid and if it is not, hex escape bytes.
  12743. // Important: We do not check the exact decoded values for validity, only the encoding format
  12744. // First check that this bytes is a valid lead byte:
  12745. // This means that it is not encoded as 1111 1XXX
  12746. // Or as 10XX XXXX
  12747. if (c < 0xC0 ||
  12748. c >= 0xF8) {
  12749. hexEscapeChar(os, c);
  12750. break;
  12751. }
  12752. auto encBytes = trailingBytes(c);
  12753. // Are there enough bytes left to avoid accessing out-of-bounds memory?
  12754. if (idx + encBytes - 1 >= m_str.size()) {
  12755. hexEscapeChar(os, c);
  12756. break;
  12757. }
  12758. // The header is valid, check data
  12759. // The next encBytes bytes must together be a valid utf-8
  12760. // This means: bitpattern 10XX XXXX and the extracted value is sane (ish)
  12761. bool valid = true;
  12762. uint32_t value = headerValue(c);
  12763. for (std::size_t n = 1; n < encBytes; ++n) {
  12764. unsigned char nc = m_str[idx + n];
  12765. valid &= ((nc & 0xC0) == 0x80);
  12766. value = (value << 6) | (nc & 0x3F);
  12767. }
  12768. if (
  12769. // Wrong bit pattern of following bytes
  12770. (!valid) ||
  12771. // Overlong encodings
  12772. (value < 0x80) ||
  12773. (0x80 <= value && value < 0x800 && encBytes > 2) ||
  12774. (0x800 < value && value < 0x10000 && encBytes > 3) ||
  12775. // Encoded value out of range
  12776. (value >= 0x110000)
  12777. ) {
  12778. hexEscapeChar(os, c);
  12779. break;
  12780. }
  12781. // If we got here, this is in fact a valid(ish) utf-8 sequence
  12782. for (std::size_t n = 0; n < encBytes; ++n) {
  12783. os << m_str[idx + n];
  12784. }
  12785. idx += encBytes - 1;
  12786. break;
  12787. }
  12788. }
  12789. }
  12790. std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) {
  12791. xmlEncode.encodeTo( os );
  12792. return os;
  12793. }
  12794. XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer, XmlFormatting fmt )
  12795. : m_writer( writer ),
  12796. m_fmt(fmt)
  12797. {}
  12798. XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept
  12799. : m_writer( other.m_writer ),
  12800. m_fmt(other.m_fmt)
  12801. {
  12802. other.m_writer = nullptr;
  12803. other.m_fmt = XmlFormatting::None;
  12804. }
  12805. XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) noexcept {
  12806. if ( m_writer ) {
  12807. m_writer->endElement();
  12808. }
  12809. m_writer = other.m_writer;
  12810. other.m_writer = nullptr;
  12811. m_fmt = other.m_fmt;
  12812. other.m_fmt = XmlFormatting::None;
  12813. return *this;
  12814. }
  12815. XmlWriter::ScopedElement::~ScopedElement() {
  12816. if (m_writer) {
  12817. m_writer->endElement(m_fmt);
  12818. }
  12819. }
  12820. XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string const& text, XmlFormatting fmt ) {
  12821. m_writer->writeText( text, fmt );
  12822. return *this;
  12823. }
  12824. XmlWriter::XmlWriter( std::ostream& os ) : m_os( os )
  12825. {
  12826. writeDeclaration();
  12827. }
  12828. XmlWriter::~XmlWriter() {
  12829. while (!m_tags.empty()) {
  12830. endElement();
  12831. }
  12832. newlineIfNecessary();
  12833. }
  12834. XmlWriter& XmlWriter::startElement( std::string const& name, XmlFormatting fmt ) {
  12835. ensureTagClosed();
  12836. newlineIfNecessary();
  12837. if (shouldIndent(fmt)) {
  12838. m_os << m_indent;
  12839. m_indent += " ";
  12840. }
  12841. m_os << '<' << name;
  12842. m_tags.push_back( name );
  12843. m_tagIsOpen = true;
  12844. applyFormatting(fmt);
  12845. return *this;
  12846. }
  12847. XmlWriter::ScopedElement XmlWriter::scopedElement( std::string const& name, XmlFormatting fmt ) {
  12848. ScopedElement scoped( this, fmt );
  12849. startElement( name, fmt );
  12850. return scoped;
  12851. }
  12852. XmlWriter& XmlWriter::endElement(XmlFormatting fmt) {
  12853. m_indent = m_indent.substr(0, m_indent.size() - 2);
  12854. if( m_tagIsOpen ) {
  12855. m_os << "/>";
  12856. m_tagIsOpen = false;
  12857. } else {
  12858. newlineIfNecessary();
  12859. if (shouldIndent(fmt)) {
  12860. m_os << m_indent;
  12861. }
  12862. m_os << "</" << m_tags.back() << ">";
  12863. }
  12864. m_os << std::flush;
  12865. applyFormatting(fmt);
  12866. m_tags.pop_back();
  12867. return *this;
  12868. }
  12869. XmlWriter& XmlWriter::writeAttribute( std::string const& name, std::string const& attribute ) {
  12870. if( !name.empty() && !attribute.empty() )
  12871. m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"';
  12872. return *this;
  12873. }
  12874. XmlWriter& XmlWriter::writeAttribute( std::string const& name, bool attribute ) {
  12875. m_os << ' ' << name << "=\"" << ( attribute ? "true" : "false" ) << '"';
  12876. return *this;
  12877. }
  12878. XmlWriter& XmlWriter::writeText( std::string const& text, XmlFormatting fmt) {
  12879. if( !text.empty() ){
  12880. bool tagWasOpen = m_tagIsOpen;
  12881. ensureTagClosed();
  12882. if (tagWasOpen && shouldIndent(fmt)) {
  12883. m_os << m_indent;
  12884. }
  12885. m_os << XmlEncode( text );
  12886. applyFormatting(fmt);
  12887. }
  12888. return *this;
  12889. }
  12890. XmlWriter& XmlWriter::writeComment( std::string const& text, XmlFormatting fmt) {
  12891. ensureTagClosed();
  12892. if (shouldIndent(fmt)) {
  12893. m_os << m_indent;
  12894. }
  12895. m_os << "<!--" << text << "-->";
  12896. applyFormatting(fmt);
  12897. return *this;
  12898. }
  12899. void XmlWriter::writeStylesheetRef( std::string const& url ) {
  12900. m_os << "<?xml-stylesheet type=\"text/xsl\" href=\"" << url << "\"?>\n";
  12901. }
  12902. XmlWriter& XmlWriter::writeBlankLine() {
  12903. ensureTagClosed();
  12904. m_os << '\n';
  12905. return *this;
  12906. }
  12907. void XmlWriter::ensureTagClosed() {
  12908. if( m_tagIsOpen ) {
  12909. m_os << '>' << std::flush;
  12910. newlineIfNecessary();
  12911. m_tagIsOpen = false;
  12912. }
  12913. }
  12914. void XmlWriter::applyFormatting(XmlFormatting fmt) {
  12915. m_needsNewline = shouldNewline(fmt);
  12916. }
  12917. void XmlWriter::writeDeclaration() {
  12918. m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
  12919. }
  12920. void XmlWriter::newlineIfNecessary() {
  12921. if( m_needsNewline ) {
  12922. m_os << std::endl;
  12923. m_needsNewline = false;
  12924. }
  12925. }
  12926. }
  12927. // end catch_xmlwriter.cpp
  12928. // start catch_reporter_bases.cpp
  12929. #include <cstring>
  12930. #include <cfloat>
  12931. #include <cstdio>
  12932. #include <cassert>
  12933. #include <memory>
  12934. namespace Catch {
  12935. void prepareExpandedExpression(AssertionResult& result) {
  12936. result.getExpandedExpression();
  12937. }
  12938. // Because formatting using c++ streams is stateful, drop down to C is required
  12939. // Alternatively we could use stringstream, but its performance is... not good.
  12940. std::string getFormattedDuration( double duration ) {
  12941. // Max exponent + 1 is required to represent the whole part
  12942. // + 1 for decimal point
  12943. // + 3 for the 3 decimal places
  12944. // + 1 for null terminator
  12945. const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1;
  12946. char buffer[maxDoubleSize];
  12947. // Save previous errno, to prevent sprintf from overwriting it
  12948. ErrnoGuard guard;
  12949. #ifdef _MSC_VER
  12950. sprintf_s(buffer, "%.3f", duration);
  12951. #else
  12952. std::sprintf(buffer, "%.3f", duration);
  12953. #endif
  12954. return std::string(buffer);
  12955. }
  12956. bool shouldShowDuration( IConfig const& config, double duration ) {
  12957. if ( config.showDurations() == ShowDurations::Always ) {
  12958. return true;
  12959. }
  12960. if ( config.showDurations() == ShowDurations::Never ) {
  12961. return false;
  12962. }
  12963. const double min = config.minDuration();
  12964. return min >= 0 && duration >= min;
  12965. }
  12966. std::string serializeFilters( std::vector<std::string> const& container ) {
  12967. ReusableStringStream oss;
  12968. bool first = true;
  12969. for (auto&& filter : container)
  12970. {
  12971. if (!first)
  12972. oss << ' ';
  12973. else
  12974. first = false;
  12975. oss << filter;
  12976. }
  12977. return oss.str();
  12978. }
  12979. TestEventListenerBase::TestEventListenerBase(ReporterConfig const & _config)
  12980. :StreamingReporterBase(_config) {}
  12981. std::set<Verbosity> TestEventListenerBase::getSupportedVerbosities() {
  12982. return { Verbosity::Quiet, Verbosity::Normal, Verbosity::High };
  12983. }
  12984. void TestEventListenerBase::assertionStarting(AssertionInfo const &) {}
  12985. bool TestEventListenerBase::assertionEnded(AssertionStats const &) {
  12986. return false;
  12987. }
  12988. } // end namespace Catch
  12989. // end catch_reporter_bases.cpp
  12990. // start catch_reporter_compact.cpp
  12991. namespace {
  12992. #ifdef CATCH_PLATFORM_MAC
  12993. const char* failedString() { return "FAILED"; }
  12994. const char* passedString() { return "PASSED"; }
  12995. #else
  12996. const char* failedString() { return "failed"; }
  12997. const char* passedString() { return "passed"; }
  12998. #endif
  12999. // Colour::LightGrey
  13000. Catch::Colour::Code dimColour() { return Catch::Colour::FileName; }
  13001. std::string bothOrAll( std::size_t count ) {
  13002. return count == 1 ? std::string() :
  13003. count == 2 ? "both " : "all " ;
  13004. }
  13005. } // anon namespace
  13006. namespace Catch {
  13007. namespace {
  13008. // Colour, message variants:
  13009. // - white: No tests ran.
  13010. // - red: Failed [both/all] N test cases, failed [both/all] M assertions.
  13011. // - white: Passed [both/all] N test cases (no assertions).
  13012. // - red: Failed N tests cases, failed M assertions.
  13013. // - green: Passed [both/all] N tests cases with M assertions.
  13014. void printTotals(std::ostream& out, const Totals& totals) {
  13015. if (totals.testCases.total() == 0) {
  13016. out << "No tests ran.";
  13017. } else if (totals.testCases.failed == totals.testCases.total()) {
  13018. Colour colour(Colour::ResultError);
  13019. const std::string qualify_assertions_failed =
  13020. totals.assertions.failed == totals.assertions.total() ?
  13021. bothOrAll(totals.assertions.failed) : std::string();
  13022. out <<
  13023. "Failed " << bothOrAll(totals.testCases.failed)
  13024. << pluralise(totals.testCases.failed, "test case") << ", "
  13025. "failed " << qualify_assertions_failed <<
  13026. pluralise(totals.assertions.failed, "assertion") << '.';
  13027. } else if (totals.assertions.total() == 0) {
  13028. out <<
  13029. "Passed " << bothOrAll(totals.testCases.total())
  13030. << pluralise(totals.testCases.total(), "test case")
  13031. << " (no assertions).";
  13032. } else if (totals.assertions.failed) {
  13033. Colour colour(Colour::ResultError);
  13034. out <<
  13035. "Failed " << pluralise(totals.testCases.failed, "test case") << ", "
  13036. "failed " << pluralise(totals.assertions.failed, "assertion") << '.';
  13037. } else {
  13038. Colour colour(Colour::ResultSuccess);
  13039. out <<
  13040. "Passed " << bothOrAll(totals.testCases.passed)
  13041. << pluralise(totals.testCases.passed, "test case") <<
  13042. " with " << pluralise(totals.assertions.passed, "assertion") << '.';
  13043. }
  13044. }
  13045. // Implementation of CompactReporter formatting
  13046. class AssertionPrinter {
  13047. public:
  13048. AssertionPrinter& operator= (AssertionPrinter const&) = delete;
  13049. AssertionPrinter(AssertionPrinter const&) = delete;
  13050. AssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
  13051. : stream(_stream)
  13052. , result(_stats.assertionResult)
  13053. , messages(_stats.infoMessages)
  13054. , itMessage(_stats.infoMessages.begin())
  13055. , printInfoMessages(_printInfoMessages) {}
  13056. void print() {
  13057. printSourceInfo();
  13058. itMessage = messages.begin();
  13059. switch (result.getResultType()) {
  13060. case ResultWas::Ok:
  13061. printResultType(Colour::ResultSuccess, passedString());
  13062. printOriginalExpression();
  13063. printReconstructedExpression();
  13064. if (!result.hasExpression())
  13065. printRemainingMessages(Colour::None);
  13066. else
  13067. printRemainingMessages();
  13068. break;
  13069. case ResultWas::ExpressionFailed:
  13070. if (result.isOk())
  13071. printResultType(Colour::ResultSuccess, failedString() + std::string(" - but was ok"));
  13072. else
  13073. printResultType(Colour::Error, failedString());
  13074. printOriginalExpression();
  13075. printReconstructedExpression();
  13076. printRemainingMessages();
  13077. break;
  13078. case ResultWas::ThrewException:
  13079. printResultType(Colour::Error, failedString());
  13080. printIssue("unexpected exception with message:");
  13081. printMessage();
  13082. printExpressionWas();
  13083. printRemainingMessages();
  13084. break;
  13085. case ResultWas::FatalErrorCondition:
  13086. printResultType(Colour::Error, failedString());
  13087. printIssue("fatal error condition with message:");
  13088. printMessage();
  13089. printExpressionWas();
  13090. printRemainingMessages();
  13091. break;
  13092. case ResultWas::DidntThrowException:
  13093. printResultType(Colour::Error, failedString());
  13094. printIssue("expected exception, got none");
  13095. printExpressionWas();
  13096. printRemainingMessages();
  13097. break;
  13098. case ResultWas::Info:
  13099. printResultType(Colour::None, "info");
  13100. printMessage();
  13101. printRemainingMessages();
  13102. break;
  13103. case ResultWas::Warning:
  13104. printResultType(Colour::None, "warning");
  13105. printMessage();
  13106. printRemainingMessages();
  13107. break;
  13108. case ResultWas::ExplicitFailure:
  13109. printResultType(Colour::Error, failedString());
  13110. printIssue("explicitly");
  13111. printRemainingMessages(Colour::None);
  13112. break;
  13113. // These cases are here to prevent compiler warnings
  13114. case ResultWas::Unknown:
  13115. case ResultWas::FailureBit:
  13116. case ResultWas::Exception:
  13117. printResultType(Colour::Error, "** internal error **");
  13118. break;
  13119. }
  13120. }
  13121. private:
  13122. void printSourceInfo() const {
  13123. Colour colourGuard(Colour::FileName);
  13124. stream << result.getSourceInfo() << ':';
  13125. }
  13126. void printResultType(Colour::Code colour, std::string const& passOrFail) const {
  13127. if (!passOrFail.empty()) {
  13128. {
  13129. Colour colourGuard(colour);
  13130. stream << ' ' << passOrFail;
  13131. }
  13132. stream << ':';
  13133. }
  13134. }
  13135. void printIssue(std::string const& issue) const {
  13136. stream << ' ' << issue;
  13137. }
  13138. void printExpressionWas() {
  13139. if (result.hasExpression()) {
  13140. stream << ';';
  13141. {
  13142. Colour colour(dimColour());
  13143. stream << " expression was:";
  13144. }
  13145. printOriginalExpression();
  13146. }
  13147. }
  13148. void printOriginalExpression() const {
  13149. if (result.hasExpression()) {
  13150. stream << ' ' << result.getExpression();
  13151. }
  13152. }
  13153. void printReconstructedExpression() const {
  13154. if (result.hasExpandedExpression()) {
  13155. {
  13156. Colour colour(dimColour());
  13157. stream << " for: ";
  13158. }
  13159. stream << result.getExpandedExpression();
  13160. }
  13161. }
  13162. void printMessage() {
  13163. if (itMessage != messages.end()) {
  13164. stream << " '" << itMessage->message << '\'';
  13165. ++itMessage;
  13166. }
  13167. }
  13168. void printRemainingMessages(Colour::Code colour = dimColour()) {
  13169. if (itMessage == messages.end())
  13170. return;
  13171. const auto itEnd = messages.cend();
  13172. const auto N = static_cast<std::size_t>(std::distance(itMessage, itEnd));
  13173. {
  13174. Colour colourGuard(colour);
  13175. stream << " with " << pluralise(N, "message") << ':';
  13176. }
  13177. while (itMessage != itEnd) {
  13178. // If this assertion is a warning ignore any INFO messages
  13179. if (printInfoMessages || itMessage->type != ResultWas::Info) {
  13180. printMessage();
  13181. if (itMessage != itEnd) {
  13182. Colour colourGuard(dimColour());
  13183. stream << " and";
  13184. }
  13185. continue;
  13186. }
  13187. ++itMessage;
  13188. }
  13189. }
  13190. private:
  13191. std::ostream& stream;
  13192. AssertionResult const& result;
  13193. std::vector<MessageInfo> messages;
  13194. std::vector<MessageInfo>::const_iterator itMessage;
  13195. bool printInfoMessages;
  13196. };
  13197. } // anon namespace
  13198. std::string CompactReporter::getDescription() {
  13199. return "Reports test results on a single line, suitable for IDEs";
  13200. }
  13201. void CompactReporter::noMatchingTestCases( std::string const& spec ) {
  13202. stream << "No test cases matched '" << spec << '\'' << std::endl;
  13203. }
  13204. void CompactReporter::assertionStarting( AssertionInfo const& ) {}
  13205. bool CompactReporter::assertionEnded( AssertionStats const& _assertionStats ) {
  13206. AssertionResult const& result = _assertionStats.assertionResult;
  13207. bool printInfoMessages = true;
  13208. // Drop out if result was successful and we're not printing those
  13209. if( !m_config->includeSuccessfulResults() && result.isOk() ) {
  13210. if( result.getResultType() != ResultWas::Warning )
  13211. return false;
  13212. printInfoMessages = false;
  13213. }
  13214. AssertionPrinter printer( stream, _assertionStats, printInfoMessages );
  13215. printer.print();
  13216. stream << std::endl;
  13217. return true;
  13218. }
  13219. void CompactReporter::sectionEnded(SectionStats const& _sectionStats) {
  13220. double dur = _sectionStats.durationInSeconds;
  13221. if ( shouldShowDuration( *m_config, dur ) ) {
  13222. stream << getFormattedDuration( dur ) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  13223. }
  13224. }
  13225. void CompactReporter::testRunEnded( TestRunStats const& _testRunStats ) {
  13226. printTotals( stream, _testRunStats.totals );
  13227. stream << '\n' << std::endl;
  13228. StreamingReporterBase::testRunEnded( _testRunStats );
  13229. }
  13230. CompactReporter::~CompactReporter() {}
  13231. CATCH_REGISTER_REPORTER( "compact", CompactReporter )
  13232. } // end namespace Catch
  13233. // end catch_reporter_compact.cpp
  13234. // start catch_reporter_console.cpp
  13235. #include <cfloat>
  13236. #include <cstdio>
  13237. #if defined(_MSC_VER)
  13238. #pragma warning(push)
  13239. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  13240. // Note that 4062 (not all labels are handled and default is missing) is enabled
  13241. #endif
  13242. #if defined(__clang__)
  13243. # pragma clang diagnostic push
  13244. // For simplicity, benchmarking-only helpers are always enabled
  13245. # pragma clang diagnostic ignored "-Wunused-function"
  13246. #endif
  13247. namespace Catch {
  13248. namespace {
  13249. // Formatter impl for ConsoleReporter
  13250. class ConsoleAssertionPrinter {
  13251. public:
  13252. ConsoleAssertionPrinter& operator= (ConsoleAssertionPrinter const&) = delete;
  13253. ConsoleAssertionPrinter(ConsoleAssertionPrinter const&) = delete;
  13254. ConsoleAssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
  13255. : stream(_stream),
  13256. stats(_stats),
  13257. result(_stats.assertionResult),
  13258. colour(Colour::None),
  13259. message(result.getMessage()),
  13260. messages(_stats.infoMessages),
  13261. printInfoMessages(_printInfoMessages) {
  13262. switch (result.getResultType()) {
  13263. case ResultWas::Ok:
  13264. colour = Colour::Success;
  13265. passOrFail = "PASSED";
  13266. //if( result.hasMessage() )
  13267. if (_stats.infoMessages.size() == 1)
  13268. messageLabel = "with message";
  13269. if (_stats.infoMessages.size() > 1)
  13270. messageLabel = "with messages";
  13271. break;
  13272. case ResultWas::ExpressionFailed:
  13273. if (result.isOk()) {
  13274. colour = Colour::Success;
  13275. passOrFail = "FAILED - but was ok";
  13276. } else {
  13277. colour = Colour::Error;
  13278. passOrFail = "FAILED";
  13279. }
  13280. if (_stats.infoMessages.size() == 1)
  13281. messageLabel = "with message";
  13282. if (_stats.infoMessages.size() > 1)
  13283. messageLabel = "with messages";
  13284. break;
  13285. case ResultWas::ThrewException:
  13286. colour = Colour::Error;
  13287. passOrFail = "FAILED";
  13288. messageLabel = "due to unexpected exception with ";
  13289. if (_stats.infoMessages.size() == 1)
  13290. messageLabel += "message";
  13291. if (_stats.infoMessages.size() > 1)
  13292. messageLabel += "messages";
  13293. break;
  13294. case ResultWas::FatalErrorCondition:
  13295. colour = Colour::Error;
  13296. passOrFail = "FAILED";
  13297. messageLabel = "due to a fatal error condition";
  13298. break;
  13299. case ResultWas::DidntThrowException:
  13300. colour = Colour::Error;
  13301. passOrFail = "FAILED";
  13302. messageLabel = "because no exception was thrown where one was expected";
  13303. break;
  13304. case ResultWas::Info:
  13305. messageLabel = "info";
  13306. break;
  13307. case ResultWas::Warning:
  13308. messageLabel = "warning";
  13309. break;
  13310. case ResultWas::ExplicitFailure:
  13311. passOrFail = "FAILED";
  13312. colour = Colour::Error;
  13313. if (_stats.infoMessages.size() == 1)
  13314. messageLabel = "explicitly with message";
  13315. if (_stats.infoMessages.size() > 1)
  13316. messageLabel = "explicitly with messages";
  13317. break;
  13318. // These cases are here to prevent compiler warnings
  13319. case ResultWas::Unknown:
  13320. case ResultWas::FailureBit:
  13321. case ResultWas::Exception:
  13322. passOrFail = "** internal error **";
  13323. colour = Colour::Error;
  13324. break;
  13325. }
  13326. }
  13327. void print() const {
  13328. printSourceInfo();
  13329. if (stats.totals.assertions.total() > 0) {
  13330. printResultType();
  13331. printOriginalExpression();
  13332. printReconstructedExpression();
  13333. } else {
  13334. stream << '\n';
  13335. }
  13336. printMessage();
  13337. }
  13338. private:
  13339. void printResultType() const {
  13340. if (!passOrFail.empty()) {
  13341. Colour colourGuard(colour);
  13342. stream << passOrFail << ":\n";
  13343. }
  13344. }
  13345. void printOriginalExpression() const {
  13346. if (result.hasExpression()) {
  13347. Colour colourGuard(Colour::OriginalExpression);
  13348. stream << " ";
  13349. stream << result.getExpressionInMacro();
  13350. stream << '\n';
  13351. }
  13352. }
  13353. void printReconstructedExpression() const {
  13354. if (result.hasExpandedExpression()) {
  13355. stream << "with expansion:\n";
  13356. Colour colourGuard(Colour::ReconstructedExpression);
  13357. stream << Column(result.getExpandedExpression()).indent(2) << '\n';
  13358. }
  13359. }
  13360. void printMessage() const {
  13361. if (!messageLabel.empty())
  13362. stream << messageLabel << ':' << '\n';
  13363. for (auto const& msg : messages) {
  13364. // If this assertion is a warning ignore any INFO messages
  13365. if (printInfoMessages || msg.type != ResultWas::Info)
  13366. stream << Column(msg.message).indent(2) << '\n';
  13367. }
  13368. }
  13369. void printSourceInfo() const {
  13370. Colour colourGuard(Colour::FileName);
  13371. stream << result.getSourceInfo() << ": ";
  13372. }
  13373. std::ostream& stream;
  13374. AssertionStats const& stats;
  13375. AssertionResult const& result;
  13376. Colour::Code colour;
  13377. std::string passOrFail;
  13378. std::string messageLabel;
  13379. std::string message;
  13380. std::vector<MessageInfo> messages;
  13381. bool printInfoMessages;
  13382. };
  13383. std::size_t makeRatio(std::size_t number, std::size_t total) {
  13384. std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0;
  13385. return (ratio == 0 && number > 0) ? 1 : ratio;
  13386. }
  13387. std::size_t& findMax(std::size_t& i, std::size_t& j, std::size_t& k) {
  13388. if (i > j && i > k)
  13389. return i;
  13390. else if (j > k)
  13391. return j;
  13392. else
  13393. return k;
  13394. }
  13395. struct ColumnInfo {
  13396. enum Justification { Left, Right };
  13397. std::string name;
  13398. int width;
  13399. Justification justification;
  13400. };
  13401. struct ColumnBreak {};
  13402. struct RowBreak {};
  13403. class Duration {
  13404. enum class Unit {
  13405. Auto,
  13406. Nanoseconds,
  13407. Microseconds,
  13408. Milliseconds,
  13409. Seconds,
  13410. Minutes
  13411. };
  13412. static const uint64_t s_nanosecondsInAMicrosecond = 1000;
  13413. static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond;
  13414. static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond;
  13415. static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond;
  13416. double m_inNanoseconds;
  13417. Unit m_units;
  13418. public:
  13419. explicit Duration(double inNanoseconds, Unit units = Unit::Microseconds)
  13420. : m_inNanoseconds(inNanoseconds),
  13421. m_units(units) {
  13422. if (m_units == Unit::Auto) {
  13423. if (m_inNanoseconds < s_nanosecondsInAMicrosecond)
  13424. m_units = Unit::Nanoseconds;
  13425. else if (m_inNanoseconds < s_nanosecondsInAMillisecond)
  13426. m_units = Unit::Microseconds;
  13427. else if (m_inNanoseconds < s_nanosecondsInASecond)
  13428. m_units = Unit::Milliseconds;
  13429. else if (m_inNanoseconds < s_nanosecondsInAMinute)
  13430. m_units = Unit::Seconds;
  13431. else
  13432. m_units = Unit::Minutes;
  13433. }
  13434. }
  13435. auto value() const -> double {
  13436. switch (m_units) {
  13437. case Unit::Microseconds:
  13438. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMicrosecond);
  13439. case Unit::Milliseconds:
  13440. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMillisecond);
  13441. case Unit::Seconds:
  13442. return m_inNanoseconds / static_cast<double>(s_nanosecondsInASecond);
  13443. case Unit::Minutes:
  13444. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMinute);
  13445. default:
  13446. return m_inNanoseconds;
  13447. }
  13448. }
  13449. auto unitsAsString() const -> std::string {
  13450. switch (m_units) {
  13451. case Unit::Nanoseconds:
  13452. return "ns";
  13453. case Unit::Microseconds:
  13454. return "us";
  13455. case Unit::Milliseconds:
  13456. return "ms";
  13457. case Unit::Seconds:
  13458. return "s";
  13459. case Unit::Minutes:
  13460. return "m";
  13461. default:
  13462. return "** internal error **";
  13463. }
  13464. }
  13465. friend auto operator << (std::ostream& os, Duration const& duration) -> std::ostream& {
  13466. return os << std::fixed << duration.value() << ' ' << duration.unitsAsString();
  13467. }
  13468. };
  13469. } // end anon namespace
  13470. class TablePrinter {
  13471. std::ostream& m_os;
  13472. std::vector<ColumnInfo> m_columnInfos;
  13473. std::ostringstream m_oss;
  13474. int m_currentColumn = -1;
  13475. bool m_isOpen = false;
  13476. public:
  13477. TablePrinter( std::ostream& os, std::vector<ColumnInfo> columnInfos )
  13478. : m_os( os ),
  13479. m_columnInfos( std::move( columnInfos ) ) {}
  13480. auto columnInfos() const -> std::vector<ColumnInfo> const& {
  13481. return m_columnInfos;
  13482. }
  13483. void open() {
  13484. if (!m_isOpen) {
  13485. m_isOpen = true;
  13486. *this << RowBreak();
  13487. Columns headerCols;
  13488. Spacer spacer(2);
  13489. for (auto const& info : m_columnInfos) {
  13490. headerCols += Column(info.name).width(static_cast<std::size_t>(info.width - 2));
  13491. headerCols += spacer;
  13492. }
  13493. m_os << headerCols << '\n';
  13494. m_os << Catch::getLineOfChars<'-'>() << '\n';
  13495. }
  13496. }
  13497. void close() {
  13498. if (m_isOpen) {
  13499. *this << RowBreak();
  13500. m_os << std::endl;
  13501. m_isOpen = false;
  13502. }
  13503. }
  13504. template<typename T>
  13505. friend TablePrinter& operator << (TablePrinter& tp, T const& value) {
  13506. tp.m_oss << value;
  13507. return tp;
  13508. }
  13509. friend TablePrinter& operator << (TablePrinter& tp, ColumnBreak) {
  13510. auto colStr = tp.m_oss.str();
  13511. const auto strSize = colStr.size();
  13512. tp.m_oss.str("");
  13513. tp.open();
  13514. if (tp.m_currentColumn == static_cast<int>(tp.m_columnInfos.size() - 1)) {
  13515. tp.m_currentColumn = -1;
  13516. tp.m_os << '\n';
  13517. }
  13518. tp.m_currentColumn++;
  13519. auto colInfo = tp.m_columnInfos[tp.m_currentColumn];
  13520. auto padding = (strSize + 1 < static_cast<std::size_t>(colInfo.width))
  13521. ? std::string(colInfo.width - (strSize + 1), ' ')
  13522. : std::string();
  13523. if (colInfo.justification == ColumnInfo::Left)
  13524. tp.m_os << colStr << padding << ' ';
  13525. else
  13526. tp.m_os << padding << colStr << ' ';
  13527. return tp;
  13528. }
  13529. friend TablePrinter& operator << (TablePrinter& tp, RowBreak) {
  13530. if (tp.m_currentColumn > 0) {
  13531. tp.m_os << '\n';
  13532. tp.m_currentColumn = -1;
  13533. }
  13534. return tp;
  13535. }
  13536. };
  13537. ConsoleReporter::ConsoleReporter(ReporterConfig const& config)
  13538. : StreamingReporterBase(config),
  13539. m_tablePrinter(new TablePrinter(config.stream(),
  13540. [&config]() -> std::vector<ColumnInfo> {
  13541. if (config.fullConfig()->benchmarkNoAnalysis())
  13542. {
  13543. return{
  13544. { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, ColumnInfo::Left },
  13545. { " samples", 14, ColumnInfo::Right },
  13546. { " iterations", 14, ColumnInfo::Right },
  13547. { " mean", 14, ColumnInfo::Right }
  13548. };
  13549. }
  13550. else
  13551. {
  13552. return{
  13553. { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, ColumnInfo::Left },
  13554. { "samples mean std dev", 14, ColumnInfo::Right },
  13555. { "iterations low mean low std dev", 14, ColumnInfo::Right },
  13556. { "estimated high mean high std dev", 14, ColumnInfo::Right }
  13557. };
  13558. }
  13559. }())) {}
  13560. ConsoleReporter::~ConsoleReporter() = default;
  13561. std::string ConsoleReporter::getDescription() {
  13562. return "Reports test results as plain lines of text";
  13563. }
  13564. void ConsoleReporter::noMatchingTestCases(std::string const& spec) {
  13565. stream << "No test cases matched '" << spec << '\'' << std::endl;
  13566. }
  13567. void ConsoleReporter::reportInvalidArguments(std::string const&arg){
  13568. stream << "Invalid Filter: " << arg << std::endl;
  13569. }
  13570. void ConsoleReporter::assertionStarting(AssertionInfo const&) {}
  13571. bool ConsoleReporter::assertionEnded(AssertionStats const& _assertionStats) {
  13572. AssertionResult const& result = _assertionStats.assertionResult;
  13573. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  13574. // Drop out if result was successful but we're not printing them.
  13575. if (!includeResults && result.getResultType() != ResultWas::Warning)
  13576. return false;
  13577. lazyPrint();
  13578. ConsoleAssertionPrinter printer(stream, _assertionStats, includeResults);
  13579. printer.print();
  13580. stream << std::endl;
  13581. return true;
  13582. }
  13583. void ConsoleReporter::sectionStarting(SectionInfo const& _sectionInfo) {
  13584. m_tablePrinter->close();
  13585. m_headerPrinted = false;
  13586. StreamingReporterBase::sectionStarting(_sectionInfo);
  13587. }
  13588. void ConsoleReporter::sectionEnded(SectionStats const& _sectionStats) {
  13589. m_tablePrinter->close();
  13590. if (_sectionStats.missingAssertions) {
  13591. lazyPrint();
  13592. Colour colour(Colour::ResultError);
  13593. if (m_sectionStack.size() > 1)
  13594. stream << "\nNo assertions in section";
  13595. else
  13596. stream << "\nNo assertions in test case";
  13597. stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl;
  13598. }
  13599. double dur = _sectionStats.durationInSeconds;
  13600. if (shouldShowDuration(*m_config, dur)) {
  13601. stream << getFormattedDuration(dur) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  13602. }
  13603. if (m_headerPrinted) {
  13604. m_headerPrinted = false;
  13605. }
  13606. StreamingReporterBase::sectionEnded(_sectionStats);
  13607. }
  13608. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  13609. void ConsoleReporter::benchmarkPreparing(std::string const& name) {
  13610. lazyPrintWithoutClosingBenchmarkTable();
  13611. auto nameCol = Column(name).width(static_cast<std::size_t>(m_tablePrinter->columnInfos()[0].width - 2));
  13612. bool firstLine = true;
  13613. for (auto line : nameCol) {
  13614. if (!firstLine)
  13615. (*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak();
  13616. else
  13617. firstLine = false;
  13618. (*m_tablePrinter) << line << ColumnBreak();
  13619. }
  13620. }
  13621. void ConsoleReporter::benchmarkStarting(BenchmarkInfo const& info) {
  13622. (*m_tablePrinter) << info.samples << ColumnBreak()
  13623. << info.iterations << ColumnBreak();
  13624. if (!m_config->benchmarkNoAnalysis())
  13625. (*m_tablePrinter) << Duration(info.estimatedDuration) << ColumnBreak();
  13626. }
  13627. void ConsoleReporter::benchmarkEnded(BenchmarkStats<> const& stats) {
  13628. if (m_config->benchmarkNoAnalysis())
  13629. {
  13630. (*m_tablePrinter) << Duration(stats.mean.point.count()) << ColumnBreak();
  13631. }
  13632. else
  13633. {
  13634. (*m_tablePrinter) << ColumnBreak()
  13635. << Duration(stats.mean.point.count()) << ColumnBreak()
  13636. << Duration(stats.mean.lower_bound.count()) << ColumnBreak()
  13637. << Duration(stats.mean.upper_bound.count()) << ColumnBreak() << ColumnBreak()
  13638. << Duration(stats.standardDeviation.point.count()) << ColumnBreak()
  13639. << Duration(stats.standardDeviation.lower_bound.count()) << ColumnBreak()
  13640. << Duration(stats.standardDeviation.upper_bound.count()) << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak();
  13641. }
  13642. }
  13643. void ConsoleReporter::benchmarkFailed(std::string const& error) {
  13644. Colour colour(Colour::Red);
  13645. (*m_tablePrinter)
  13646. << "Benchmark failed (" << error << ')'
  13647. << ColumnBreak() << RowBreak();
  13648. }
  13649. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  13650. void ConsoleReporter::testCaseEnded(TestCaseStats const& _testCaseStats) {
  13651. m_tablePrinter->close();
  13652. StreamingReporterBase::testCaseEnded(_testCaseStats);
  13653. m_headerPrinted = false;
  13654. }
  13655. void ConsoleReporter::testGroupEnded(TestGroupStats const& _testGroupStats) {
  13656. if (currentGroupInfo.used) {
  13657. printSummaryDivider();
  13658. stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n";
  13659. printTotals(_testGroupStats.totals);
  13660. stream << '\n' << std::endl;
  13661. }
  13662. StreamingReporterBase::testGroupEnded(_testGroupStats);
  13663. }
  13664. void ConsoleReporter::testRunEnded(TestRunStats const& _testRunStats) {
  13665. printTotalsDivider(_testRunStats.totals);
  13666. printTotals(_testRunStats.totals);
  13667. stream << std::endl;
  13668. StreamingReporterBase::testRunEnded(_testRunStats);
  13669. }
  13670. void ConsoleReporter::testRunStarting(TestRunInfo const& _testInfo) {
  13671. StreamingReporterBase::testRunStarting(_testInfo);
  13672. printTestFilters();
  13673. }
  13674. void ConsoleReporter::lazyPrint() {
  13675. m_tablePrinter->close();
  13676. lazyPrintWithoutClosingBenchmarkTable();
  13677. }
  13678. void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() {
  13679. if (!currentTestRunInfo.used)
  13680. lazyPrintRunInfo();
  13681. if (!currentGroupInfo.used)
  13682. lazyPrintGroupInfo();
  13683. if (!m_headerPrinted) {
  13684. printTestCaseAndSectionHeader();
  13685. m_headerPrinted = true;
  13686. }
  13687. }
  13688. void ConsoleReporter::lazyPrintRunInfo() {
  13689. stream << '\n' << getLineOfChars<'~'>() << '\n';
  13690. Colour colour(Colour::SecondaryText);
  13691. stream << currentTestRunInfo->name
  13692. << " is a Catch v" << libraryVersion() << " host application.\n"
  13693. << "Run with -? for options\n\n";
  13694. if (m_config->rngSeed() != 0)
  13695. stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n";
  13696. currentTestRunInfo.used = true;
  13697. }
  13698. void ConsoleReporter::lazyPrintGroupInfo() {
  13699. if (!currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1) {
  13700. printClosedHeader("Group: " + currentGroupInfo->name);
  13701. currentGroupInfo.used = true;
  13702. }
  13703. }
  13704. void ConsoleReporter::printTestCaseAndSectionHeader() {
  13705. assert(!m_sectionStack.empty());
  13706. printOpenHeader(currentTestCaseInfo->name);
  13707. if (m_sectionStack.size() > 1) {
  13708. Colour colourGuard(Colour::Headers);
  13709. auto
  13710. it = m_sectionStack.begin() + 1, // Skip first section (test case)
  13711. itEnd = m_sectionStack.end();
  13712. for (; it != itEnd; ++it)
  13713. printHeaderString(it->name, 2);
  13714. }
  13715. SourceLineInfo lineInfo = m_sectionStack.back().lineInfo;
  13716. stream << getLineOfChars<'-'>() << '\n';
  13717. Colour colourGuard(Colour::FileName);
  13718. stream << lineInfo << '\n';
  13719. stream << getLineOfChars<'.'>() << '\n' << std::endl;
  13720. }
  13721. void ConsoleReporter::printClosedHeader(std::string const& _name) {
  13722. printOpenHeader(_name);
  13723. stream << getLineOfChars<'.'>() << '\n';
  13724. }
  13725. void ConsoleReporter::printOpenHeader(std::string const& _name) {
  13726. stream << getLineOfChars<'-'>() << '\n';
  13727. {
  13728. Colour colourGuard(Colour::Headers);
  13729. printHeaderString(_name);
  13730. }
  13731. }
  13732. // if string has a : in first line will set indent to follow it on
  13733. // subsequent lines
  13734. void ConsoleReporter::printHeaderString(std::string const& _string, std::size_t indent) {
  13735. std::size_t i = _string.find(": ");
  13736. if (i != std::string::npos)
  13737. i += 2;
  13738. else
  13739. i = 0;
  13740. stream << Column(_string).indent(indent + i).initialIndent(indent) << '\n';
  13741. }
  13742. struct SummaryColumn {
  13743. SummaryColumn( std::string _label, Colour::Code _colour )
  13744. : label( std::move( _label ) ),
  13745. colour( _colour ) {}
  13746. SummaryColumn addRow( std::size_t count ) {
  13747. ReusableStringStream rss;
  13748. rss << count;
  13749. std::string row = rss.str();
  13750. for (auto& oldRow : rows) {
  13751. while (oldRow.size() < row.size())
  13752. oldRow = ' ' + oldRow;
  13753. while (oldRow.size() > row.size())
  13754. row = ' ' + row;
  13755. }
  13756. rows.push_back(row);
  13757. return *this;
  13758. }
  13759. std::string label;
  13760. Colour::Code colour;
  13761. std::vector<std::string> rows;
  13762. };
  13763. void ConsoleReporter::printTotals( Totals const& totals ) {
  13764. if (totals.testCases.total() == 0) {
  13765. stream << Colour(Colour::Warning) << "No tests ran\n";
  13766. } else if (totals.assertions.total() > 0 && totals.testCases.allPassed()) {
  13767. stream << Colour(Colour::ResultSuccess) << "All tests passed";
  13768. stream << " ("
  13769. << pluralise(totals.assertions.passed, "assertion") << " in "
  13770. << pluralise(totals.testCases.passed, "test case") << ')'
  13771. << '\n';
  13772. } else {
  13773. std::vector<SummaryColumn> columns;
  13774. columns.push_back(SummaryColumn("", Colour::None)
  13775. .addRow(totals.testCases.total())
  13776. .addRow(totals.assertions.total()));
  13777. columns.push_back(SummaryColumn("passed", Colour::Success)
  13778. .addRow(totals.testCases.passed)
  13779. .addRow(totals.assertions.passed));
  13780. columns.push_back(SummaryColumn("failed", Colour::ResultError)
  13781. .addRow(totals.testCases.failed)
  13782. .addRow(totals.assertions.failed));
  13783. columns.push_back(SummaryColumn("failed as expected", Colour::ResultExpectedFailure)
  13784. .addRow(totals.testCases.failedButOk)
  13785. .addRow(totals.assertions.failedButOk));
  13786. printSummaryRow("test cases", columns, 0);
  13787. printSummaryRow("assertions", columns, 1);
  13788. }
  13789. }
  13790. void ConsoleReporter::printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row) {
  13791. for (auto col : cols) {
  13792. std::string value = col.rows[row];
  13793. if (col.label.empty()) {
  13794. stream << label << ": ";
  13795. if (value != "0")
  13796. stream << value;
  13797. else
  13798. stream << Colour(Colour::Warning) << "- none -";
  13799. } else if (value != "0") {
  13800. stream << Colour(Colour::LightGrey) << " | ";
  13801. stream << Colour(col.colour)
  13802. << value << ' ' << col.label;
  13803. }
  13804. }
  13805. stream << '\n';
  13806. }
  13807. void ConsoleReporter::printTotalsDivider(Totals const& totals) {
  13808. if (totals.testCases.total() > 0) {
  13809. std::size_t failedRatio = makeRatio(totals.testCases.failed, totals.testCases.total());
  13810. std::size_t failedButOkRatio = makeRatio(totals.testCases.failedButOk, totals.testCases.total());
  13811. std::size_t passedRatio = makeRatio(totals.testCases.passed, totals.testCases.total());
  13812. while (failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1)
  13813. findMax(failedRatio, failedButOkRatio, passedRatio)++;
  13814. while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1)
  13815. findMax(failedRatio, failedButOkRatio, passedRatio)--;
  13816. stream << Colour(Colour::Error) << std::string(failedRatio, '=');
  13817. stream << Colour(Colour::ResultExpectedFailure) << std::string(failedButOkRatio, '=');
  13818. if (totals.testCases.allPassed())
  13819. stream << Colour(Colour::ResultSuccess) << std::string(passedRatio, '=');
  13820. else
  13821. stream << Colour(Colour::Success) << std::string(passedRatio, '=');
  13822. } else {
  13823. stream << Colour(Colour::Warning) << std::string(CATCH_CONFIG_CONSOLE_WIDTH - 1, '=');
  13824. }
  13825. stream << '\n';
  13826. }
  13827. void ConsoleReporter::printSummaryDivider() {
  13828. stream << getLineOfChars<'-'>() << '\n';
  13829. }
  13830. void ConsoleReporter::printTestFilters() {
  13831. if (m_config->testSpec().hasFilters()) {
  13832. Colour guard(Colour::BrightYellow);
  13833. stream << "Filters: " << serializeFilters(m_config->getTestsOrTags()) << '\n';
  13834. }
  13835. }
  13836. CATCH_REGISTER_REPORTER("console", ConsoleReporter)
  13837. } // end namespace Catch
  13838. #if defined(_MSC_VER)
  13839. #pragma warning(pop)
  13840. #endif
  13841. #if defined(__clang__)
  13842. # pragma clang diagnostic pop
  13843. #endif
  13844. // end catch_reporter_console.cpp
  13845. // start catch_reporter_junit.cpp
  13846. #include <cassert>
  13847. #include <sstream>
  13848. #include <ctime>
  13849. #include <algorithm>
  13850. #include <iomanip>
  13851. namespace Catch {
  13852. namespace {
  13853. std::string getCurrentTimestamp() {
  13854. // Beware, this is not reentrant because of backward compatibility issues
  13855. // Also, UTC only, again because of backward compatibility (%z is C++11)
  13856. time_t rawtime;
  13857. std::time(&rawtime);
  13858. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  13859. #ifdef _MSC_VER
  13860. std::tm timeInfo = {};
  13861. gmtime_s(&timeInfo, &rawtime);
  13862. #else
  13863. std::tm* timeInfo;
  13864. timeInfo = std::gmtime(&rawtime);
  13865. #endif
  13866. char timeStamp[timeStampSize];
  13867. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  13868. #ifdef _MSC_VER
  13869. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  13870. #else
  13871. std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
  13872. #endif
  13873. return std::string(timeStamp, timeStampSize-1);
  13874. }
  13875. std::string fileNameTag(const std::vector<std::string> &tags) {
  13876. auto it = std::find_if(begin(tags),
  13877. end(tags),
  13878. [] (std::string const& tag) {return tag.front() == '#'; });
  13879. if (it != tags.end())
  13880. return it->substr(1);
  13881. return std::string();
  13882. }
  13883. // Formats the duration in seconds to 3 decimal places.
  13884. // This is done because some genius defined Maven Surefire schema
  13885. // in a way that only accepts 3 decimal places, and tools like
  13886. // Jenkins use that schema for validation JUnit reporter output.
  13887. std::string formatDuration( double seconds ) {
  13888. ReusableStringStream rss;
  13889. rss << std::fixed << std::setprecision( 3 ) << seconds;
  13890. return rss.str();
  13891. }
  13892. } // anonymous namespace
  13893. JunitReporter::JunitReporter( ReporterConfig const& _config )
  13894. : CumulativeReporterBase( _config ),
  13895. xml( _config.stream() )
  13896. {
  13897. m_reporterPrefs.shouldRedirectStdOut = true;
  13898. m_reporterPrefs.shouldReportAllAssertions = true;
  13899. }
  13900. JunitReporter::~JunitReporter() {}
  13901. std::string JunitReporter::getDescription() {
  13902. return "Reports test results in an XML format that looks like Ant's junitreport target";
  13903. }
  13904. void JunitReporter::noMatchingTestCases( std::string const& /*spec*/ ) {}
  13905. void JunitReporter::testRunStarting( TestRunInfo const& runInfo ) {
  13906. CumulativeReporterBase::testRunStarting( runInfo );
  13907. xml.startElement( "testsuites" );
  13908. }
  13909. void JunitReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  13910. suiteTimer.start();
  13911. stdOutForSuite.clear();
  13912. stdErrForSuite.clear();
  13913. unexpectedExceptions = 0;
  13914. CumulativeReporterBase::testGroupStarting( groupInfo );
  13915. }
  13916. void JunitReporter::testCaseStarting( TestCaseInfo const& testCaseInfo ) {
  13917. m_okToFail = testCaseInfo.okToFail();
  13918. }
  13919. bool JunitReporter::assertionEnded( AssertionStats const& assertionStats ) {
  13920. if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail )
  13921. unexpectedExceptions++;
  13922. return CumulativeReporterBase::assertionEnded( assertionStats );
  13923. }
  13924. void JunitReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  13925. stdOutForSuite += testCaseStats.stdOut;
  13926. stdErrForSuite += testCaseStats.stdErr;
  13927. CumulativeReporterBase::testCaseEnded( testCaseStats );
  13928. }
  13929. void JunitReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  13930. double suiteTime = suiteTimer.getElapsedSeconds();
  13931. CumulativeReporterBase::testGroupEnded( testGroupStats );
  13932. writeGroup( *m_testGroups.back(), suiteTime );
  13933. }
  13934. void JunitReporter::testRunEndedCumulative() {
  13935. xml.endElement();
  13936. }
  13937. void JunitReporter::writeGroup( TestGroupNode const& groupNode, double suiteTime ) {
  13938. XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" );
  13939. TestGroupStats const& stats = groupNode.value;
  13940. xml.writeAttribute( "name", stats.groupInfo.name );
  13941. xml.writeAttribute( "errors", unexpectedExceptions );
  13942. xml.writeAttribute( "failures", stats.totals.assertions.failed-unexpectedExceptions );
  13943. xml.writeAttribute( "tests", stats.totals.assertions.total() );
  13944. xml.writeAttribute( "hostname", "tbd" ); // !TBD
  13945. if( m_config->showDurations() == ShowDurations::Never )
  13946. xml.writeAttribute( "time", "" );
  13947. else
  13948. xml.writeAttribute( "time", formatDuration( suiteTime ) );
  13949. xml.writeAttribute( "timestamp", getCurrentTimestamp() );
  13950. // Write properties if there are any
  13951. if (m_config->hasTestFilters() || m_config->rngSeed() != 0) {
  13952. auto properties = xml.scopedElement("properties");
  13953. if (m_config->hasTestFilters()) {
  13954. xml.scopedElement("property")
  13955. .writeAttribute("name", "filters")
  13956. .writeAttribute("value", serializeFilters(m_config->getTestsOrTags()));
  13957. }
  13958. if (m_config->rngSeed() != 0) {
  13959. xml.scopedElement("property")
  13960. .writeAttribute("name", "random-seed")
  13961. .writeAttribute("value", m_config->rngSeed());
  13962. }
  13963. }
  13964. // Write test cases
  13965. for( auto const& child : groupNode.children )
  13966. writeTestCase( *child );
  13967. xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite ), XmlFormatting::Newline );
  13968. xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite ), XmlFormatting::Newline );
  13969. }
  13970. void JunitReporter::writeTestCase( TestCaseNode const& testCaseNode ) {
  13971. TestCaseStats const& stats = testCaseNode.value;
  13972. // All test cases have exactly one section - which represents the
  13973. // test case itself. That section may have 0-n nested sections
  13974. assert( testCaseNode.children.size() == 1 );
  13975. SectionNode const& rootSection = *testCaseNode.children.front();
  13976. std::string className = stats.testInfo.className;
  13977. if( className.empty() ) {
  13978. className = fileNameTag(stats.testInfo.tags);
  13979. if ( className.empty() )
  13980. className = "global";
  13981. }
  13982. if ( !m_config->name().empty() )
  13983. className = m_config->name() + "." + className;
  13984. writeSection( className, "", rootSection, stats.testInfo.okToFail() );
  13985. }
  13986. void JunitReporter::writeSection( std::string const& className,
  13987. std::string const& rootName,
  13988. SectionNode const& sectionNode,
  13989. bool testOkToFail) {
  13990. std::string name = trim( sectionNode.stats.sectionInfo.name );
  13991. if( !rootName.empty() )
  13992. name = rootName + '/' + name;
  13993. if( !sectionNode.assertions.empty() ||
  13994. !sectionNode.stdOut.empty() ||
  13995. !sectionNode.stdErr.empty() ) {
  13996. XmlWriter::ScopedElement e = xml.scopedElement( "testcase" );
  13997. if( className.empty() ) {
  13998. xml.writeAttribute( "classname", name );
  13999. xml.writeAttribute( "name", "root" );
  14000. }
  14001. else {
  14002. xml.writeAttribute( "classname", className );
  14003. xml.writeAttribute( "name", name );
  14004. }
  14005. xml.writeAttribute( "time", formatDuration( sectionNode.stats.durationInSeconds ) );
  14006. // This is not ideal, but it should be enough to mimic gtest's
  14007. // junit output.
  14008. // Ideally the JUnit reporter would also handle `skipTest`
  14009. // events and write those out appropriately.
  14010. xml.writeAttribute( "status", "run" );
  14011. if (sectionNode.stats.assertions.failedButOk) {
  14012. xml.scopedElement("skipped")
  14013. .writeAttribute("message", "TEST_CASE tagged with !mayfail");
  14014. }
  14015. writeAssertions( sectionNode );
  14016. if( !sectionNode.stdOut.empty() )
  14017. xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), XmlFormatting::Newline );
  14018. if( !sectionNode.stdErr.empty() )
  14019. xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), XmlFormatting::Newline );
  14020. }
  14021. for( auto const& childNode : sectionNode.childSections )
  14022. if( className.empty() )
  14023. writeSection( name, "", *childNode, testOkToFail );
  14024. else
  14025. writeSection( className, name, *childNode, testOkToFail );
  14026. }
  14027. void JunitReporter::writeAssertions( SectionNode const& sectionNode ) {
  14028. for( auto const& assertion : sectionNode.assertions )
  14029. writeAssertion( assertion );
  14030. }
  14031. void JunitReporter::writeAssertion( AssertionStats const& stats ) {
  14032. AssertionResult const& result = stats.assertionResult;
  14033. if( !result.isOk() ) {
  14034. std::string elementName;
  14035. switch( result.getResultType() ) {
  14036. case ResultWas::ThrewException:
  14037. case ResultWas::FatalErrorCondition:
  14038. elementName = "error";
  14039. break;
  14040. case ResultWas::ExplicitFailure:
  14041. case ResultWas::ExpressionFailed:
  14042. case ResultWas::DidntThrowException:
  14043. elementName = "failure";
  14044. break;
  14045. // We should never see these here:
  14046. case ResultWas::Info:
  14047. case ResultWas::Warning:
  14048. case ResultWas::Ok:
  14049. case ResultWas::Unknown:
  14050. case ResultWas::FailureBit:
  14051. case ResultWas::Exception:
  14052. elementName = "internalError";
  14053. break;
  14054. }
  14055. XmlWriter::ScopedElement e = xml.scopedElement( elementName );
  14056. xml.writeAttribute( "message", result.getExpression() );
  14057. xml.writeAttribute( "type", result.getTestMacroName() );
  14058. ReusableStringStream rss;
  14059. if (stats.totals.assertions.total() > 0) {
  14060. rss << "FAILED" << ":\n";
  14061. if (result.hasExpression()) {
  14062. rss << " ";
  14063. rss << result.getExpressionInMacro();
  14064. rss << '\n';
  14065. }
  14066. if (result.hasExpandedExpression()) {
  14067. rss << "with expansion:\n";
  14068. rss << Column(result.getExpandedExpression()).indent(2) << '\n';
  14069. }
  14070. } else {
  14071. rss << '\n';
  14072. }
  14073. if( !result.getMessage().empty() )
  14074. rss << result.getMessage() << '\n';
  14075. for( auto const& msg : stats.infoMessages )
  14076. if( msg.type == ResultWas::Info )
  14077. rss << msg.message << '\n';
  14078. rss << "at " << result.getSourceInfo();
  14079. xml.writeText( rss.str(), XmlFormatting::Newline );
  14080. }
  14081. }
  14082. CATCH_REGISTER_REPORTER( "junit", JunitReporter )
  14083. } // end namespace Catch
  14084. // end catch_reporter_junit.cpp
  14085. // start catch_reporter_listening.cpp
  14086. #include <cassert>
  14087. namespace Catch {
  14088. ListeningReporter::ListeningReporter() {
  14089. // We will assume that listeners will always want all assertions
  14090. m_preferences.shouldReportAllAssertions = true;
  14091. }
  14092. void ListeningReporter::addListener( IStreamingReporterPtr&& listener ) {
  14093. m_listeners.push_back( std::move( listener ) );
  14094. }
  14095. void ListeningReporter::addReporter(IStreamingReporterPtr&& reporter) {
  14096. assert(!m_reporter && "Listening reporter can wrap only 1 real reporter");
  14097. m_reporter = std::move( reporter );
  14098. m_preferences.shouldRedirectStdOut = m_reporter->getPreferences().shouldRedirectStdOut;
  14099. }
  14100. ReporterPreferences ListeningReporter::getPreferences() const {
  14101. return m_preferences;
  14102. }
  14103. std::set<Verbosity> ListeningReporter::getSupportedVerbosities() {
  14104. return std::set<Verbosity>{ };
  14105. }
  14106. void ListeningReporter::noMatchingTestCases( std::string const& spec ) {
  14107. for ( auto const& listener : m_listeners ) {
  14108. listener->noMatchingTestCases( spec );
  14109. }
  14110. m_reporter->noMatchingTestCases( spec );
  14111. }
  14112. void ListeningReporter::reportInvalidArguments(std::string const&arg){
  14113. for ( auto const& listener : m_listeners ) {
  14114. listener->reportInvalidArguments( arg );
  14115. }
  14116. m_reporter->reportInvalidArguments( arg );
  14117. }
  14118. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  14119. void ListeningReporter::benchmarkPreparing( std::string const& name ) {
  14120. for (auto const& listener : m_listeners) {
  14121. listener->benchmarkPreparing(name);
  14122. }
  14123. m_reporter->benchmarkPreparing(name);
  14124. }
  14125. void ListeningReporter::benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) {
  14126. for ( auto const& listener : m_listeners ) {
  14127. listener->benchmarkStarting( benchmarkInfo );
  14128. }
  14129. m_reporter->benchmarkStarting( benchmarkInfo );
  14130. }
  14131. void ListeningReporter::benchmarkEnded( BenchmarkStats<> const& benchmarkStats ) {
  14132. for ( auto const& listener : m_listeners ) {
  14133. listener->benchmarkEnded( benchmarkStats );
  14134. }
  14135. m_reporter->benchmarkEnded( benchmarkStats );
  14136. }
  14137. void ListeningReporter::benchmarkFailed( std::string const& error ) {
  14138. for (auto const& listener : m_listeners) {
  14139. listener->benchmarkFailed(error);
  14140. }
  14141. m_reporter->benchmarkFailed(error);
  14142. }
  14143. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  14144. void ListeningReporter::testRunStarting( TestRunInfo const& testRunInfo ) {
  14145. for ( auto const& listener : m_listeners ) {
  14146. listener->testRunStarting( testRunInfo );
  14147. }
  14148. m_reporter->testRunStarting( testRunInfo );
  14149. }
  14150. void ListeningReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  14151. for ( auto const& listener : m_listeners ) {
  14152. listener->testGroupStarting( groupInfo );
  14153. }
  14154. m_reporter->testGroupStarting( groupInfo );
  14155. }
  14156. void ListeningReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
  14157. for ( auto const& listener : m_listeners ) {
  14158. listener->testCaseStarting( testInfo );
  14159. }
  14160. m_reporter->testCaseStarting( testInfo );
  14161. }
  14162. void ListeningReporter::sectionStarting( SectionInfo const& sectionInfo ) {
  14163. for ( auto const& listener : m_listeners ) {
  14164. listener->sectionStarting( sectionInfo );
  14165. }
  14166. m_reporter->sectionStarting( sectionInfo );
  14167. }
  14168. void ListeningReporter::assertionStarting( AssertionInfo const& assertionInfo ) {
  14169. for ( auto const& listener : m_listeners ) {
  14170. listener->assertionStarting( assertionInfo );
  14171. }
  14172. m_reporter->assertionStarting( assertionInfo );
  14173. }
  14174. // The return value indicates if the messages buffer should be cleared:
  14175. bool ListeningReporter::assertionEnded( AssertionStats const& assertionStats ) {
  14176. for( auto const& listener : m_listeners ) {
  14177. static_cast<void>( listener->assertionEnded( assertionStats ) );
  14178. }
  14179. return m_reporter->assertionEnded( assertionStats );
  14180. }
  14181. void ListeningReporter::sectionEnded( SectionStats const& sectionStats ) {
  14182. for ( auto const& listener : m_listeners ) {
  14183. listener->sectionEnded( sectionStats );
  14184. }
  14185. m_reporter->sectionEnded( sectionStats );
  14186. }
  14187. void ListeningReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  14188. for ( auto const& listener : m_listeners ) {
  14189. listener->testCaseEnded( testCaseStats );
  14190. }
  14191. m_reporter->testCaseEnded( testCaseStats );
  14192. }
  14193. void ListeningReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  14194. for ( auto const& listener : m_listeners ) {
  14195. listener->testGroupEnded( testGroupStats );
  14196. }
  14197. m_reporter->testGroupEnded( testGroupStats );
  14198. }
  14199. void ListeningReporter::testRunEnded( TestRunStats const& testRunStats ) {
  14200. for ( auto const& listener : m_listeners ) {
  14201. listener->testRunEnded( testRunStats );
  14202. }
  14203. m_reporter->testRunEnded( testRunStats );
  14204. }
  14205. void ListeningReporter::skipTest( TestCaseInfo const& testInfo ) {
  14206. for ( auto const& listener : m_listeners ) {
  14207. listener->skipTest( testInfo );
  14208. }
  14209. m_reporter->skipTest( testInfo );
  14210. }
  14211. bool ListeningReporter::isMulti() const {
  14212. return true;
  14213. }
  14214. } // end namespace Catch
  14215. // end catch_reporter_listening.cpp
  14216. // start catch_reporter_xml.cpp
  14217. #if defined(_MSC_VER)
  14218. #pragma warning(push)
  14219. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  14220. // Note that 4062 (not all labels are handled
  14221. // and default is missing) is enabled
  14222. #endif
  14223. namespace Catch {
  14224. XmlReporter::XmlReporter( ReporterConfig const& _config )
  14225. : StreamingReporterBase( _config ),
  14226. m_xml(_config.stream())
  14227. {
  14228. m_reporterPrefs.shouldRedirectStdOut = true;
  14229. m_reporterPrefs.shouldReportAllAssertions = true;
  14230. }
  14231. XmlReporter::~XmlReporter() = default;
  14232. std::string XmlReporter::getDescription() {
  14233. return "Reports test results as an XML document";
  14234. }
  14235. std::string XmlReporter::getStylesheetRef() const {
  14236. return std::string();
  14237. }
  14238. void XmlReporter::writeSourceInfo( SourceLineInfo const& sourceInfo ) {
  14239. m_xml
  14240. .writeAttribute( "filename", sourceInfo.file )
  14241. .writeAttribute( "line", sourceInfo.line );
  14242. }
  14243. void XmlReporter::noMatchingTestCases( std::string const& s ) {
  14244. StreamingReporterBase::noMatchingTestCases( s );
  14245. }
  14246. void XmlReporter::testRunStarting( TestRunInfo const& testInfo ) {
  14247. StreamingReporterBase::testRunStarting( testInfo );
  14248. std::string stylesheetRef = getStylesheetRef();
  14249. if( !stylesheetRef.empty() )
  14250. m_xml.writeStylesheetRef( stylesheetRef );
  14251. m_xml.startElement( "Catch" );
  14252. if( !m_config->name().empty() )
  14253. m_xml.writeAttribute( "name", m_config->name() );
  14254. if (m_config->testSpec().hasFilters())
  14255. m_xml.writeAttribute( "filters", serializeFilters( m_config->getTestsOrTags() ) );
  14256. if( m_config->rngSeed() != 0 )
  14257. m_xml.scopedElement( "Randomness" )
  14258. .writeAttribute( "seed", m_config->rngSeed() );
  14259. }
  14260. void XmlReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  14261. StreamingReporterBase::testGroupStarting( groupInfo );
  14262. m_xml.startElement( "Group" )
  14263. .writeAttribute( "name", groupInfo.name );
  14264. }
  14265. void XmlReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
  14266. StreamingReporterBase::testCaseStarting(testInfo);
  14267. m_xml.startElement( "TestCase" )
  14268. .writeAttribute( "name", trim( testInfo.name ) )
  14269. .writeAttribute( "description", testInfo.description )
  14270. .writeAttribute( "tags", testInfo.tagsAsString() );
  14271. writeSourceInfo( testInfo.lineInfo );
  14272. if ( m_config->showDurations() == ShowDurations::Always )
  14273. m_testCaseTimer.start();
  14274. m_xml.ensureTagClosed();
  14275. }
  14276. void XmlReporter::sectionStarting( SectionInfo const& sectionInfo ) {
  14277. StreamingReporterBase::sectionStarting( sectionInfo );
  14278. if( m_sectionDepth++ > 0 ) {
  14279. m_xml.startElement( "Section" )
  14280. .writeAttribute( "name", trim( sectionInfo.name ) );
  14281. writeSourceInfo( sectionInfo.lineInfo );
  14282. m_xml.ensureTagClosed();
  14283. }
  14284. }
  14285. void XmlReporter::assertionStarting( AssertionInfo const& ) { }
  14286. bool XmlReporter::assertionEnded( AssertionStats const& assertionStats ) {
  14287. AssertionResult const& result = assertionStats.assertionResult;
  14288. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  14289. if( includeResults || result.getResultType() == ResultWas::Warning ) {
  14290. // Print any info messages in <Info> tags.
  14291. for( auto const& msg : assertionStats.infoMessages ) {
  14292. if( msg.type == ResultWas::Info && includeResults ) {
  14293. m_xml.scopedElement( "Info" )
  14294. .writeText( msg.message );
  14295. } else if ( msg.type == ResultWas::Warning ) {
  14296. m_xml.scopedElement( "Warning" )
  14297. .writeText( msg.message );
  14298. }
  14299. }
  14300. }
  14301. // Drop out if result was successful but we're not printing them.
  14302. if( !includeResults && result.getResultType() != ResultWas::Warning )
  14303. return true;
  14304. // Print the expression if there is one.
  14305. if( result.hasExpression() ) {
  14306. m_xml.startElement( "Expression" )
  14307. .writeAttribute( "success", result.succeeded() )
  14308. .writeAttribute( "type", result.getTestMacroName() );
  14309. writeSourceInfo( result.getSourceInfo() );
  14310. m_xml.scopedElement( "Original" )
  14311. .writeText( result.getExpression() );
  14312. m_xml.scopedElement( "Expanded" )
  14313. .writeText( result.getExpandedExpression() );
  14314. }
  14315. // And... Print a result applicable to each result type.
  14316. switch( result.getResultType() ) {
  14317. case ResultWas::ThrewException:
  14318. m_xml.startElement( "Exception" );
  14319. writeSourceInfo( result.getSourceInfo() );
  14320. m_xml.writeText( result.getMessage() );
  14321. m_xml.endElement();
  14322. break;
  14323. case ResultWas::FatalErrorCondition:
  14324. m_xml.startElement( "FatalErrorCondition" );
  14325. writeSourceInfo( result.getSourceInfo() );
  14326. m_xml.writeText( result.getMessage() );
  14327. m_xml.endElement();
  14328. break;
  14329. case ResultWas::Info:
  14330. m_xml.scopedElement( "Info" )
  14331. .writeText( result.getMessage() );
  14332. break;
  14333. case ResultWas::Warning:
  14334. // Warning will already have been written
  14335. break;
  14336. case ResultWas::ExplicitFailure:
  14337. m_xml.startElement( "Failure" );
  14338. writeSourceInfo( result.getSourceInfo() );
  14339. m_xml.writeText( result.getMessage() );
  14340. m_xml.endElement();
  14341. break;
  14342. default:
  14343. break;
  14344. }
  14345. if( result.hasExpression() )
  14346. m_xml.endElement();
  14347. return true;
  14348. }
  14349. void XmlReporter::sectionEnded( SectionStats const& sectionStats ) {
  14350. StreamingReporterBase::sectionEnded( sectionStats );
  14351. if( --m_sectionDepth > 0 ) {
  14352. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResults" );
  14353. e.writeAttribute( "successes", sectionStats.assertions.passed );
  14354. e.writeAttribute( "failures", sectionStats.assertions.failed );
  14355. e.writeAttribute( "expectedFailures", sectionStats.assertions.failedButOk );
  14356. if ( m_config->showDurations() == ShowDurations::Always )
  14357. e.writeAttribute( "durationInSeconds", sectionStats.durationInSeconds );
  14358. m_xml.endElement();
  14359. }
  14360. }
  14361. void XmlReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  14362. StreamingReporterBase::testCaseEnded( testCaseStats );
  14363. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResult" );
  14364. e.writeAttribute( "success", testCaseStats.totals.assertions.allOk() );
  14365. if ( m_config->showDurations() == ShowDurations::Always )
  14366. e.writeAttribute( "durationInSeconds", m_testCaseTimer.getElapsedSeconds() );
  14367. if( !testCaseStats.stdOut.empty() )
  14368. m_xml.scopedElement( "StdOut" ).writeText( trim( testCaseStats.stdOut ), XmlFormatting::Newline );
  14369. if( !testCaseStats.stdErr.empty() )
  14370. m_xml.scopedElement( "StdErr" ).writeText( trim( testCaseStats.stdErr ), XmlFormatting::Newline );
  14371. m_xml.endElement();
  14372. }
  14373. void XmlReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  14374. StreamingReporterBase::testGroupEnded( testGroupStats );
  14375. // TODO: Check testGroupStats.aborting and act accordingly.
  14376. m_xml.scopedElement( "OverallResults" )
  14377. .writeAttribute( "successes", testGroupStats.totals.assertions.passed )
  14378. .writeAttribute( "failures", testGroupStats.totals.assertions.failed )
  14379. .writeAttribute( "expectedFailures", testGroupStats.totals.assertions.failedButOk );
  14380. m_xml.scopedElement( "OverallResultsCases")
  14381. .writeAttribute( "successes", testGroupStats.totals.testCases.passed )
  14382. .writeAttribute( "failures", testGroupStats.totals.testCases.failed )
  14383. .writeAttribute( "expectedFailures", testGroupStats.totals.testCases.failedButOk );
  14384. m_xml.endElement();
  14385. }
  14386. void XmlReporter::testRunEnded( TestRunStats const& testRunStats ) {
  14387. StreamingReporterBase::testRunEnded( testRunStats );
  14388. m_xml.scopedElement( "OverallResults" )
  14389. .writeAttribute( "successes", testRunStats.totals.assertions.passed )
  14390. .writeAttribute( "failures", testRunStats.totals.assertions.failed )
  14391. .writeAttribute( "expectedFailures", testRunStats.totals.assertions.failedButOk );
  14392. m_xml.scopedElement( "OverallResultsCases")
  14393. .writeAttribute( "successes", testRunStats.totals.testCases.passed )
  14394. .writeAttribute( "failures", testRunStats.totals.testCases.failed )
  14395. .writeAttribute( "expectedFailures", testRunStats.totals.testCases.failedButOk );
  14396. m_xml.endElement();
  14397. }
  14398. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  14399. void XmlReporter::benchmarkPreparing(std::string const& name) {
  14400. m_xml.startElement("BenchmarkResults")
  14401. .writeAttribute("name", name);
  14402. }
  14403. void XmlReporter::benchmarkStarting(BenchmarkInfo const &info) {
  14404. m_xml.writeAttribute("samples", info.samples)
  14405. .writeAttribute("resamples", info.resamples)
  14406. .writeAttribute("iterations", info.iterations)
  14407. .writeAttribute("clockResolution", info.clockResolution)
  14408. .writeAttribute("estimatedDuration", info.estimatedDuration)
  14409. .writeComment("All values in nano seconds");
  14410. }
  14411. void XmlReporter::benchmarkEnded(BenchmarkStats<> const& benchmarkStats) {
  14412. m_xml.startElement("mean")
  14413. .writeAttribute("value", benchmarkStats.mean.point.count())
  14414. .writeAttribute("lowerBound", benchmarkStats.mean.lower_bound.count())
  14415. .writeAttribute("upperBound", benchmarkStats.mean.upper_bound.count())
  14416. .writeAttribute("ci", benchmarkStats.mean.confidence_interval);
  14417. m_xml.endElement();
  14418. m_xml.startElement("standardDeviation")
  14419. .writeAttribute("value", benchmarkStats.standardDeviation.point.count())
  14420. .writeAttribute("lowerBound", benchmarkStats.standardDeviation.lower_bound.count())
  14421. .writeAttribute("upperBound", benchmarkStats.standardDeviation.upper_bound.count())
  14422. .writeAttribute("ci", benchmarkStats.standardDeviation.confidence_interval);
  14423. m_xml.endElement();
  14424. m_xml.startElement("outliers")
  14425. .writeAttribute("variance", benchmarkStats.outlierVariance)
  14426. .writeAttribute("lowMild", benchmarkStats.outliers.low_mild)
  14427. .writeAttribute("lowSevere", benchmarkStats.outliers.low_severe)
  14428. .writeAttribute("highMild", benchmarkStats.outliers.high_mild)
  14429. .writeAttribute("highSevere", benchmarkStats.outliers.high_severe);
  14430. m_xml.endElement();
  14431. m_xml.endElement();
  14432. }
  14433. void XmlReporter::benchmarkFailed(std::string const &error) {
  14434. m_xml.scopedElement("failed").
  14435. writeAttribute("message", error);
  14436. m_xml.endElement();
  14437. }
  14438. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  14439. CATCH_REGISTER_REPORTER( "xml", XmlReporter )
  14440. } // end namespace Catch
  14441. #if defined(_MSC_VER)
  14442. #pragma warning(pop)
  14443. #endif
  14444. // end catch_reporter_xml.cpp
  14445. namespace Catch {
  14446. LeakDetector leakDetector;
  14447. }
  14448. #ifdef __clang__
  14449. #pragma clang diagnostic pop
  14450. #endif
  14451. // end catch_impl.hpp
  14452. #endif
  14453. #ifdef CATCH_CONFIG_MAIN
  14454. // start catch_default_main.hpp
  14455. #ifndef __OBJC__
  14456. #if defined(CATCH_CONFIG_WCHAR) && defined(CATCH_PLATFORM_WINDOWS) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN)
  14457. // Standard C/C++ Win32 Unicode wmain entry point
  14458. extern "C" int wmain (int argc, wchar_t * argv[], wchar_t * []) {
  14459. #else
  14460. // Standard C/C++ main entry point
  14461. int main (int argc, char * argv[]) {
  14462. #endif
  14463. return Catch::Session().run( argc, argv );
  14464. }
  14465. #else // __OBJC__
  14466. // Objective-C entry point
  14467. int main (int argc, char * const argv[]) {
  14468. #if !CATCH_ARC_ENABLED
  14469. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  14470. #endif
  14471. Catch::registerTestMethods();
  14472. int result = Catch::Session().run( argc, (char**)argv );
  14473. #if !CATCH_ARC_ENABLED
  14474. [pool drain];
  14475. #endif
  14476. return result;
  14477. }
  14478. #endif // __OBJC__
  14479. // end catch_default_main.hpp
  14480. #endif
  14481. #if !defined(CATCH_CONFIG_IMPL_ONLY)
  14482. #ifdef CLARA_CONFIG_MAIN_NOT_DEFINED
  14483. # undef CLARA_CONFIG_MAIN
  14484. #endif
  14485. #if !defined(CATCH_CONFIG_DISABLE)
  14486. //////
  14487. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  14488. #ifdef CATCH_CONFIG_PREFIX_ALL
  14489. #define CATCH_REQUIRE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  14490. #define CATCH_REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  14491. #define CATCH_REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  14492. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  14493. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  14494. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14495. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  14496. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  14497. #define CATCH_REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  14498. #define CATCH_CHECK( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14499. #define CATCH_CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  14500. #define CATCH_CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14501. #define CATCH_CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14502. #define CATCH_CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  14503. #define CATCH_CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14504. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  14505. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  14506. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14507. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  14508. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14509. #define CATCH_CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14510. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14511. #define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  14512. #define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  14513. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14514. #define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg )
  14515. #define CATCH_UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "CATCH_UNSCOPED_INFO", msg )
  14516. #define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  14517. #define CATCH_CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CATCH_CAPTURE",__VA_ARGS__ )
  14518. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  14519. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14520. #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  14521. #define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  14522. #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  14523. #define CATCH_DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
  14524. #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  14525. #define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14526. #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14527. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  14528. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  14529. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14530. #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ )
  14531. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14532. #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
  14533. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )
  14534. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ )
  14535. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14536. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
  14537. #else
  14538. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
  14539. #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) )
  14540. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  14541. #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
  14542. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )
  14543. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) )
  14544. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  14545. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
  14546. #endif
  14547. #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
  14548. #define CATCH_STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__ , #__VA_ARGS__ ); CATCH_SUCCEED( #__VA_ARGS__ )
  14549. #define CATCH_STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); CATCH_SUCCEED( #__VA_ARGS__ )
  14550. #else
  14551. #define CATCH_STATIC_REQUIRE( ... ) CATCH_REQUIRE( __VA_ARGS__ )
  14552. #define CATCH_STATIC_REQUIRE_FALSE( ... ) CATCH_REQUIRE_FALSE( __VA_ARGS__ )
  14553. #endif
  14554. // "BDD-style" convenience wrappers
  14555. #define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ )
  14556. #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  14557. #define CATCH_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
  14558. #define CATCH_AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
  14559. #define CATCH_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
  14560. #define CATCH_AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
  14561. #define CATCH_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
  14562. #define CATCH_AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
  14563. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  14564. #define CATCH_BENCHMARK(...) \
  14565. 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__,,))
  14566. #define CATCH_BENCHMARK_ADVANCED(name) \
  14567. INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_B_E_N_C_H_), name)
  14568. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  14569. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  14570. #else
  14571. #define REQUIRE( ... ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  14572. #define REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  14573. #define REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  14574. #define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  14575. #define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  14576. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14577. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  14578. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14579. #define REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  14580. #define CHECK( ... ) INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14581. #define CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  14582. #define CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14583. #define CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14584. #define CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  14585. #define CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14586. #define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  14587. #define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  14588. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14589. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  14590. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14591. #define CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14592. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14593. #define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  14594. #define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  14595. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14596. #define INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg )
  14597. #define UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "UNSCOPED_INFO", msg )
  14598. #define WARN( msg ) INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  14599. #define CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CAPTURE",__VA_ARGS__ )
  14600. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  14601. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14602. #define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  14603. #define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  14604. #define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  14605. #define DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
  14606. #define FAIL( ... ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  14607. #define FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14608. #define SUCCEED( ... ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14609. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  14610. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  14611. #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14612. #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ )
  14613. #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14614. #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
  14615. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )
  14616. #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ )
  14617. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14618. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
  14619. #define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(__VA_ARGS__)
  14620. #define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14621. #else
  14622. #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
  14623. #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) )
  14624. #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  14625. #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
  14626. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )
  14627. #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) )
  14628. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  14629. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
  14630. #define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE( __VA_ARGS__ ) )
  14631. #define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  14632. #endif
  14633. #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
  14634. #define STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__, #__VA_ARGS__ ); SUCCEED( #__VA_ARGS__ )
  14635. #define STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); SUCCEED( "!(" #__VA_ARGS__ ")" )
  14636. #else
  14637. #define STATIC_REQUIRE( ... ) REQUIRE( __VA_ARGS__ )
  14638. #define STATIC_REQUIRE_FALSE( ... ) REQUIRE_FALSE( __VA_ARGS__ )
  14639. #endif
  14640. #endif
  14641. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature )
  14642. // "BDD-style" convenience wrappers
  14643. #define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ )
  14644. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  14645. #define GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
  14646. #define AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
  14647. #define WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
  14648. #define AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
  14649. #define THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
  14650. #define AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
  14651. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  14652. #define BENCHMARK(...) \
  14653. 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__,,))
  14654. #define BENCHMARK_ADVANCED(name) \
  14655. INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_B_E_N_C_H_), name)
  14656. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  14657. using Catch::Detail::Approx;
  14658. #else // CATCH_CONFIG_DISABLE
  14659. //////
  14660. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  14661. #ifdef CATCH_CONFIG_PREFIX_ALL
  14662. #define CATCH_REQUIRE( ... ) (void)(0)
  14663. #define CATCH_REQUIRE_FALSE( ... ) (void)(0)
  14664. #define CATCH_REQUIRE_THROWS( ... ) (void)(0)
  14665. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  14666. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  14667. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14668. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  14669. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  14670. #define CATCH_REQUIRE_NOTHROW( ... ) (void)(0)
  14671. #define CATCH_CHECK( ... ) (void)(0)
  14672. #define CATCH_CHECK_FALSE( ... ) (void)(0)
  14673. #define CATCH_CHECKED_IF( ... ) if (__VA_ARGS__)
  14674. #define CATCH_CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  14675. #define CATCH_CHECK_NOFAIL( ... ) (void)(0)
  14676. #define CATCH_CHECK_THROWS( ... ) (void)(0)
  14677. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  14678. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  14679. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14680. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  14681. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14682. #define CATCH_CHECK_NOTHROW( ... ) (void)(0)
  14683. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14684. #define CATCH_CHECK_THAT( arg, matcher ) (void)(0)
  14685. #define CATCH_REQUIRE_THAT( arg, matcher ) (void)(0)
  14686. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14687. #define CATCH_INFO( msg ) (void)(0)
  14688. #define CATCH_UNSCOPED_INFO( msg ) (void)(0)
  14689. #define CATCH_WARN( msg ) (void)(0)
  14690. #define CATCH_CAPTURE( msg ) (void)(0)
  14691. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ))
  14692. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ))
  14693. #define CATCH_METHOD_AS_TEST_CASE( method, ... )
  14694. #define CATCH_REGISTER_TEST_CASE( Function, ... ) (void)(0)
  14695. #define CATCH_SECTION( ... )
  14696. #define CATCH_DYNAMIC_SECTION( ... )
  14697. #define CATCH_FAIL( ... ) (void)(0)
  14698. #define CATCH_FAIL_CHECK( ... ) (void)(0)
  14699. #define CATCH_SUCCEED( ... ) (void)(0)
  14700. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ))
  14701. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  14702. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
  14703. #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
  14704. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
  14705. #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ )
  14706. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14707. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14708. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14709. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14710. #else
  14711. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) )
  14712. #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) )
  14713. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) )
  14714. #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) )
  14715. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14716. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14717. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14718. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14719. #endif
  14720. // "BDD-style" convenience wrappers
  14721. #define CATCH_SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ))
  14722. #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 )
  14723. #define CATCH_GIVEN( desc )
  14724. #define CATCH_AND_GIVEN( desc )
  14725. #define CATCH_WHEN( desc )
  14726. #define CATCH_AND_WHEN( desc )
  14727. #define CATCH_THEN( desc )
  14728. #define CATCH_AND_THEN( desc )
  14729. #define CATCH_STATIC_REQUIRE( ... ) (void)(0)
  14730. #define CATCH_STATIC_REQUIRE_FALSE( ... ) (void)(0)
  14731. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  14732. #else
  14733. #define REQUIRE( ... ) (void)(0)
  14734. #define REQUIRE_FALSE( ... ) (void)(0)
  14735. #define REQUIRE_THROWS( ... ) (void)(0)
  14736. #define REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  14737. #define REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  14738. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14739. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  14740. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14741. #define REQUIRE_NOTHROW( ... ) (void)(0)
  14742. #define CHECK( ... ) (void)(0)
  14743. #define CHECK_FALSE( ... ) (void)(0)
  14744. #define CHECKED_IF( ... ) if (__VA_ARGS__)
  14745. #define CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  14746. #define CHECK_NOFAIL( ... ) (void)(0)
  14747. #define CHECK_THROWS( ... ) (void)(0)
  14748. #define CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  14749. #define CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  14750. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14751. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  14752. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14753. #define CHECK_NOTHROW( ... ) (void)(0)
  14754. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14755. #define CHECK_THAT( arg, matcher ) (void)(0)
  14756. #define REQUIRE_THAT( arg, matcher ) (void)(0)
  14757. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14758. #define INFO( msg ) (void)(0)
  14759. #define UNSCOPED_INFO( msg ) (void)(0)
  14760. #define WARN( msg ) (void)(0)
  14761. #define CAPTURE( ... ) (void)(0)
  14762. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ))
  14763. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ))
  14764. #define METHOD_AS_TEST_CASE( method, ... )
  14765. #define REGISTER_TEST_CASE( Function, ... ) (void)(0)
  14766. #define SECTION( ... )
  14767. #define DYNAMIC_SECTION( ... )
  14768. #define FAIL( ... ) (void)(0)
  14769. #define FAIL_CHECK( ... ) (void)(0)
  14770. #define SUCCEED( ... ) (void)(0)
  14771. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ))
  14772. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  14773. #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
  14774. #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
  14775. #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
  14776. #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ )
  14777. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14778. #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14779. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14780. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14781. #else
  14782. #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) )
  14783. #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) )
  14784. #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) )
  14785. #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) )
  14786. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14787. #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14788. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14789. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14790. #endif
  14791. #define STATIC_REQUIRE( ... ) (void)(0)
  14792. #define STATIC_REQUIRE_FALSE( ... ) (void)(0)
  14793. #endif
  14794. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
  14795. // "BDD-style" convenience wrappers
  14796. #define SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ) )
  14797. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ), className )
  14798. #define GIVEN( desc )
  14799. #define AND_GIVEN( desc )
  14800. #define WHEN( desc )
  14801. #define AND_WHEN( desc )
  14802. #define THEN( desc )
  14803. #define AND_THEN( desc )
  14804. using Catch::Detail::Approx;
  14805. #endif
  14806. #endif // ! CATCH_CONFIG_IMPL_ONLY
  14807. // start catch_reenable_warnings.h
  14808. #ifdef __clang__
  14809. # ifdef __ICC // icpc defines the __clang__ macro
  14810. # pragma warning(pop)
  14811. # else
  14812. # pragma clang diagnostic pop
  14813. # endif
  14814. #elif defined __GNUC__
  14815. # pragma GCC diagnostic pop
  14816. #endif
  14817. // end catch_reenable_warnings.h
  14818. // end catch.hpp
  14819. #endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED