catch.hpp 641 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937
  1. /*
  2. * Catch v2.13.6
  3. * Generated: 2021-04-16 18:23:38.044268
  4. * ----------------------------------------------------------
  5. * This file has been merged from multiple headers. Please don't edit it directly
  6. * Copyright (c) 2021 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 6
  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. # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION __pragma( warning(push) )
  196. # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION __pragma( warning(pop) )
  197. // Universal Windows platform does not support SEH
  198. // Or console colours (or console at all...)
  199. # if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP)
  200. # define CATCH_CONFIG_COLOUR_NONE
  201. # else
  202. # define CATCH_INTERNAL_CONFIG_WINDOWS_SEH
  203. # endif
  204. // MSVC traditional preprocessor needs some workaround for __VA_ARGS__
  205. // _MSVC_TRADITIONAL == 0 means new conformant preprocessor
  206. // _MSVC_TRADITIONAL == 1 means old traditional non-conformant preprocessor
  207. # if !defined(__clang__) // Handle Clang masquerading for msvc
  208. # if !defined(_MSVC_TRADITIONAL) || (defined(_MSVC_TRADITIONAL) && _MSVC_TRADITIONAL)
  209. # define CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  210. # endif // MSVC_TRADITIONAL
  211. # endif // __clang__
  212. #endif // _MSC_VER
  213. #if defined(_REENTRANT) || defined(_MSC_VER)
  214. // Enable async processing, as -pthread is specified or no additional linking is required
  215. # define CATCH_INTERNAL_CONFIG_USE_ASYNC
  216. #endif // _MSC_VER
  217. ////////////////////////////////////////////////////////////////////////////////
  218. // Check if we are compiled with -fno-exceptions or equivalent
  219. #if defined(__EXCEPTIONS) || defined(__cpp_exceptions) || defined(_CPPUNWIND)
  220. # define CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED
  221. #endif
  222. ////////////////////////////////////////////////////////////////////////////////
  223. // DJGPP
  224. #ifdef __DJGPP__
  225. # define CATCH_INTERNAL_CONFIG_NO_WCHAR
  226. #endif // __DJGPP__
  227. ////////////////////////////////////////////////////////////////////////////////
  228. // Embarcadero C++Build
  229. #if defined(__BORLANDC__)
  230. #define CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN
  231. #endif
  232. ////////////////////////////////////////////////////////////////////////////////
  233. // Use of __COUNTER__ is suppressed during code analysis in
  234. // CLion/AppCode 2017.2.x and former, because __COUNTER__ is not properly
  235. // handled by it.
  236. // Otherwise all supported compilers support COUNTER macro,
  237. // but user still might want to turn it off
  238. #if ( !defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L )
  239. #define CATCH_INTERNAL_CONFIG_COUNTER
  240. #endif
  241. ////////////////////////////////////////////////////////////////////////////////
  242. // RTX is a special version of Windows that is real time.
  243. // This means that it is detected as Windows, but does not provide
  244. // the same set of capabilities as real Windows does.
  245. #if defined(UNDER_RTSS) || defined(RTX64_BUILD)
  246. #define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH
  247. #define CATCH_INTERNAL_CONFIG_NO_ASYNC
  248. #define CATCH_CONFIG_COLOUR_NONE
  249. #endif
  250. #if !defined(_GLIBCXX_USE_C99_MATH_TR1)
  251. #define CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER
  252. #endif
  253. // Various stdlib support checks that require __has_include
  254. #if defined(__has_include)
  255. // Check if string_view is available and usable
  256. #if __has_include(<string_view>) && defined(CATCH_CPP17_OR_GREATER)
  257. # define CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW
  258. #endif
  259. // Check if optional is available and usable
  260. # if __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
  261. # define CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL
  262. # endif // __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
  263. // Check if byte is available and usable
  264. # if __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER)
  265. # include <cstddef>
  266. # if __cpp_lib_byte > 0
  267. # define CATCH_INTERNAL_CONFIG_CPP17_BYTE
  268. # endif
  269. # endif // __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER)
  270. // Check if variant is available and usable
  271. # if __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
  272. # if defined(__clang__) && (__clang_major__ < 8)
  273. // work around clang bug with libstdc++ https://bugs.llvm.org/show_bug.cgi?id=31852
  274. // fix should be in clang 8, workaround in libstdc++ 8.2
  275. # include <ciso646>
  276. # if defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
  277. # define CATCH_CONFIG_NO_CPP17_VARIANT
  278. # else
  279. # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
  280. # endif // defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
  281. # else
  282. # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
  283. # endif // defined(__clang__) && (__clang_major__ < 8)
  284. # endif // __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
  285. #endif // defined(__has_include)
  286. #if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER)
  287. # define CATCH_CONFIG_COUNTER
  288. #endif
  289. #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)
  290. # define CATCH_CONFIG_WINDOWS_SEH
  291. #endif
  292. // This is set by default, because we assume that unix compilers are posix-signal-compatible by default.
  293. #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)
  294. # define CATCH_CONFIG_POSIX_SIGNALS
  295. #endif
  296. // This is set by default, because we assume that compilers with no wchar_t support are just rare exceptions.
  297. #if !defined(CATCH_INTERNAL_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_WCHAR)
  298. # define CATCH_CONFIG_WCHAR
  299. #endif
  300. #if !defined(CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_CPP11_TO_STRING)
  301. # define CATCH_CONFIG_CPP11_TO_STRING
  302. #endif
  303. #if defined(CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_NO_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_CPP17_OPTIONAL)
  304. # define CATCH_CONFIG_CPP17_OPTIONAL
  305. #endif
  306. #if defined(CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_NO_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_CPP17_STRING_VIEW)
  307. # define CATCH_CONFIG_CPP17_STRING_VIEW
  308. #endif
  309. #if defined(CATCH_INTERNAL_CONFIG_CPP17_VARIANT) && !defined(CATCH_CONFIG_NO_CPP17_VARIANT) && !defined(CATCH_CONFIG_CPP17_VARIANT)
  310. # define CATCH_CONFIG_CPP17_VARIANT
  311. #endif
  312. #if defined(CATCH_INTERNAL_CONFIG_CPP17_BYTE) && !defined(CATCH_CONFIG_NO_CPP17_BYTE) && !defined(CATCH_CONFIG_CPP17_BYTE)
  313. # define CATCH_CONFIG_CPP17_BYTE
  314. #endif
  315. #if defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
  316. # define CATCH_INTERNAL_CONFIG_NEW_CAPTURE
  317. #endif
  318. #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)
  319. # define CATCH_CONFIG_NEW_CAPTURE
  320. #endif
  321. #if !defined(CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  322. # define CATCH_CONFIG_DISABLE_EXCEPTIONS
  323. #endif
  324. #if defined(CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_NO_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_POLYFILL_ISNAN)
  325. # define CATCH_CONFIG_POLYFILL_ISNAN
  326. #endif
  327. #if defined(CATCH_INTERNAL_CONFIG_USE_ASYNC) && !defined(CATCH_INTERNAL_CONFIG_NO_ASYNC) && !defined(CATCH_CONFIG_NO_USE_ASYNC) && !defined(CATCH_CONFIG_USE_ASYNC)
  328. # define CATCH_CONFIG_USE_ASYNC
  329. #endif
  330. #if defined(CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_NO_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_ANDROID_LOGWRITE)
  331. # define CATCH_CONFIG_ANDROID_LOGWRITE
  332. #endif
  333. #if defined(CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_NO_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
  334. # define CATCH_CONFIG_GLOBAL_NEXTAFTER
  335. #endif
  336. // Even if we do not think the compiler has that warning, we still have
  337. // to provide a macro that can be used by the code.
  338. #if !defined(CATCH_INTERNAL_START_WARNINGS_SUPPRESSION)
  339. # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION
  340. #endif
  341. #if !defined(CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION)
  342. # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
  343. #endif
  344. #if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS)
  345. # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS
  346. #endif
  347. #if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS)
  348. # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  349. #endif
  350. #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS)
  351. # define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS
  352. #endif
  353. #if !defined(CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS)
  354. # define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS
  355. #endif
  356. // The goal of this macro is to avoid evaluation of the arguments, but
  357. // still have the compiler warn on problems inside...
  358. #if !defined(CATCH_INTERNAL_IGNORE_BUT_WARN)
  359. # define CATCH_INTERNAL_IGNORE_BUT_WARN(...)
  360. #endif
  361. #if defined(__APPLE__) && defined(__apple_build_version__) && (__clang_major__ < 10)
  362. # undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
  363. #elif defined(__clang__) && (__clang_major__ < 5)
  364. # undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
  365. #endif
  366. #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS)
  367. # define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
  368. #endif
  369. #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  370. #define CATCH_TRY if ((true))
  371. #define CATCH_CATCH_ALL if ((false))
  372. #define CATCH_CATCH_ANON(type) if ((false))
  373. #else
  374. #define CATCH_TRY try
  375. #define CATCH_CATCH_ALL catch (...)
  376. #define CATCH_CATCH_ANON(type) catch (type)
  377. #endif
  378. #if defined(CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_NO_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR)
  379. #define CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  380. #endif
  381. // end catch_compiler_capabilities.h
  382. #define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line
  383. #define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line )
  384. #ifdef CATCH_CONFIG_COUNTER
  385. # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ )
  386. #else
  387. # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ )
  388. #endif
  389. #include <iosfwd>
  390. #include <string>
  391. #include <cstdint>
  392. // We need a dummy global operator<< so we can bring it into Catch namespace later
  393. struct Catch_global_namespace_dummy {};
  394. std::ostream& operator<<(std::ostream&, Catch_global_namespace_dummy);
  395. namespace Catch {
  396. struct CaseSensitive { enum Choice {
  397. Yes,
  398. No
  399. }; };
  400. class NonCopyable {
  401. NonCopyable( NonCopyable const& ) = delete;
  402. NonCopyable( NonCopyable && ) = delete;
  403. NonCopyable& operator = ( NonCopyable const& ) = delete;
  404. NonCopyable& operator = ( NonCopyable && ) = delete;
  405. protected:
  406. NonCopyable();
  407. virtual ~NonCopyable();
  408. };
  409. struct SourceLineInfo {
  410. SourceLineInfo() = delete;
  411. SourceLineInfo( char const* _file, std::size_t _line ) noexcept
  412. : file( _file ),
  413. line( _line )
  414. {}
  415. SourceLineInfo( SourceLineInfo const& other ) = default;
  416. SourceLineInfo& operator = ( SourceLineInfo const& ) = default;
  417. SourceLineInfo( SourceLineInfo&& ) noexcept = default;
  418. SourceLineInfo& operator = ( SourceLineInfo&& ) noexcept = default;
  419. bool empty() const noexcept { return file[0] == '\0'; }
  420. bool operator == ( SourceLineInfo const& other ) const noexcept;
  421. bool operator < ( SourceLineInfo const& other ) const noexcept;
  422. char const* file;
  423. std::size_t line;
  424. };
  425. std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info );
  426. // Bring in operator<< from global namespace into Catch namespace
  427. // This is necessary because the overload of operator<< above makes
  428. // lookup stop at namespace Catch
  429. using ::operator<<;
  430. // Use this in variadic streaming macros to allow
  431. // >> +StreamEndStop
  432. // as well as
  433. // >> stuff +StreamEndStop
  434. struct StreamEndStop {
  435. std::string operator+() const;
  436. };
  437. template<typename T>
  438. T const& operator + ( T const& value, StreamEndStop ) {
  439. return value;
  440. }
  441. }
  442. #define CATCH_INTERNAL_LINEINFO \
  443. ::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) )
  444. // end catch_common.h
  445. namespace Catch {
  446. struct RegistrarForTagAliases {
  447. RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo );
  448. };
  449. } // end namespace Catch
  450. #define CATCH_REGISTER_TAG_ALIAS( alias, spec ) \
  451. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
  452. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  453. namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } \
  454. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
  455. // end catch_tag_alias_autoregistrar.h
  456. // start catch_test_registry.h
  457. // start catch_interfaces_testcase.h
  458. #include <vector>
  459. namespace Catch {
  460. class TestSpec;
  461. struct ITestInvoker {
  462. virtual void invoke () const = 0;
  463. virtual ~ITestInvoker();
  464. };
  465. class TestCase;
  466. struct IConfig;
  467. struct ITestCaseRegistry {
  468. virtual ~ITestCaseRegistry();
  469. virtual std::vector<TestCase> const& getAllTests() const = 0;
  470. virtual std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const = 0;
  471. };
  472. bool isThrowSafe( TestCase const& testCase, IConfig const& config );
  473. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
  474. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
  475. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
  476. }
  477. // end catch_interfaces_testcase.h
  478. // start catch_stringref.h
  479. #include <cstddef>
  480. #include <string>
  481. #include <iosfwd>
  482. #include <cassert>
  483. namespace Catch {
  484. /// A non-owning string class (similar to the forthcoming std::string_view)
  485. /// Note that, because a StringRef may be a substring of another string,
  486. /// it may not be null terminated.
  487. class StringRef {
  488. public:
  489. using size_type = std::size_t;
  490. using const_iterator = const char*;
  491. private:
  492. static constexpr char const* const s_empty = "";
  493. char const* m_start = s_empty;
  494. size_type m_size = 0;
  495. public: // construction
  496. constexpr StringRef() noexcept = default;
  497. StringRef( char const* rawChars ) noexcept;
  498. constexpr StringRef( char const* rawChars, size_type size ) noexcept
  499. : m_start( rawChars ),
  500. m_size( size )
  501. {}
  502. StringRef( std::string const& stdString ) noexcept
  503. : m_start( stdString.c_str() ),
  504. m_size( stdString.size() )
  505. {}
  506. explicit operator std::string() const {
  507. return std::string(m_start, m_size);
  508. }
  509. public: // operators
  510. auto operator == ( StringRef const& other ) const noexcept -> bool;
  511. auto operator != (StringRef const& other) const noexcept -> bool {
  512. return !(*this == other);
  513. }
  514. auto operator[] ( size_type index ) const noexcept -> char {
  515. assert(index < m_size);
  516. return m_start[index];
  517. }
  518. public: // named queries
  519. constexpr auto empty() const noexcept -> bool {
  520. return m_size == 0;
  521. }
  522. constexpr auto size() const noexcept -> size_type {
  523. return m_size;
  524. }
  525. // Returns the current start pointer. If the StringRef is not
  526. // null-terminated, throws std::domain_exception
  527. auto c_str() const -> char const*;
  528. public: // substrings and searches
  529. // Returns a substring of [start, start + length).
  530. // If start + length > size(), then the substring is [start, size()).
  531. // If start > size(), then the substring is empty.
  532. auto substr( size_type start, size_type length ) const noexcept -> StringRef;
  533. // Returns the current start pointer. May not be null-terminated.
  534. auto data() const noexcept -> char const*;
  535. constexpr auto isNullTerminated() const noexcept -> bool {
  536. return m_start[m_size] == '\0';
  537. }
  538. public: // iterators
  539. constexpr const_iterator begin() const { return m_start; }
  540. constexpr const_iterator end() const { return m_start + m_size; }
  541. };
  542. auto operator += ( std::string& lhs, StringRef const& sr ) -> std::string&;
  543. auto operator << ( std::ostream& os, StringRef const& sr ) -> std::ostream&;
  544. constexpr auto operator "" _sr( char const* rawChars, std::size_t size ) noexcept -> StringRef {
  545. return StringRef( rawChars, size );
  546. }
  547. } // namespace Catch
  548. constexpr auto operator "" _catch_sr( char const* rawChars, std::size_t size ) noexcept -> Catch::StringRef {
  549. return Catch::StringRef( rawChars, size );
  550. }
  551. // end catch_stringref.h
  552. // start catch_preprocessor.hpp
  553. #define CATCH_RECURSION_LEVEL0(...) __VA_ARGS__
  554. #define CATCH_RECURSION_LEVEL1(...) CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(__VA_ARGS__)))
  555. #define CATCH_RECURSION_LEVEL2(...) CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(__VA_ARGS__)))
  556. #define CATCH_RECURSION_LEVEL3(...) CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(__VA_ARGS__)))
  557. #define CATCH_RECURSION_LEVEL4(...) CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(__VA_ARGS__)))
  558. #define CATCH_RECURSION_LEVEL5(...) CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(__VA_ARGS__)))
  559. #ifdef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  560. #define INTERNAL_CATCH_EXPAND_VARGS(...) __VA_ARGS__
  561. // MSVC needs more evaluations
  562. #define CATCH_RECURSION_LEVEL6(...) CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(__VA_ARGS__)))
  563. #define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL6(CATCH_RECURSION_LEVEL6(__VA_ARGS__))
  564. #else
  565. #define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL5(__VA_ARGS__)
  566. #endif
  567. #define CATCH_REC_END(...)
  568. #define CATCH_REC_OUT
  569. #define CATCH_EMPTY()
  570. #define CATCH_DEFER(id) id CATCH_EMPTY()
  571. #define CATCH_REC_GET_END2() 0, CATCH_REC_END
  572. #define CATCH_REC_GET_END1(...) CATCH_REC_GET_END2
  573. #define CATCH_REC_GET_END(...) CATCH_REC_GET_END1
  574. #define CATCH_REC_NEXT0(test, next, ...) next CATCH_REC_OUT
  575. #define CATCH_REC_NEXT1(test, next) CATCH_DEFER ( CATCH_REC_NEXT0 ) ( test, next, 0)
  576. #define CATCH_REC_NEXT(test, next) CATCH_REC_NEXT1(CATCH_REC_GET_END test, next)
  577. #define CATCH_REC_LIST0(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ )
  578. #define CATCH_REC_LIST1(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0) ) ( f, peek, __VA_ARGS__ )
  579. #define CATCH_REC_LIST2(f, x, peek, ...) f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ )
  580. #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__ )
  581. #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__ )
  582. #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__ )
  583. // Applies the function macro `f` to each of the remaining parameters, inserts commas between the results,
  584. // and passes userdata as the first parameter to each invocation,
  585. // e.g. CATCH_REC_LIST_UD(f, x, a, b, c) evaluates to f(x, a), f(x, b), f(x, c)
  586. #define CATCH_REC_LIST_UD(f, userdata, ...) CATCH_RECURSE(CATCH_REC_LIST2_UD(f, userdata, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
  587. #define CATCH_REC_LIST(f, ...) CATCH_RECURSE(CATCH_REC_LIST2(f, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
  588. #define INTERNAL_CATCH_EXPAND1(param) INTERNAL_CATCH_EXPAND2(param)
  589. #define INTERNAL_CATCH_EXPAND2(...) INTERNAL_CATCH_NO## __VA_ARGS__
  590. #define INTERNAL_CATCH_DEF(...) INTERNAL_CATCH_DEF __VA_ARGS__
  591. #define INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
  592. #define INTERNAL_CATCH_STRINGIZE(...) INTERNAL_CATCH_STRINGIZE2(__VA_ARGS__)
  593. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  594. #define INTERNAL_CATCH_STRINGIZE2(...) #__VA_ARGS__
  595. #define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param))
  596. #else
  597. // MSVC is adding extra space and needs another indirection to expand INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
  598. #define INTERNAL_CATCH_STRINGIZE2(...) INTERNAL_CATCH_STRINGIZE3(__VA_ARGS__)
  599. #define INTERNAL_CATCH_STRINGIZE3(...) #__VA_ARGS__
  600. #define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) (INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) + 1)
  601. #endif
  602. #define INTERNAL_CATCH_MAKE_NAMESPACE2(...) ns_##__VA_ARGS__
  603. #define INTERNAL_CATCH_MAKE_NAMESPACE(name) INTERNAL_CATCH_MAKE_NAMESPACE2(name)
  604. #define INTERNAL_CATCH_REMOVE_PARENS(...) INTERNAL_CATCH_EXPAND1(INTERNAL_CATCH_DEF __VA_ARGS__)
  605. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  606. #define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>())
  607. #define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__))
  608. #else
  609. #define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) INTERNAL_CATCH_EXPAND_VARGS(decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>()))
  610. #define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__)))
  611. #endif
  612. #define INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(...)\
  613. CATCH_REC_LIST(INTERNAL_CATCH_MAKE_TYPE_LIST,__VA_ARGS__)
  614. #define INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_0) INTERNAL_CATCH_REMOVE_PARENS(_0)
  615. #define INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_0, _1) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_1)
  616. #define INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_0, _1, _2) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_1, _2)
  617. #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)
  618. #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)
  619. #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)
  620. #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)
  621. #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)
  622. #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)
  623. #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)
  624. #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)
  625. #define INTERNAL_CATCH_VA_NARGS_IMPL(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N
  626. #define INTERNAL_CATCH_TYPE_GEN\
  627. template<typename...> struct TypeList {};\
  628. template<typename...Ts>\
  629. constexpr auto get_wrapper() noexcept -> TypeList<Ts...> { return {}; }\
  630. template<template<typename...> class...> struct TemplateTypeList{};\
  631. template<template<typename...> class...Cs>\
  632. constexpr auto get_wrapper() noexcept -> TemplateTypeList<Cs...> { return {}; }\
  633. template<typename...>\
  634. struct append;\
  635. template<typename...>\
  636. struct rewrap;\
  637. template<template<typename...> class, typename...>\
  638. struct create;\
  639. template<template<typename...> class, typename>\
  640. struct convert;\
  641. \
  642. template<typename T> \
  643. struct append<T> { using type = T; };\
  644. template< template<typename...> class L1, typename...E1, template<typename...> class L2, typename...E2, typename...Rest>\
  645. struct append<L1<E1...>, L2<E2...>, Rest...> { using type = typename append<L1<E1...,E2...>, Rest...>::type; };\
  646. template< template<typename...> class L1, typename...E1, typename...Rest>\
  647. struct append<L1<E1...>, TypeList<mpl_::na>, Rest...> { using type = L1<E1...>; };\
  648. \
  649. template< template<typename...> class Container, template<typename...> class List, typename...elems>\
  650. struct rewrap<TemplateTypeList<Container>, List<elems...>> { using type = TypeList<Container<elems...>>; };\
  651. template< template<typename...> class Container, template<typename...> class List, class...Elems, typename...Elements>\
  652. struct rewrap<TemplateTypeList<Container>, List<Elems...>, Elements...> { using type = typename append<TypeList<Container<Elems...>>, typename rewrap<TemplateTypeList<Container>, Elements...>::type>::type; };\
  653. \
  654. template<template <typename...> class Final, template< typename...> class...Containers, typename...Types>\
  655. struct create<Final, TemplateTypeList<Containers...>, TypeList<Types...>> { using type = typename append<Final<>, typename rewrap<TemplateTypeList<Containers>, Types...>::type...>::type; };\
  656. template<template <typename...> class Final, template <typename...> class List, typename...Ts>\
  657. struct convert<Final, List<Ts...>> { using type = typename append<Final<>,TypeList<Ts>...>::type; };
  658. #define INTERNAL_CATCH_NTTP_1(signature, ...)\
  659. template<INTERNAL_CATCH_REMOVE_PARENS(signature)> struct Nttp{};\
  660. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  661. constexpr auto get_wrapper() noexcept -> Nttp<__VA_ARGS__> { return {}; } \
  662. template<template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...> struct NttpTemplateTypeList{};\
  663. template<template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...Cs>\
  664. constexpr auto get_wrapper() noexcept -> NttpTemplateTypeList<Cs...> { return {}; } \
  665. \
  666. template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  667. struct rewrap<NttpTemplateTypeList<Container>, List<__VA_ARGS__>> { using type = TypeList<Container<__VA_ARGS__>>; };\
  668. template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature), typename...Elements>\
  669. struct rewrap<NttpTemplateTypeList<Container>, List<__VA_ARGS__>, Elements...> { using type = typename append<TypeList<Container<__VA_ARGS__>>, typename rewrap<NttpTemplateTypeList<Container>, Elements...>::type>::type; };\
  670. template<template <typename...> class Final, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...Containers, typename...Types>\
  671. struct create<Final, NttpTemplateTypeList<Containers...>, TypeList<Types...>> { using type = typename append<Final<>, typename rewrap<NttpTemplateTypeList<Containers>, Types...>::type...>::type; };
  672. #define INTERNAL_CATCH_DECLARE_SIG_TEST0(TestName)
  673. #define INTERNAL_CATCH_DECLARE_SIG_TEST1(TestName, signature)\
  674. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  675. static void TestName()
  676. #define INTERNAL_CATCH_DECLARE_SIG_TEST_X(TestName, signature, ...)\
  677. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  678. static void TestName()
  679. #define INTERNAL_CATCH_DEFINE_SIG_TEST0(TestName)
  680. #define INTERNAL_CATCH_DEFINE_SIG_TEST1(TestName, signature)\
  681. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  682. static void TestName()
  683. #define INTERNAL_CATCH_DEFINE_SIG_TEST_X(TestName, signature,...)\
  684. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  685. static void TestName()
  686. #define INTERNAL_CATCH_NTTP_REGISTER0(TestFunc, signature)\
  687. template<typename Type>\
  688. void reg_test(TypeList<Type>, Catch::NameAndTags nameAndTags)\
  689. {\
  690. Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<Type>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\
  691. }
  692. #define INTERNAL_CATCH_NTTP_REGISTER(TestFunc, signature, ...)\
  693. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  694. void reg_test(Nttp<__VA_ARGS__>, Catch::NameAndTags nameAndTags)\
  695. {\
  696. Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<__VA_ARGS__>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\
  697. }
  698. #define INTERNAL_CATCH_NTTP_REGISTER_METHOD0(TestName, signature, ...)\
  699. template<typename Type>\
  700. void reg_test(TypeList<Type>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\
  701. {\
  702. Catch::AutoReg( Catch::makeTestInvoker(&TestName<Type>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\
  703. }
  704. #define INTERNAL_CATCH_NTTP_REGISTER_METHOD(TestName, signature, ...)\
  705. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  706. void reg_test(Nttp<__VA_ARGS__>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\
  707. {\
  708. Catch::AutoReg( Catch::makeTestInvoker(&TestName<__VA_ARGS__>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\
  709. }
  710. #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0(TestName, ClassName)
  711. #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1(TestName, ClassName, signature)\
  712. template<typename TestType> \
  713. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<TestType> { \
  714. void test();\
  715. }
  716. #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X(TestName, ClassName, signature, ...)\
  717. template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \
  718. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<__VA_ARGS__> { \
  719. void test();\
  720. }
  721. #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0(TestName)
  722. #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1(TestName, signature)\
  723. template<typename TestType> \
  724. void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<TestType>::test()
  725. #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X(TestName, signature, ...)\
  726. template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \
  727. void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<__VA_ARGS__>::test()
  728. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  729. #define INTERNAL_CATCH_NTTP_0
  730. #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)
  731. #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__)
  732. #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__)
  733. #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__)
  734. #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__)
  735. #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__)
  736. #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__)
  737. #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__)
  738. #else
  739. #define INTERNAL_CATCH_NTTP_0(signature)
  740. #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__))
  741. #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__))
  742. #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__))
  743. #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__))
  744. #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__))
  745. #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__))
  746. #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__))
  747. #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__))
  748. #endif
  749. // end catch_preprocessor.hpp
  750. // start catch_meta.hpp
  751. #include <type_traits>
  752. namespace Catch {
  753. template<typename T>
  754. struct always_false : std::false_type {};
  755. template <typename> struct true_given : std::true_type {};
  756. struct is_callable_tester {
  757. template <typename Fun, typename... Args>
  758. true_given<decltype(std::declval<Fun>()(std::declval<Args>()...))> static test(int);
  759. template <typename...>
  760. std::false_type static test(...);
  761. };
  762. template <typename T>
  763. struct is_callable;
  764. template <typename Fun, typename... Args>
  765. struct is_callable<Fun(Args...)> : decltype(is_callable_tester::test<Fun, Args...>(0)) {};
  766. #if defined(__cpp_lib_is_invocable) && __cpp_lib_is_invocable >= 201703
  767. // std::result_of is deprecated in C++17 and removed in C++20. Hence, it is
  768. // replaced with std::invoke_result here.
  769. template <typename Func, typename... U>
  770. using FunctionReturnType = std::remove_reference_t<std::remove_cv_t<std::invoke_result_t<Func, U...>>>;
  771. #else
  772. // Keep ::type here because we still support C++11
  773. template <typename Func, typename... U>
  774. using FunctionReturnType = typename std::remove_reference<typename std::remove_cv<typename std::result_of<Func(U...)>::type>::type>::type;
  775. #endif
  776. } // namespace Catch
  777. namespace mpl_{
  778. struct na;
  779. }
  780. // end catch_meta.hpp
  781. namespace Catch {
  782. template<typename C>
  783. class TestInvokerAsMethod : public ITestInvoker {
  784. void (C::*m_testAsMethod)();
  785. public:
  786. TestInvokerAsMethod( void (C::*testAsMethod)() ) noexcept : m_testAsMethod( testAsMethod ) {}
  787. void invoke() const override {
  788. C obj;
  789. (obj.*m_testAsMethod)();
  790. }
  791. };
  792. auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker*;
  793. template<typename C>
  794. auto makeTestInvoker( void (C::*testAsMethod)() ) noexcept -> ITestInvoker* {
  795. return new(std::nothrow) TestInvokerAsMethod<C>( testAsMethod );
  796. }
  797. struct NameAndTags {
  798. NameAndTags( StringRef const& name_ = StringRef(), StringRef const& tags_ = StringRef() ) noexcept;
  799. StringRef name;
  800. StringRef tags;
  801. };
  802. struct AutoReg : NonCopyable {
  803. AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept;
  804. ~AutoReg();
  805. };
  806. } // end namespace Catch
  807. #if defined(CATCH_CONFIG_DISABLE)
  808. #define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( TestName, ... ) \
  809. static void TestName()
  810. #define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( TestName, ClassName, ... ) \
  811. namespace{ \
  812. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
  813. void test(); \
  814. }; \
  815. } \
  816. void TestName::test()
  817. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( TestName, TestFunc, Name, Tags, Signature, ... ) \
  818. INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature))
  819. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... ) \
  820. namespace{ \
  821. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
  822. INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
  823. } \
  824. } \
  825. INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))
  826. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  827. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \
  828. 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__ )
  829. #else
  830. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \
  831. 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__ ) )
  832. #endif
  833. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  834. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \
  835. 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__ )
  836. #else
  837. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \
  838. 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__ ) )
  839. #endif
  840. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  841. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \
  842. 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__ )
  843. #else
  844. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \
  845. 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__ ) )
  846. #endif
  847. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  848. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \
  849. 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__ )
  850. #else
  851. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \
  852. 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__ ) )
  853. #endif
  854. #endif
  855. ///////////////////////////////////////////////////////////////////////////////
  856. #define INTERNAL_CATCH_TESTCASE2( TestName, ... ) \
  857. static void TestName(); \
  858. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
  859. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  860. namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &TestName ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
  861. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
  862. static void TestName()
  863. #define INTERNAL_CATCH_TESTCASE( ... ) \
  864. INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), __VA_ARGS__ )
  865. ///////////////////////////////////////////////////////////////////////////////
  866. #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \
  867. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
  868. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  869. namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &QualifiedMethod ), CATCH_INTERNAL_LINEINFO, "&" #QualifiedMethod, Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
  870. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
  871. ///////////////////////////////////////////////////////////////////////////////
  872. #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestName, ClassName, ... )\
  873. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
  874. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  875. namespace{ \
  876. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
  877. void test(); \
  878. }; \
  879. Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( Catch::makeTestInvoker( &TestName::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
  880. } \
  881. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
  882. void TestName::test()
  883. #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \
  884. INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, __VA_ARGS__ )
  885. ///////////////////////////////////////////////////////////////////////////////
  886. #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \
  887. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
  888. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  889. Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( Function ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
  890. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
  891. ///////////////////////////////////////////////////////////////////////////////
  892. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_2(TestName, TestFunc, Name, Tags, Signature, ... )\
  893. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
  894. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  895. CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
  896. CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
  897. INTERNAL_CATCH_DECLARE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
  898. namespace {\
  899. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\
  900. INTERNAL_CATCH_TYPE_GEN\
  901. INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
  902. INTERNAL_CATCH_NTTP_REG_GEN(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature))\
  903. template<typename...Types> \
  904. struct TestName{\
  905. TestName(){\
  906. int index = 0; \
  907. constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\
  908. using expander = int[];\
  909. (void)expander{(reg_test(Types{}, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++)... };/* NOLINT */ \
  910. }\
  911. };\
  912. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
  913. TestName<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\
  914. return 0;\
  915. }();\
  916. }\
  917. }\
  918. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
  919. INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature))
  920. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  921. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
  922. 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__ )
  923. #else
  924. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
  925. 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__ ) )
  926. #endif
  927. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  928. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \
  929. 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__ )
  930. #else
  931. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \
  932. 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__ ) )
  933. #endif
  934. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(TestName, TestFuncName, Name, Tags, Signature, TmplTypes, TypesList) \
  935. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
  936. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  937. CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
  938. CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
  939. template<typename TestType> static void TestFuncName(); \
  940. namespace {\
  941. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
  942. INTERNAL_CATCH_TYPE_GEN \
  943. INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature)) \
  944. template<typename... Types> \
  945. struct TestName { \
  946. void reg_tests() { \
  947. int index = 0; \
  948. using expander = int[]; \
  949. constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\
  950. constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\
  951. constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\
  952. (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 */\
  953. } \
  954. }; \
  955. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \
  956. 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; \
  957. TestInit t; \
  958. t.reg_tests(); \
  959. return 0; \
  960. }(); \
  961. } \
  962. } \
  963. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
  964. template<typename TestType> \
  965. static void TestFuncName()
  966. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  967. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\
  968. 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__)
  969. #else
  970. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\
  971. 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__ ) )
  972. #endif
  973. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  974. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\
  975. 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__)
  976. #else
  977. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\
  978. 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__ ) )
  979. #endif
  980. #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2(TestName, TestFunc, Name, Tags, TmplList)\
  981. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
  982. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  983. CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
  984. template<typename TestType> static void TestFunc(); \
  985. namespace {\
  986. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\
  987. INTERNAL_CATCH_TYPE_GEN\
  988. template<typename... Types> \
  989. struct TestName { \
  990. void reg_tests() { \
  991. int index = 0; \
  992. using expander = int[]; \
  993. (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 */\
  994. } \
  995. };\
  996. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \
  997. using TestInit = typename convert<TestName, TmplList>::type; \
  998. TestInit t; \
  999. t.reg_tests(); \
  1000. return 0; \
  1001. }(); \
  1002. }}\
  1003. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
  1004. template<typename TestType> \
  1005. static void TestFunc()
  1006. #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(Name, Tags, TmplList) \
  1007. 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 )
  1008. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... ) \
  1009. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
  1010. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  1011. CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
  1012. CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
  1013. namespace {\
  1014. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \
  1015. INTERNAL_CATCH_TYPE_GEN\
  1016. INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
  1017. INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
  1018. INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))\
  1019. template<typename...Types> \
  1020. struct TestNameClass{\
  1021. TestNameClass(){\
  1022. int index = 0; \
  1023. constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\
  1024. using expander = int[];\
  1025. (void)expander{(reg_test(Types{}, #ClassName, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++)... };/* NOLINT */ \
  1026. }\
  1027. };\
  1028. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
  1029. TestNameClass<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\
  1030. return 0;\
  1031. }();\
  1032. }\
  1033. }\
  1034. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
  1035. INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))
  1036. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  1037. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \
  1038. 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__ )
  1039. #else
  1040. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \
  1041. 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__ ) )
  1042. #endif
  1043. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  1044. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \
  1045. 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__ )
  1046. #else
  1047. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \
  1048. 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__ ) )
  1049. #endif
  1050. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2(TestNameClass, TestName, ClassName, Name, Tags, Signature, TmplTypes, TypesList)\
  1051. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
  1052. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  1053. CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
  1054. CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
  1055. template<typename TestType> \
  1056. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \
  1057. void test();\
  1058. };\
  1059. namespace {\
  1060. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestNameClass) {\
  1061. INTERNAL_CATCH_TYPE_GEN \
  1062. INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
  1063. template<typename...Types>\
  1064. struct TestNameClass{\
  1065. void reg_tests(){\
  1066. int index = 0;\
  1067. using expander = int[];\
  1068. constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\
  1069. constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\
  1070. constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\
  1071. (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 */ \
  1072. }\
  1073. };\
  1074. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
  1075. 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;\
  1076. TestInit t;\
  1077. t.reg_tests();\
  1078. return 0;\
  1079. }(); \
  1080. }\
  1081. }\
  1082. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
  1083. template<typename TestType> \
  1084. void TestName<TestType>::test()
  1085. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  1086. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\
  1087. 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__ )
  1088. #else
  1089. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\
  1090. 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__ ) )
  1091. #endif
  1092. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  1093. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\
  1094. 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__ )
  1095. #else
  1096. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\
  1097. 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__ ) )
  1098. #endif
  1099. #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, TmplList) \
  1100. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
  1101. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  1102. CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
  1103. template<typename TestType> \
  1104. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \
  1105. void test();\
  1106. };\
  1107. namespace {\
  1108. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \
  1109. INTERNAL_CATCH_TYPE_GEN\
  1110. template<typename...Types>\
  1111. struct TestNameClass{\
  1112. void reg_tests(){\
  1113. int index = 0;\
  1114. using expander = int[];\
  1115. (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 */ \
  1116. }\
  1117. };\
  1118. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
  1119. using TestInit = typename convert<TestNameClass, TmplList>::type;\
  1120. TestInit t;\
  1121. t.reg_tests();\
  1122. return 0;\
  1123. }(); \
  1124. }}\
  1125. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
  1126. template<typename TestType> \
  1127. void TestName<TestType>::test()
  1128. #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD(ClassName, Name, Tags, TmplList) \
  1129. 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 )
  1130. // end catch_test_registry.h
  1131. // start catch_capture.hpp
  1132. // start catch_assertionhandler.h
  1133. // start catch_assertioninfo.h
  1134. // start catch_result_type.h
  1135. namespace Catch {
  1136. // ResultWas::OfType enum
  1137. struct ResultWas { enum OfType {
  1138. Unknown = -1,
  1139. Ok = 0,
  1140. Info = 1,
  1141. Warning = 2,
  1142. FailureBit = 0x10,
  1143. ExpressionFailed = FailureBit | 1,
  1144. ExplicitFailure = FailureBit | 2,
  1145. Exception = 0x100 | FailureBit,
  1146. ThrewException = Exception | 1,
  1147. DidntThrowException = Exception | 2,
  1148. FatalErrorCondition = 0x200 | FailureBit
  1149. }; };
  1150. bool isOk( ResultWas::OfType resultType );
  1151. bool isJustInfo( int flags );
  1152. // ResultDisposition::Flags enum
  1153. struct ResultDisposition { enum Flags {
  1154. Normal = 0x01,
  1155. ContinueOnFailure = 0x02, // Failures fail test, but execution continues
  1156. FalseTest = 0x04, // Prefix expression with !
  1157. SuppressFail = 0x08 // Failures are reported but do not fail the test
  1158. }; };
  1159. ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs );
  1160. bool shouldContinueOnFailure( int flags );
  1161. inline bool isFalseTest( int flags ) { return ( flags & ResultDisposition::FalseTest ) != 0; }
  1162. bool shouldSuppressFailure( int flags );
  1163. } // end namespace Catch
  1164. // end catch_result_type.h
  1165. namespace Catch {
  1166. struct AssertionInfo
  1167. {
  1168. StringRef macroName;
  1169. SourceLineInfo lineInfo;
  1170. StringRef capturedExpression;
  1171. ResultDisposition::Flags resultDisposition;
  1172. // We want to delete this constructor but a compiler bug in 4.8 means
  1173. // the struct is then treated as non-aggregate
  1174. //AssertionInfo() = delete;
  1175. };
  1176. } // end namespace Catch
  1177. // end catch_assertioninfo.h
  1178. // start catch_decomposer.h
  1179. // start catch_tostring.h
  1180. #include <vector>
  1181. #include <cstddef>
  1182. #include <type_traits>
  1183. #include <string>
  1184. // start catch_stream.h
  1185. #include <iosfwd>
  1186. #include <cstddef>
  1187. #include <ostream>
  1188. namespace Catch {
  1189. std::ostream& cout();
  1190. std::ostream& cerr();
  1191. std::ostream& clog();
  1192. class StringRef;
  1193. struct IStream {
  1194. virtual ~IStream();
  1195. virtual std::ostream& stream() const = 0;
  1196. };
  1197. auto makeStream( StringRef const &filename ) -> IStream const*;
  1198. class ReusableStringStream : NonCopyable {
  1199. std::size_t m_index;
  1200. std::ostream* m_oss;
  1201. public:
  1202. ReusableStringStream();
  1203. ~ReusableStringStream();
  1204. auto str() const -> std::string;
  1205. template<typename T>
  1206. auto operator << ( T const& value ) -> ReusableStringStream& {
  1207. *m_oss << value;
  1208. return *this;
  1209. }
  1210. auto get() -> std::ostream& { return *m_oss; }
  1211. };
  1212. }
  1213. // end catch_stream.h
  1214. // start catch_interfaces_enum_values_registry.h
  1215. #include <vector>
  1216. namespace Catch {
  1217. namespace Detail {
  1218. struct EnumInfo {
  1219. StringRef m_name;
  1220. std::vector<std::pair<int, StringRef>> m_values;
  1221. ~EnumInfo();
  1222. StringRef lookup( int value ) const;
  1223. };
  1224. } // namespace Detail
  1225. struct IMutableEnumValuesRegistry {
  1226. virtual ~IMutableEnumValuesRegistry();
  1227. virtual Detail::EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::vector<int> const& values ) = 0;
  1228. template<typename E>
  1229. Detail::EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::initializer_list<E> values ) {
  1230. static_assert(sizeof(int) >= sizeof(E), "Cannot serialize enum to int");
  1231. std::vector<int> intValues;
  1232. intValues.reserve( values.size() );
  1233. for( auto enumValue : values )
  1234. intValues.push_back( static_cast<int>( enumValue ) );
  1235. return registerEnum( enumName, allEnums, intValues );
  1236. }
  1237. };
  1238. } // Catch
  1239. // end catch_interfaces_enum_values_registry.h
  1240. #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  1241. #include <string_view>
  1242. #endif
  1243. #ifdef __OBJC__
  1244. // start catch_objc_arc.hpp
  1245. #import <Foundation/Foundation.h>
  1246. #ifdef __has_feature
  1247. #define CATCH_ARC_ENABLED __has_feature(objc_arc)
  1248. #else
  1249. #define CATCH_ARC_ENABLED 0
  1250. #endif
  1251. void arcSafeRelease( NSObject* obj );
  1252. id performOptionalSelector( id obj, SEL sel );
  1253. #if !CATCH_ARC_ENABLED
  1254. inline void arcSafeRelease( NSObject* obj ) {
  1255. [obj release];
  1256. }
  1257. inline id performOptionalSelector( id obj, SEL sel ) {
  1258. if( [obj respondsToSelector: sel] )
  1259. return [obj performSelector: sel];
  1260. return nil;
  1261. }
  1262. #define CATCH_UNSAFE_UNRETAINED
  1263. #define CATCH_ARC_STRONG
  1264. #else
  1265. inline void arcSafeRelease( NSObject* ){}
  1266. inline id performOptionalSelector( id obj, SEL sel ) {
  1267. #ifdef __clang__
  1268. #pragma clang diagnostic push
  1269. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  1270. #endif
  1271. if( [obj respondsToSelector: sel] )
  1272. return [obj performSelector: sel];
  1273. #ifdef __clang__
  1274. #pragma clang diagnostic pop
  1275. #endif
  1276. return nil;
  1277. }
  1278. #define CATCH_UNSAFE_UNRETAINED __unsafe_unretained
  1279. #define CATCH_ARC_STRONG __strong
  1280. #endif
  1281. // end catch_objc_arc.hpp
  1282. #endif
  1283. #ifdef _MSC_VER
  1284. #pragma warning(push)
  1285. #pragma warning(disable:4180) // We attempt to stream a function (address) by const&, which MSVC complains about but is harmless
  1286. #endif
  1287. namespace Catch {
  1288. namespace Detail {
  1289. extern const std::string unprintableString;
  1290. std::string rawMemoryToString( const void *object, std::size_t size );
  1291. template<typename T>
  1292. std::string rawMemoryToString( const T& object ) {
  1293. return rawMemoryToString( &object, sizeof(object) );
  1294. }
  1295. template<typename T>
  1296. class IsStreamInsertable {
  1297. template<typename Stream, typename U>
  1298. static auto test(int)
  1299. -> decltype(std::declval<Stream&>() << std::declval<U>(), std::true_type());
  1300. template<typename, typename>
  1301. static auto test(...)->std::false_type;
  1302. public:
  1303. static const bool value = decltype(test<std::ostream, const T&>(0))::value;
  1304. };
  1305. template<typename E>
  1306. std::string convertUnknownEnumToString( E e );
  1307. template<typename T>
  1308. typename std::enable_if<
  1309. !std::is_enum<T>::value && !std::is_base_of<std::exception, T>::value,
  1310. std::string>::type convertUnstreamable( T const& ) {
  1311. return Detail::unprintableString;
  1312. }
  1313. template<typename T>
  1314. typename std::enable_if<
  1315. !std::is_enum<T>::value && std::is_base_of<std::exception, T>::value,
  1316. std::string>::type convertUnstreamable(T const& ex) {
  1317. return ex.what();
  1318. }
  1319. template<typename T>
  1320. typename std::enable_if<
  1321. std::is_enum<T>::value
  1322. , std::string>::type convertUnstreamable( T const& value ) {
  1323. return convertUnknownEnumToString( value );
  1324. }
  1325. #if defined(_MANAGED)
  1326. //! Convert a CLR string to a utf8 std::string
  1327. template<typename T>
  1328. std::string clrReferenceToString( T^ ref ) {
  1329. if (ref == nullptr)
  1330. return std::string("null");
  1331. auto bytes = System::Text::Encoding::UTF8->GetBytes(ref->ToString());
  1332. cli::pin_ptr<System::Byte> p = &bytes[0];
  1333. return std::string(reinterpret_cast<char const *>(p), bytes->Length);
  1334. }
  1335. #endif
  1336. } // namespace Detail
  1337. // If we decide for C++14, change these to enable_if_ts
  1338. template <typename T, typename = void>
  1339. struct StringMaker {
  1340. template <typename Fake = T>
  1341. static
  1342. typename std::enable_if<::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
  1343. convert(const Fake& value) {
  1344. ReusableStringStream rss;
  1345. // NB: call using the function-like syntax to avoid ambiguity with
  1346. // user-defined templated operator<< under clang.
  1347. rss.operator<<(value);
  1348. return rss.str();
  1349. }
  1350. template <typename Fake = T>
  1351. static
  1352. typename std::enable_if<!::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
  1353. convert( const Fake& value ) {
  1354. #if !defined(CATCH_CONFIG_FALLBACK_STRINGIFIER)
  1355. return Detail::convertUnstreamable(value);
  1356. #else
  1357. return CATCH_CONFIG_FALLBACK_STRINGIFIER(value);
  1358. #endif
  1359. }
  1360. };
  1361. namespace Detail {
  1362. // This function dispatches all stringification requests inside of Catch.
  1363. // Should be preferably called fully qualified, like ::Catch::Detail::stringify
  1364. template <typename T>
  1365. std::string stringify(const T& e) {
  1366. return ::Catch::StringMaker<typename std::remove_cv<typename std::remove_reference<T>::type>::type>::convert(e);
  1367. }
  1368. template<typename E>
  1369. std::string convertUnknownEnumToString( E e ) {
  1370. return ::Catch::Detail::stringify(static_cast<typename std::underlying_type<E>::type>(e));
  1371. }
  1372. #if defined(_MANAGED)
  1373. template <typename T>
  1374. std::string stringify( T^ e ) {
  1375. return ::Catch::StringMaker<T^>::convert(e);
  1376. }
  1377. #endif
  1378. } // namespace Detail
  1379. // Some predefined specializations
  1380. template<>
  1381. struct StringMaker<std::string> {
  1382. static std::string convert(const std::string& str);
  1383. };
  1384. #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  1385. template<>
  1386. struct StringMaker<std::string_view> {
  1387. static std::string convert(std::string_view str);
  1388. };
  1389. #endif
  1390. template<>
  1391. struct StringMaker<char const *> {
  1392. static std::string convert(char const * str);
  1393. };
  1394. template<>
  1395. struct StringMaker<char *> {
  1396. static std::string convert(char * str);
  1397. };
  1398. #ifdef CATCH_CONFIG_WCHAR
  1399. template<>
  1400. struct StringMaker<std::wstring> {
  1401. static std::string convert(const std::wstring& wstr);
  1402. };
  1403. # ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  1404. template<>
  1405. struct StringMaker<std::wstring_view> {
  1406. static std::string convert(std::wstring_view str);
  1407. };
  1408. # endif
  1409. template<>
  1410. struct StringMaker<wchar_t const *> {
  1411. static std::string convert(wchar_t const * str);
  1412. };
  1413. template<>
  1414. struct StringMaker<wchar_t *> {
  1415. static std::string convert(wchar_t * str);
  1416. };
  1417. #endif
  1418. // TBD: Should we use `strnlen` to ensure that we don't go out of the buffer,
  1419. // while keeping string semantics?
  1420. template<int SZ>
  1421. struct StringMaker<char[SZ]> {
  1422. static std::string convert(char const* str) {
  1423. return ::Catch::Detail::stringify(std::string{ str });
  1424. }
  1425. };
  1426. template<int SZ>
  1427. struct StringMaker<signed char[SZ]> {
  1428. static std::string convert(signed char const* str) {
  1429. return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) });
  1430. }
  1431. };
  1432. template<int SZ>
  1433. struct StringMaker<unsigned char[SZ]> {
  1434. static std::string convert(unsigned char const* str) {
  1435. return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) });
  1436. }
  1437. };
  1438. #if defined(CATCH_CONFIG_CPP17_BYTE)
  1439. template<>
  1440. struct StringMaker<std::byte> {
  1441. static std::string convert(std::byte value);
  1442. };
  1443. #endif // defined(CATCH_CONFIG_CPP17_BYTE)
  1444. template<>
  1445. struct StringMaker<int> {
  1446. static std::string convert(int value);
  1447. };
  1448. template<>
  1449. struct StringMaker<long> {
  1450. static std::string convert(long value);
  1451. };
  1452. template<>
  1453. struct StringMaker<long long> {
  1454. static std::string convert(long long value);
  1455. };
  1456. template<>
  1457. struct StringMaker<unsigned int> {
  1458. static std::string convert(unsigned int value);
  1459. };
  1460. template<>
  1461. struct StringMaker<unsigned long> {
  1462. static std::string convert(unsigned long value);
  1463. };
  1464. template<>
  1465. struct StringMaker<unsigned long long> {
  1466. static std::string convert(unsigned long long value);
  1467. };
  1468. template<>
  1469. struct StringMaker<bool> {
  1470. static std::string convert(bool b);
  1471. };
  1472. template<>
  1473. struct StringMaker<char> {
  1474. static std::string convert(char c);
  1475. };
  1476. template<>
  1477. struct StringMaker<signed char> {
  1478. static std::string convert(signed char c);
  1479. };
  1480. template<>
  1481. struct StringMaker<unsigned char> {
  1482. static std::string convert(unsigned char c);
  1483. };
  1484. template<>
  1485. struct StringMaker<std::nullptr_t> {
  1486. static std::string convert(std::nullptr_t);
  1487. };
  1488. template<>
  1489. struct StringMaker<float> {
  1490. static std::string convert(float value);
  1491. static int precision;
  1492. };
  1493. template<>
  1494. struct StringMaker<double> {
  1495. static std::string convert(double value);
  1496. static int precision;
  1497. };
  1498. template <typename T>
  1499. struct StringMaker<T*> {
  1500. template <typename U>
  1501. static std::string convert(U* p) {
  1502. if (p) {
  1503. return ::Catch::Detail::rawMemoryToString(p);
  1504. } else {
  1505. return "nullptr";
  1506. }
  1507. }
  1508. };
  1509. template <typename R, typename C>
  1510. struct StringMaker<R C::*> {
  1511. static std::string convert(R C::* p) {
  1512. if (p) {
  1513. return ::Catch::Detail::rawMemoryToString(p);
  1514. } else {
  1515. return "nullptr";
  1516. }
  1517. }
  1518. };
  1519. #if defined(_MANAGED)
  1520. template <typename T>
  1521. struct StringMaker<T^> {
  1522. static std::string convert( T^ ref ) {
  1523. return ::Catch::Detail::clrReferenceToString(ref);
  1524. }
  1525. };
  1526. #endif
  1527. namespace Detail {
  1528. template<typename InputIterator, typename Sentinel = InputIterator>
  1529. std::string rangeToString(InputIterator first, Sentinel last) {
  1530. ReusableStringStream rss;
  1531. rss << "{ ";
  1532. if (first != last) {
  1533. rss << ::Catch::Detail::stringify(*first);
  1534. for (++first; first != last; ++first)
  1535. rss << ", " << ::Catch::Detail::stringify(*first);
  1536. }
  1537. rss << " }";
  1538. return rss.str();
  1539. }
  1540. }
  1541. #ifdef __OBJC__
  1542. template<>
  1543. struct StringMaker<NSString*> {
  1544. static std::string convert(NSString * nsstring) {
  1545. if (!nsstring)
  1546. return "nil";
  1547. return std::string("@") + [nsstring UTF8String];
  1548. }
  1549. };
  1550. template<>
  1551. struct StringMaker<NSObject*> {
  1552. static std::string convert(NSObject* nsObject) {
  1553. return ::Catch::Detail::stringify([nsObject description]);
  1554. }
  1555. };
  1556. namespace Detail {
  1557. inline std::string stringify( NSString* nsstring ) {
  1558. return StringMaker<NSString*>::convert( nsstring );
  1559. }
  1560. } // namespace Detail
  1561. #endif // __OBJC__
  1562. } // namespace Catch
  1563. //////////////////////////////////////////////////////
  1564. // Separate std-lib types stringification, so it can be selectively enabled
  1565. // This means that we do not bring in
  1566. #if defined(CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS)
  1567. # define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
  1568. # define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
  1569. # define CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
  1570. # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  1571. # define CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
  1572. #endif
  1573. // Separate std::pair specialization
  1574. #if defined(CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER)
  1575. #include <utility>
  1576. namespace Catch {
  1577. template<typename T1, typename T2>
  1578. struct StringMaker<std::pair<T1, T2> > {
  1579. static std::string convert(const std::pair<T1, T2>& pair) {
  1580. ReusableStringStream rss;
  1581. rss << "{ "
  1582. << ::Catch::Detail::stringify(pair.first)
  1583. << ", "
  1584. << ::Catch::Detail::stringify(pair.second)
  1585. << " }";
  1586. return rss.str();
  1587. }
  1588. };
  1589. }
  1590. #endif // CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
  1591. #if defined(CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_OPTIONAL)
  1592. #include <optional>
  1593. namespace Catch {
  1594. template<typename T>
  1595. struct StringMaker<std::optional<T> > {
  1596. static std::string convert(const std::optional<T>& optional) {
  1597. ReusableStringStream rss;
  1598. if (optional.has_value()) {
  1599. rss << ::Catch::Detail::stringify(*optional);
  1600. } else {
  1601. rss << "{ }";
  1602. }
  1603. return rss.str();
  1604. }
  1605. };
  1606. }
  1607. #endif // CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
  1608. // Separate std::tuple specialization
  1609. #if defined(CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER)
  1610. #include <tuple>
  1611. namespace Catch {
  1612. namespace Detail {
  1613. template<
  1614. typename Tuple,
  1615. std::size_t N = 0,
  1616. bool = (N < std::tuple_size<Tuple>::value)
  1617. >
  1618. struct TupleElementPrinter {
  1619. static void print(const Tuple& tuple, std::ostream& os) {
  1620. os << (N ? ", " : " ")
  1621. << ::Catch::Detail::stringify(std::get<N>(tuple));
  1622. TupleElementPrinter<Tuple, N + 1>::print(tuple, os);
  1623. }
  1624. };
  1625. template<
  1626. typename Tuple,
  1627. std::size_t N
  1628. >
  1629. struct TupleElementPrinter<Tuple, N, false> {
  1630. static void print(const Tuple&, std::ostream&) {}
  1631. };
  1632. }
  1633. template<typename ...Types>
  1634. struct StringMaker<std::tuple<Types...>> {
  1635. static std::string convert(const std::tuple<Types...>& tuple) {
  1636. ReusableStringStream rss;
  1637. rss << '{';
  1638. Detail::TupleElementPrinter<std::tuple<Types...>>::print(tuple, rss.get());
  1639. rss << " }";
  1640. return rss.str();
  1641. }
  1642. };
  1643. }
  1644. #endif // CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
  1645. #if defined(CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_VARIANT)
  1646. #include <variant>
  1647. namespace Catch {
  1648. template<>
  1649. struct StringMaker<std::monostate> {
  1650. static std::string convert(const std::monostate&) {
  1651. return "{ }";
  1652. }
  1653. };
  1654. template<typename... Elements>
  1655. struct StringMaker<std::variant<Elements...>> {
  1656. static std::string convert(const std::variant<Elements...>& variant) {
  1657. if (variant.valueless_by_exception()) {
  1658. return "{valueless variant}";
  1659. } else {
  1660. return std::visit(
  1661. [](const auto& value) {
  1662. return ::Catch::Detail::stringify(value);
  1663. },
  1664. variant
  1665. );
  1666. }
  1667. }
  1668. };
  1669. }
  1670. #endif // CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
  1671. namespace Catch {
  1672. // Import begin/ end from std here
  1673. using std::begin;
  1674. using std::end;
  1675. namespace detail {
  1676. template <typename...>
  1677. struct void_type {
  1678. using type = void;
  1679. };
  1680. template <typename T, typename = void>
  1681. struct is_range_impl : std::false_type {
  1682. };
  1683. template <typename T>
  1684. struct is_range_impl<T, typename void_type<decltype(begin(std::declval<T>()))>::type> : std::true_type {
  1685. };
  1686. } // namespace detail
  1687. template <typename T>
  1688. struct is_range : detail::is_range_impl<T> {
  1689. };
  1690. #if defined(_MANAGED) // Managed types are never ranges
  1691. template <typename T>
  1692. struct is_range<T^> {
  1693. static const bool value = false;
  1694. };
  1695. #endif
  1696. template<typename Range>
  1697. std::string rangeToString( Range const& range ) {
  1698. return ::Catch::Detail::rangeToString( begin( range ), end( range ) );
  1699. }
  1700. // Handle vector<bool> specially
  1701. template<typename Allocator>
  1702. std::string rangeToString( std::vector<bool, Allocator> const& v ) {
  1703. ReusableStringStream rss;
  1704. rss << "{ ";
  1705. bool first = true;
  1706. for( bool b : v ) {
  1707. if( first )
  1708. first = false;
  1709. else
  1710. rss << ", ";
  1711. rss << ::Catch::Detail::stringify( b );
  1712. }
  1713. rss << " }";
  1714. return rss.str();
  1715. }
  1716. template<typename R>
  1717. struct StringMaker<R, typename std::enable_if<is_range<R>::value && !::Catch::Detail::IsStreamInsertable<R>::value>::type> {
  1718. static std::string convert( R const& range ) {
  1719. return rangeToString( range );
  1720. }
  1721. };
  1722. template <typename T, int SZ>
  1723. struct StringMaker<T[SZ]> {
  1724. static std::string convert(T const(&arr)[SZ]) {
  1725. return rangeToString(arr);
  1726. }
  1727. };
  1728. } // namespace Catch
  1729. // Separate std::chrono::duration specialization
  1730. #if defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  1731. #include <ctime>
  1732. #include <ratio>
  1733. #include <chrono>
  1734. namespace Catch {
  1735. template <class Ratio>
  1736. struct ratio_string {
  1737. static std::string symbol();
  1738. };
  1739. template <class Ratio>
  1740. std::string ratio_string<Ratio>::symbol() {
  1741. Catch::ReusableStringStream rss;
  1742. rss << '[' << Ratio::num << '/'
  1743. << Ratio::den << ']';
  1744. return rss.str();
  1745. }
  1746. template <>
  1747. struct ratio_string<std::atto> {
  1748. static std::string symbol();
  1749. };
  1750. template <>
  1751. struct ratio_string<std::femto> {
  1752. static std::string symbol();
  1753. };
  1754. template <>
  1755. struct ratio_string<std::pico> {
  1756. static std::string symbol();
  1757. };
  1758. template <>
  1759. struct ratio_string<std::nano> {
  1760. static std::string symbol();
  1761. };
  1762. template <>
  1763. struct ratio_string<std::micro> {
  1764. static std::string symbol();
  1765. };
  1766. template <>
  1767. struct ratio_string<std::milli> {
  1768. static std::string symbol();
  1769. };
  1770. ////////////
  1771. // std::chrono::duration specializations
  1772. template<typename Value, typename Ratio>
  1773. struct StringMaker<std::chrono::duration<Value, Ratio>> {
  1774. static std::string convert(std::chrono::duration<Value, Ratio> const& duration) {
  1775. ReusableStringStream rss;
  1776. rss << duration.count() << ' ' << ratio_string<Ratio>::symbol() << 's';
  1777. return rss.str();
  1778. }
  1779. };
  1780. template<typename Value>
  1781. struct StringMaker<std::chrono::duration<Value, std::ratio<1>>> {
  1782. static std::string convert(std::chrono::duration<Value, std::ratio<1>> const& duration) {
  1783. ReusableStringStream rss;
  1784. rss << duration.count() << " s";
  1785. return rss.str();
  1786. }
  1787. };
  1788. template<typename Value>
  1789. struct StringMaker<std::chrono::duration<Value, std::ratio<60>>> {
  1790. static std::string convert(std::chrono::duration<Value, std::ratio<60>> const& duration) {
  1791. ReusableStringStream rss;
  1792. rss << duration.count() << " m";
  1793. return rss.str();
  1794. }
  1795. };
  1796. template<typename Value>
  1797. struct StringMaker<std::chrono::duration<Value, std::ratio<3600>>> {
  1798. static std::string convert(std::chrono::duration<Value, std::ratio<3600>> const& duration) {
  1799. ReusableStringStream rss;
  1800. rss << duration.count() << " h";
  1801. return rss.str();
  1802. }
  1803. };
  1804. ////////////
  1805. // std::chrono::time_point specialization
  1806. // Generic time_point cannot be specialized, only std::chrono::time_point<system_clock>
  1807. template<typename Clock, typename Duration>
  1808. struct StringMaker<std::chrono::time_point<Clock, Duration>> {
  1809. static std::string convert(std::chrono::time_point<Clock, Duration> const& time_point) {
  1810. return ::Catch::Detail::stringify(time_point.time_since_epoch()) + " since epoch";
  1811. }
  1812. };
  1813. // std::chrono::time_point<system_clock> specialization
  1814. template<typename Duration>
  1815. struct StringMaker<std::chrono::time_point<std::chrono::system_clock, Duration>> {
  1816. static std::string convert(std::chrono::time_point<std::chrono::system_clock, Duration> const& time_point) {
  1817. auto converted = std::chrono::system_clock::to_time_t(time_point);
  1818. #ifdef _MSC_VER
  1819. std::tm timeInfo = {};
  1820. gmtime_s(&timeInfo, &converted);
  1821. #else
  1822. std::tm* timeInfo = std::gmtime(&converted);
  1823. #endif
  1824. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  1825. char timeStamp[timeStampSize];
  1826. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  1827. #ifdef _MSC_VER
  1828. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  1829. #else
  1830. std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
  1831. #endif
  1832. return std::string(timeStamp);
  1833. }
  1834. };
  1835. }
  1836. #endif // CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  1837. #define INTERNAL_CATCH_REGISTER_ENUM( enumName, ... ) \
  1838. namespace Catch { \
  1839. template<> struct StringMaker<enumName> { \
  1840. static std::string convert( enumName value ) { \
  1841. static const auto& enumInfo = ::Catch::getMutableRegistryHub().getMutableEnumValuesRegistry().registerEnum( #enumName, #__VA_ARGS__, { __VA_ARGS__ } ); \
  1842. return static_cast<std::string>(enumInfo.lookup( static_cast<int>( value ) )); \
  1843. } \
  1844. }; \
  1845. }
  1846. #define CATCH_REGISTER_ENUM( enumName, ... ) INTERNAL_CATCH_REGISTER_ENUM( enumName, __VA_ARGS__ )
  1847. #ifdef _MSC_VER
  1848. #pragma warning(pop)
  1849. #endif
  1850. // end catch_tostring.h
  1851. #include <iosfwd>
  1852. #ifdef _MSC_VER
  1853. #pragma warning(push)
  1854. #pragma warning(disable:4389) // '==' : signed/unsigned mismatch
  1855. #pragma warning(disable:4018) // more "signed/unsigned mismatch"
  1856. #pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform)
  1857. #pragma warning(disable:4180) // qualifier applied to function type has no meaning
  1858. #pragma warning(disable:4800) // Forcing result to true or false
  1859. #endif
  1860. namespace Catch {
  1861. struct ITransientExpression {
  1862. auto isBinaryExpression() const -> bool { return m_isBinaryExpression; }
  1863. auto getResult() const -> bool { return m_result; }
  1864. virtual void streamReconstructedExpression( std::ostream &os ) const = 0;
  1865. ITransientExpression( bool isBinaryExpression, bool result )
  1866. : m_isBinaryExpression( isBinaryExpression ),
  1867. m_result( result )
  1868. {}
  1869. // We don't actually need a virtual destructor, but many static analysers
  1870. // complain if it's not here :-(
  1871. virtual ~ITransientExpression();
  1872. bool m_isBinaryExpression;
  1873. bool m_result;
  1874. };
  1875. void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs );
  1876. template<typename LhsT, typename RhsT>
  1877. class BinaryExpr : public ITransientExpression {
  1878. LhsT m_lhs;
  1879. StringRef m_op;
  1880. RhsT m_rhs;
  1881. void streamReconstructedExpression( std::ostream &os ) const override {
  1882. formatReconstructedExpression
  1883. ( os, Catch::Detail::stringify( m_lhs ), m_op, Catch::Detail::stringify( m_rhs ) );
  1884. }
  1885. public:
  1886. BinaryExpr( bool comparisonResult, LhsT lhs, StringRef op, RhsT rhs )
  1887. : ITransientExpression{ true, comparisonResult },
  1888. m_lhs( lhs ),
  1889. m_op( op ),
  1890. m_rhs( rhs )
  1891. {}
  1892. template<typename T>
  1893. auto operator && ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1894. static_assert(always_false<T>::value,
  1895. "chained comparisons are not supported inside assertions, "
  1896. "wrap the expression inside parentheses, or decompose it");
  1897. }
  1898. template<typename T>
  1899. auto operator || ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1900. static_assert(always_false<T>::value,
  1901. "chained comparisons are not supported inside assertions, "
  1902. "wrap the expression inside parentheses, or decompose it");
  1903. }
  1904. template<typename T>
  1905. auto operator == ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1906. static_assert(always_false<T>::value,
  1907. "chained comparisons are not supported inside assertions, "
  1908. "wrap the expression inside parentheses, or decompose it");
  1909. }
  1910. template<typename T>
  1911. auto operator != ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1912. static_assert(always_false<T>::value,
  1913. "chained comparisons are not supported inside assertions, "
  1914. "wrap the expression inside parentheses, or decompose it");
  1915. }
  1916. template<typename T>
  1917. auto operator > ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1918. static_assert(always_false<T>::value,
  1919. "chained comparisons are not supported inside assertions, "
  1920. "wrap the expression inside parentheses, or decompose it");
  1921. }
  1922. template<typename T>
  1923. auto operator < ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1924. static_assert(always_false<T>::value,
  1925. "chained comparisons are not supported inside assertions, "
  1926. "wrap the expression inside parentheses, or decompose it");
  1927. }
  1928. template<typename T>
  1929. auto operator >= ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1930. static_assert(always_false<T>::value,
  1931. "chained comparisons are not supported inside assertions, "
  1932. "wrap the expression inside parentheses, or decompose it");
  1933. }
  1934. template<typename T>
  1935. auto operator <= ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1936. static_assert(always_false<T>::value,
  1937. "chained comparisons are not supported inside assertions, "
  1938. "wrap the expression inside parentheses, or decompose it");
  1939. }
  1940. };
  1941. template<typename LhsT>
  1942. class UnaryExpr : public ITransientExpression {
  1943. LhsT m_lhs;
  1944. void streamReconstructedExpression( std::ostream &os ) const override {
  1945. os << Catch::Detail::stringify( m_lhs );
  1946. }
  1947. public:
  1948. explicit UnaryExpr( LhsT lhs )
  1949. : ITransientExpression{ false, static_cast<bool>(lhs) },
  1950. m_lhs( lhs )
  1951. {}
  1952. };
  1953. // Specialised comparison functions to handle equality comparisons between ints and pointers (NULL deduces as an int)
  1954. template<typename LhsT, typename RhsT>
  1955. auto compareEqual( LhsT const& lhs, RhsT const& rhs ) -> bool { return static_cast<bool>(lhs == rhs); }
  1956. template<typename T>
  1957. auto compareEqual( T* const& lhs, int rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
  1958. template<typename T>
  1959. auto compareEqual( T* const& lhs, long rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
  1960. template<typename T>
  1961. auto compareEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
  1962. template<typename T>
  1963. auto compareEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
  1964. template<typename LhsT, typename RhsT>
  1965. auto compareNotEqual( LhsT const& lhs, RhsT&& rhs ) -> bool { return static_cast<bool>(lhs != rhs); }
  1966. template<typename T>
  1967. auto compareNotEqual( T* const& lhs, int rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
  1968. template<typename T>
  1969. auto compareNotEqual( T* const& lhs, long rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
  1970. template<typename T>
  1971. auto compareNotEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
  1972. template<typename T>
  1973. auto compareNotEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
  1974. template<typename LhsT>
  1975. class ExprLhs {
  1976. LhsT m_lhs;
  1977. public:
  1978. explicit ExprLhs( LhsT lhs ) : m_lhs( lhs ) {}
  1979. template<typename RhsT>
  1980. auto operator == ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1981. return { compareEqual( m_lhs, rhs ), m_lhs, "==", rhs };
  1982. }
  1983. auto operator == ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
  1984. return { m_lhs == rhs, m_lhs, "==", rhs };
  1985. }
  1986. template<typename RhsT>
  1987. auto operator != ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1988. return { compareNotEqual( m_lhs, rhs ), m_lhs, "!=", rhs };
  1989. }
  1990. auto operator != ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
  1991. return { m_lhs != rhs, m_lhs, "!=", rhs };
  1992. }
  1993. template<typename RhsT>
  1994. auto operator > ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1995. return { static_cast<bool>(m_lhs > rhs), m_lhs, ">", rhs };
  1996. }
  1997. template<typename RhsT>
  1998. auto operator < ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1999. return { static_cast<bool>(m_lhs < rhs), m_lhs, "<", rhs };
  2000. }
  2001. template<typename RhsT>
  2002. auto operator >= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  2003. return { static_cast<bool>(m_lhs >= rhs), m_lhs, ">=", rhs };
  2004. }
  2005. template<typename RhsT>
  2006. auto operator <= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  2007. return { static_cast<bool>(m_lhs <= rhs), m_lhs, "<=", rhs };
  2008. }
  2009. template <typename RhsT>
  2010. auto operator | (RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const {
  2011. return { static_cast<bool>(m_lhs | rhs), m_lhs, "|", rhs };
  2012. }
  2013. template <typename RhsT>
  2014. auto operator & (RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const {
  2015. return { static_cast<bool>(m_lhs & rhs), m_lhs, "&", rhs };
  2016. }
  2017. template <typename RhsT>
  2018. auto operator ^ (RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const {
  2019. return { static_cast<bool>(m_lhs ^ rhs), m_lhs, "^", rhs };
  2020. }
  2021. template<typename RhsT>
  2022. auto operator && ( RhsT const& ) -> BinaryExpr<LhsT, RhsT const&> const {
  2023. static_assert(always_false<RhsT>::value,
  2024. "operator&& is not supported inside assertions, "
  2025. "wrap the expression inside parentheses, or decompose it");
  2026. }
  2027. template<typename RhsT>
  2028. auto operator || ( RhsT const& ) -> BinaryExpr<LhsT, RhsT const&> const {
  2029. static_assert(always_false<RhsT>::value,
  2030. "operator|| is not supported inside assertions, "
  2031. "wrap the expression inside parentheses, or decompose it");
  2032. }
  2033. auto makeUnaryExpr() const -> UnaryExpr<LhsT> {
  2034. return UnaryExpr<LhsT>{ m_lhs };
  2035. }
  2036. };
  2037. void handleExpression( ITransientExpression const& expr );
  2038. template<typename T>
  2039. void handleExpression( ExprLhs<T> const& expr ) {
  2040. handleExpression( expr.makeUnaryExpr() );
  2041. }
  2042. struct Decomposer {
  2043. template<typename T>
  2044. auto operator <= ( T const& lhs ) -> ExprLhs<T const&> {
  2045. return ExprLhs<T const&>{ lhs };
  2046. }
  2047. auto operator <=( bool value ) -> ExprLhs<bool> {
  2048. return ExprLhs<bool>{ value };
  2049. }
  2050. };
  2051. } // end namespace Catch
  2052. #ifdef _MSC_VER
  2053. #pragma warning(pop)
  2054. #endif
  2055. // end catch_decomposer.h
  2056. // start catch_interfaces_capture.h
  2057. #include <string>
  2058. #include <chrono>
  2059. namespace Catch {
  2060. class AssertionResult;
  2061. struct AssertionInfo;
  2062. struct SectionInfo;
  2063. struct SectionEndInfo;
  2064. struct MessageInfo;
  2065. struct MessageBuilder;
  2066. struct Counts;
  2067. struct AssertionReaction;
  2068. struct SourceLineInfo;
  2069. struct ITransientExpression;
  2070. struct IGeneratorTracker;
  2071. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  2072. struct BenchmarkInfo;
  2073. template <typename Duration = std::chrono::duration<double, std::nano>>
  2074. struct BenchmarkStats;
  2075. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  2076. struct IResultCapture {
  2077. virtual ~IResultCapture();
  2078. virtual bool sectionStarted( SectionInfo const& sectionInfo,
  2079. Counts& assertions ) = 0;
  2080. virtual void sectionEnded( SectionEndInfo const& endInfo ) = 0;
  2081. virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) = 0;
  2082. virtual auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker& = 0;
  2083. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  2084. virtual void benchmarkPreparing( std::string const& name ) = 0;
  2085. virtual void benchmarkStarting( BenchmarkInfo const& info ) = 0;
  2086. virtual void benchmarkEnded( BenchmarkStats<> const& stats ) = 0;
  2087. virtual void benchmarkFailed( std::string const& error ) = 0;
  2088. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  2089. virtual void pushScopedMessage( MessageInfo const& message ) = 0;
  2090. virtual void popScopedMessage( MessageInfo const& message ) = 0;
  2091. virtual void emplaceUnscopedMessage( MessageBuilder const& builder ) = 0;
  2092. virtual void handleFatalErrorCondition( StringRef message ) = 0;
  2093. virtual void handleExpr
  2094. ( AssertionInfo const& info,
  2095. ITransientExpression const& expr,
  2096. AssertionReaction& reaction ) = 0;
  2097. virtual void handleMessage
  2098. ( AssertionInfo const& info,
  2099. ResultWas::OfType resultType,
  2100. StringRef const& message,
  2101. AssertionReaction& reaction ) = 0;
  2102. virtual void handleUnexpectedExceptionNotThrown
  2103. ( AssertionInfo const& info,
  2104. AssertionReaction& reaction ) = 0;
  2105. virtual void handleUnexpectedInflightException
  2106. ( AssertionInfo const& info,
  2107. std::string const& message,
  2108. AssertionReaction& reaction ) = 0;
  2109. virtual void handleIncomplete
  2110. ( AssertionInfo const& info ) = 0;
  2111. virtual void handleNonExpr
  2112. ( AssertionInfo const &info,
  2113. ResultWas::OfType resultType,
  2114. AssertionReaction &reaction ) = 0;
  2115. virtual bool lastAssertionPassed() = 0;
  2116. virtual void assertionPassed() = 0;
  2117. // Deprecated, do not use:
  2118. virtual std::string getCurrentTestName() const = 0;
  2119. virtual const AssertionResult* getLastResult() const = 0;
  2120. virtual void exceptionEarlyReported() = 0;
  2121. };
  2122. IResultCapture& getResultCapture();
  2123. }
  2124. // end catch_interfaces_capture.h
  2125. namespace Catch {
  2126. struct TestFailureException{};
  2127. struct AssertionResultData;
  2128. struct IResultCapture;
  2129. class RunContext;
  2130. class LazyExpression {
  2131. friend class AssertionHandler;
  2132. friend struct AssertionStats;
  2133. friend class RunContext;
  2134. ITransientExpression const* m_transientExpression = nullptr;
  2135. bool m_isNegated;
  2136. public:
  2137. LazyExpression( bool isNegated );
  2138. LazyExpression( LazyExpression const& other );
  2139. LazyExpression& operator = ( LazyExpression const& ) = delete;
  2140. explicit operator bool() const;
  2141. friend auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream&;
  2142. };
  2143. struct AssertionReaction {
  2144. bool shouldDebugBreak = false;
  2145. bool shouldThrow = false;
  2146. };
  2147. class AssertionHandler {
  2148. AssertionInfo m_assertionInfo;
  2149. AssertionReaction m_reaction;
  2150. bool m_completed = false;
  2151. IResultCapture& m_resultCapture;
  2152. public:
  2153. AssertionHandler
  2154. ( StringRef const& macroName,
  2155. SourceLineInfo const& lineInfo,
  2156. StringRef capturedExpression,
  2157. ResultDisposition::Flags resultDisposition );
  2158. ~AssertionHandler() {
  2159. if ( !m_completed ) {
  2160. m_resultCapture.handleIncomplete( m_assertionInfo );
  2161. }
  2162. }
  2163. template<typename T>
  2164. void handleExpr( ExprLhs<T> const& expr ) {
  2165. handleExpr( expr.makeUnaryExpr() );
  2166. }
  2167. void handleExpr( ITransientExpression const& expr );
  2168. void handleMessage(ResultWas::OfType resultType, StringRef const& message);
  2169. void handleExceptionThrownAsExpected();
  2170. void handleUnexpectedExceptionNotThrown();
  2171. void handleExceptionNotThrownAsExpected();
  2172. void handleThrowingCallSkipped();
  2173. void handleUnexpectedInflightException();
  2174. void complete();
  2175. void setCompleted();
  2176. // query
  2177. auto allowThrows() const -> bool;
  2178. };
  2179. void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString );
  2180. } // namespace Catch
  2181. // end catch_assertionhandler.h
  2182. // start catch_message.h
  2183. #include <string>
  2184. #include <vector>
  2185. namespace Catch {
  2186. struct MessageInfo {
  2187. MessageInfo( StringRef const& _macroName,
  2188. SourceLineInfo const& _lineInfo,
  2189. ResultWas::OfType _type );
  2190. StringRef macroName;
  2191. std::string message;
  2192. SourceLineInfo lineInfo;
  2193. ResultWas::OfType type;
  2194. unsigned int sequence;
  2195. bool operator == ( MessageInfo const& other ) const;
  2196. bool operator < ( MessageInfo const& other ) const;
  2197. private:
  2198. static unsigned int globalCount;
  2199. };
  2200. struct MessageStream {
  2201. template<typename T>
  2202. MessageStream& operator << ( T const& value ) {
  2203. m_stream << value;
  2204. return *this;
  2205. }
  2206. ReusableStringStream m_stream;
  2207. };
  2208. struct MessageBuilder : MessageStream {
  2209. MessageBuilder( StringRef const& macroName,
  2210. SourceLineInfo const& lineInfo,
  2211. ResultWas::OfType type );
  2212. template<typename T>
  2213. MessageBuilder& operator << ( T const& value ) {
  2214. m_stream << value;
  2215. return *this;
  2216. }
  2217. MessageInfo m_info;
  2218. };
  2219. class ScopedMessage {
  2220. public:
  2221. explicit ScopedMessage( MessageBuilder const& builder );
  2222. ScopedMessage( ScopedMessage& duplicate ) = delete;
  2223. ScopedMessage( ScopedMessage&& old );
  2224. ~ScopedMessage();
  2225. MessageInfo m_info;
  2226. bool m_moved;
  2227. };
  2228. class Capturer {
  2229. std::vector<MessageInfo> m_messages;
  2230. IResultCapture& m_resultCapture = getResultCapture();
  2231. size_t m_captured = 0;
  2232. public:
  2233. Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names );
  2234. ~Capturer();
  2235. void captureValue( size_t index, std::string const& value );
  2236. template<typename T>
  2237. void captureValues( size_t index, T const& value ) {
  2238. captureValue( index, Catch::Detail::stringify( value ) );
  2239. }
  2240. template<typename T, typename... Ts>
  2241. void captureValues( size_t index, T const& value, Ts const&... values ) {
  2242. captureValue( index, Catch::Detail::stringify(value) );
  2243. captureValues( index+1, values... );
  2244. }
  2245. };
  2246. } // end namespace Catch
  2247. // end catch_message.h
  2248. #if !defined(CATCH_CONFIG_DISABLE)
  2249. #if !defined(CATCH_CONFIG_DISABLE_STRINGIFICATION)
  2250. #define CATCH_INTERNAL_STRINGIFY(...) #__VA_ARGS__
  2251. #else
  2252. #define CATCH_INTERNAL_STRINGIFY(...) "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION"
  2253. #endif
  2254. #if defined(CATCH_CONFIG_FAST_COMPILE) || defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  2255. ///////////////////////////////////////////////////////////////////////////////
  2256. // Another way to speed-up compilation is to omit local try-catch for REQUIRE*
  2257. // macros.
  2258. #define INTERNAL_CATCH_TRY
  2259. #define INTERNAL_CATCH_CATCH( capturer )
  2260. #else // CATCH_CONFIG_FAST_COMPILE
  2261. #define INTERNAL_CATCH_TRY try
  2262. #define INTERNAL_CATCH_CATCH( handler ) catch(...) { handler.handleUnexpectedInflightException(); }
  2263. #endif
  2264. #define INTERNAL_CATCH_REACT( handler ) handler.complete();
  2265. ///////////////////////////////////////////////////////////////////////////////
  2266. #define INTERNAL_CATCH_TEST( macroName, resultDisposition, ... ) \
  2267. do { \
  2268. CATCH_INTERNAL_IGNORE_BUT_WARN(__VA_ARGS__); \
  2269. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
  2270. INTERNAL_CATCH_TRY { \
  2271. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
  2272. CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
  2273. catchAssertionHandler.handleExpr( Catch::Decomposer() <= __VA_ARGS__ ); \
  2274. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
  2275. } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
  2276. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2277. } while( (void)0, (false) && static_cast<bool>( !!(__VA_ARGS__) ) )
  2278. ///////////////////////////////////////////////////////////////////////////////
  2279. #define INTERNAL_CATCH_IF( macroName, resultDisposition, ... ) \
  2280. INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
  2281. if( Catch::getResultCapture().lastAssertionPassed() )
  2282. ///////////////////////////////////////////////////////////////////////////////
  2283. #define INTERNAL_CATCH_ELSE( macroName, resultDisposition, ... ) \
  2284. INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
  2285. if( !Catch::getResultCapture().lastAssertionPassed() )
  2286. ///////////////////////////////////////////////////////////////////////////////
  2287. #define INTERNAL_CATCH_NO_THROW( macroName, resultDisposition, ... ) \
  2288. do { \
  2289. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
  2290. try { \
  2291. static_cast<void>(__VA_ARGS__); \
  2292. catchAssertionHandler.handleExceptionNotThrownAsExpected(); \
  2293. } \
  2294. catch( ... ) { \
  2295. catchAssertionHandler.handleUnexpectedInflightException(); \
  2296. } \
  2297. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2298. } while( false )
  2299. ///////////////////////////////////////////////////////////////////////////////
  2300. #define INTERNAL_CATCH_THROWS( macroName, resultDisposition, ... ) \
  2301. do { \
  2302. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition); \
  2303. if( catchAssertionHandler.allowThrows() ) \
  2304. try { \
  2305. static_cast<void>(__VA_ARGS__); \
  2306. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  2307. } \
  2308. catch( ... ) { \
  2309. catchAssertionHandler.handleExceptionThrownAsExpected(); \
  2310. } \
  2311. else \
  2312. catchAssertionHandler.handleThrowingCallSkipped(); \
  2313. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2314. } while( false )
  2315. ///////////////////////////////////////////////////////////////////////////////
  2316. #define INTERNAL_CATCH_THROWS_AS( macroName, exceptionType, resultDisposition, expr ) \
  2317. do { \
  2318. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType), resultDisposition ); \
  2319. if( catchAssertionHandler.allowThrows() ) \
  2320. try { \
  2321. static_cast<void>(expr); \
  2322. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  2323. } \
  2324. catch( exceptionType const& ) { \
  2325. catchAssertionHandler.handleExceptionThrownAsExpected(); \
  2326. } \
  2327. catch( ... ) { \
  2328. catchAssertionHandler.handleUnexpectedInflightException(); \
  2329. } \
  2330. else \
  2331. catchAssertionHandler.handleThrowingCallSkipped(); \
  2332. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2333. } while( false )
  2334. ///////////////////////////////////////////////////////////////////////////////
  2335. #define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, ... ) \
  2336. do { \
  2337. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::StringRef(), resultDisposition ); \
  2338. catchAssertionHandler.handleMessage( messageType, ( Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop() ).m_stream.str() ); \
  2339. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2340. } while( false )
  2341. ///////////////////////////////////////////////////////////////////////////////
  2342. #define INTERNAL_CATCH_CAPTURE( varName, macroName, ... ) \
  2343. auto varName = Catch::Capturer( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info, #__VA_ARGS__ ); \
  2344. varName.captureValues( 0, __VA_ARGS__ )
  2345. ///////////////////////////////////////////////////////////////////////////////
  2346. #define INTERNAL_CATCH_INFO( macroName, log ) \
  2347. Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage )( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log );
  2348. ///////////////////////////////////////////////////////////////////////////////
  2349. #define INTERNAL_CATCH_UNSCOPED_INFO( macroName, log ) \
  2350. Catch::getResultCapture().emplaceUnscopedMessage( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log )
  2351. ///////////////////////////////////////////////////////////////////////////////
  2352. // Although this is matcher-based, it can be used with just a string
  2353. #define INTERNAL_CATCH_THROWS_STR_MATCHES( macroName, resultDisposition, matcher, ... ) \
  2354. do { \
  2355. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  2356. if( catchAssertionHandler.allowThrows() ) \
  2357. try { \
  2358. static_cast<void>(__VA_ARGS__); \
  2359. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  2360. } \
  2361. catch( ... ) { \
  2362. Catch::handleExceptionMatchExpr( catchAssertionHandler, matcher, #matcher##_catch_sr ); \
  2363. } \
  2364. else \
  2365. catchAssertionHandler.handleThrowingCallSkipped(); \
  2366. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2367. } while( false )
  2368. #endif // CATCH_CONFIG_DISABLE
  2369. // end catch_capture.hpp
  2370. // start catch_section.h
  2371. // start catch_section_info.h
  2372. // start catch_totals.h
  2373. #include <cstddef>
  2374. namespace Catch {
  2375. struct Counts {
  2376. Counts operator - ( Counts const& other ) const;
  2377. Counts& operator += ( Counts const& other );
  2378. std::size_t total() const;
  2379. bool allPassed() const;
  2380. bool allOk() const;
  2381. std::size_t passed = 0;
  2382. std::size_t failed = 0;
  2383. std::size_t failedButOk = 0;
  2384. };
  2385. struct Totals {
  2386. Totals operator - ( Totals const& other ) const;
  2387. Totals& operator += ( Totals const& other );
  2388. Totals delta( Totals const& prevTotals ) const;
  2389. int error = 0;
  2390. Counts assertions;
  2391. Counts testCases;
  2392. };
  2393. }
  2394. // end catch_totals.h
  2395. #include <string>
  2396. namespace Catch {
  2397. struct SectionInfo {
  2398. SectionInfo
  2399. ( SourceLineInfo const& _lineInfo,
  2400. std::string const& _name );
  2401. // Deprecated
  2402. SectionInfo
  2403. ( SourceLineInfo const& _lineInfo,
  2404. std::string const& _name,
  2405. std::string const& ) : SectionInfo( _lineInfo, _name ) {}
  2406. std::string name;
  2407. std::string description; // !Deprecated: this will always be empty
  2408. SourceLineInfo lineInfo;
  2409. };
  2410. struct SectionEndInfo {
  2411. SectionInfo sectionInfo;
  2412. Counts prevAssertions;
  2413. double durationInSeconds;
  2414. };
  2415. } // end namespace Catch
  2416. // end catch_section_info.h
  2417. // start catch_timer.h
  2418. #include <cstdint>
  2419. namespace Catch {
  2420. auto getCurrentNanosecondsSinceEpoch() -> uint64_t;
  2421. auto getEstimatedClockResolution() -> uint64_t;
  2422. class Timer {
  2423. uint64_t m_nanoseconds = 0;
  2424. public:
  2425. void start();
  2426. auto getElapsedNanoseconds() const -> uint64_t;
  2427. auto getElapsedMicroseconds() const -> uint64_t;
  2428. auto getElapsedMilliseconds() const -> unsigned int;
  2429. auto getElapsedSeconds() const -> double;
  2430. };
  2431. } // namespace Catch
  2432. // end catch_timer.h
  2433. #include <string>
  2434. namespace Catch {
  2435. class Section : NonCopyable {
  2436. public:
  2437. Section( SectionInfo const& info );
  2438. ~Section();
  2439. // This indicates whether the section should be executed or not
  2440. explicit operator bool() const;
  2441. private:
  2442. SectionInfo m_info;
  2443. std::string m_name;
  2444. Counts m_assertions;
  2445. bool m_sectionIncluded;
  2446. Timer m_timer;
  2447. };
  2448. } // end namespace Catch
  2449. #define INTERNAL_CATCH_SECTION( ... ) \
  2450. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
  2451. CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
  2452. if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) ) \
  2453. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
  2454. #define INTERNAL_CATCH_DYNAMIC_SECTION( ... ) \
  2455. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
  2456. CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
  2457. if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, (Catch::ReusableStringStream() << __VA_ARGS__).str() ) ) \
  2458. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
  2459. // end catch_section.h
  2460. // start catch_interfaces_exception.h
  2461. // start catch_interfaces_registry_hub.h
  2462. #include <string>
  2463. #include <memory>
  2464. namespace Catch {
  2465. class TestCase;
  2466. struct ITestCaseRegistry;
  2467. struct IExceptionTranslatorRegistry;
  2468. struct IExceptionTranslator;
  2469. struct IReporterRegistry;
  2470. struct IReporterFactory;
  2471. struct ITagAliasRegistry;
  2472. struct IMutableEnumValuesRegistry;
  2473. class StartupExceptionRegistry;
  2474. using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
  2475. struct IRegistryHub {
  2476. virtual ~IRegistryHub();
  2477. virtual IReporterRegistry const& getReporterRegistry() const = 0;
  2478. virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0;
  2479. virtual ITagAliasRegistry const& getTagAliasRegistry() const = 0;
  2480. virtual IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const = 0;
  2481. virtual StartupExceptionRegistry const& getStartupExceptionRegistry() const = 0;
  2482. };
  2483. struct IMutableRegistryHub {
  2484. virtual ~IMutableRegistryHub();
  2485. virtual void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) = 0;
  2486. virtual void registerListener( IReporterFactoryPtr const& factory ) = 0;
  2487. virtual void registerTest( TestCase const& testInfo ) = 0;
  2488. virtual void registerTranslator( const IExceptionTranslator* translator ) = 0;
  2489. virtual void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) = 0;
  2490. virtual void registerStartupException() noexcept = 0;
  2491. virtual IMutableEnumValuesRegistry& getMutableEnumValuesRegistry() = 0;
  2492. };
  2493. IRegistryHub const& getRegistryHub();
  2494. IMutableRegistryHub& getMutableRegistryHub();
  2495. void cleanUp();
  2496. std::string translateActiveException();
  2497. }
  2498. // end catch_interfaces_registry_hub.h
  2499. #if defined(CATCH_CONFIG_DISABLE)
  2500. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( translatorName, signature) \
  2501. static std::string translatorName( signature )
  2502. #endif
  2503. #include <exception>
  2504. #include <string>
  2505. #include <vector>
  2506. namespace Catch {
  2507. using exceptionTranslateFunction = std::string(*)();
  2508. struct IExceptionTranslator;
  2509. using ExceptionTranslators = std::vector<std::unique_ptr<IExceptionTranslator const>>;
  2510. struct IExceptionTranslator {
  2511. virtual ~IExceptionTranslator();
  2512. virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const = 0;
  2513. };
  2514. struct IExceptionTranslatorRegistry {
  2515. virtual ~IExceptionTranslatorRegistry();
  2516. virtual std::string translateActiveException() const = 0;
  2517. };
  2518. class ExceptionTranslatorRegistrar {
  2519. template<typename T>
  2520. class ExceptionTranslator : public IExceptionTranslator {
  2521. public:
  2522. ExceptionTranslator( std::string(*translateFunction)( T& ) )
  2523. : m_translateFunction( translateFunction )
  2524. {}
  2525. std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const override {
  2526. #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  2527. return "";
  2528. #else
  2529. try {
  2530. if( it == itEnd )
  2531. std::rethrow_exception(std::current_exception());
  2532. else
  2533. return (*it)->translate( it+1, itEnd );
  2534. }
  2535. catch( T& ex ) {
  2536. return m_translateFunction( ex );
  2537. }
  2538. #endif
  2539. }
  2540. protected:
  2541. std::string(*m_translateFunction)( T& );
  2542. };
  2543. public:
  2544. template<typename T>
  2545. ExceptionTranslatorRegistrar( std::string(*translateFunction)( T& ) ) {
  2546. getMutableRegistryHub().registerTranslator
  2547. ( new ExceptionTranslator<T>( translateFunction ) );
  2548. }
  2549. };
  2550. }
  2551. ///////////////////////////////////////////////////////////////////////////////
  2552. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION2( translatorName, signature ) \
  2553. static std::string translatorName( signature ); \
  2554. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
  2555. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  2556. namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &translatorName ); } \
  2557. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
  2558. static std::string translatorName( signature )
  2559. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
  2560. // end catch_interfaces_exception.h
  2561. // start catch_approx.h
  2562. #include <type_traits>
  2563. namespace Catch {
  2564. namespace Detail {
  2565. class Approx {
  2566. private:
  2567. bool equalityComparisonImpl(double other) const;
  2568. // Validates the new margin (margin >= 0)
  2569. // out-of-line to avoid including stdexcept in the header
  2570. void setMargin(double margin);
  2571. // Validates the new epsilon (0 < epsilon < 1)
  2572. // out-of-line to avoid including stdexcept in the header
  2573. void setEpsilon(double epsilon);
  2574. public:
  2575. explicit Approx ( double value );
  2576. static Approx custom();
  2577. Approx operator-() const;
  2578. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2579. Approx operator()( T const& value ) {
  2580. Approx approx( static_cast<double>(value) );
  2581. approx.m_epsilon = m_epsilon;
  2582. approx.m_margin = m_margin;
  2583. approx.m_scale = m_scale;
  2584. return approx;
  2585. }
  2586. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2587. explicit Approx( T const& value ): Approx(static_cast<double>(value))
  2588. {}
  2589. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2590. friend bool operator == ( const T& lhs, Approx const& rhs ) {
  2591. auto lhs_v = static_cast<double>(lhs);
  2592. return rhs.equalityComparisonImpl(lhs_v);
  2593. }
  2594. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2595. friend bool operator == ( Approx const& lhs, const T& rhs ) {
  2596. return operator==( rhs, lhs );
  2597. }
  2598. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2599. friend bool operator != ( T const& lhs, Approx const& rhs ) {
  2600. return !operator==( lhs, rhs );
  2601. }
  2602. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2603. friend bool operator != ( Approx const& lhs, T const& rhs ) {
  2604. return !operator==( rhs, lhs );
  2605. }
  2606. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2607. friend bool operator <= ( T const& lhs, Approx const& rhs ) {
  2608. return static_cast<double>(lhs) < rhs.m_value || lhs == rhs;
  2609. }
  2610. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2611. friend bool operator <= ( Approx const& lhs, T const& rhs ) {
  2612. return lhs.m_value < static_cast<double>(rhs) || lhs == rhs;
  2613. }
  2614. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2615. friend bool operator >= ( T const& lhs, Approx const& rhs ) {
  2616. return static_cast<double>(lhs) > rhs.m_value || lhs == rhs;
  2617. }
  2618. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2619. friend bool operator >= ( Approx const& lhs, T const& rhs ) {
  2620. return lhs.m_value > static_cast<double>(rhs) || lhs == rhs;
  2621. }
  2622. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2623. Approx& epsilon( T const& newEpsilon ) {
  2624. double epsilonAsDouble = static_cast<double>(newEpsilon);
  2625. setEpsilon(epsilonAsDouble);
  2626. return *this;
  2627. }
  2628. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2629. Approx& margin( T const& newMargin ) {
  2630. double marginAsDouble = static_cast<double>(newMargin);
  2631. setMargin(marginAsDouble);
  2632. return *this;
  2633. }
  2634. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2635. Approx& scale( T const& newScale ) {
  2636. m_scale = static_cast<double>(newScale);
  2637. return *this;
  2638. }
  2639. std::string toString() const;
  2640. private:
  2641. double m_epsilon;
  2642. double m_margin;
  2643. double m_scale;
  2644. double m_value;
  2645. };
  2646. } // end namespace Detail
  2647. namespace literals {
  2648. Detail::Approx operator "" _a(long double val);
  2649. Detail::Approx operator "" _a(unsigned long long val);
  2650. } // end namespace literals
  2651. template<>
  2652. struct StringMaker<Catch::Detail::Approx> {
  2653. static std::string convert(Catch::Detail::Approx const& value);
  2654. };
  2655. } // end namespace Catch
  2656. // end catch_approx.h
  2657. // start catch_string_manip.h
  2658. #include <string>
  2659. #include <iosfwd>
  2660. #include <vector>
  2661. namespace Catch {
  2662. bool startsWith( std::string const& s, std::string const& prefix );
  2663. bool startsWith( std::string const& s, char prefix );
  2664. bool endsWith( std::string const& s, std::string const& suffix );
  2665. bool endsWith( std::string const& s, char suffix );
  2666. bool contains( std::string const& s, std::string const& infix );
  2667. void toLowerInPlace( std::string& s );
  2668. std::string toLower( std::string const& s );
  2669. //! Returns a new string without whitespace at the start/end
  2670. std::string trim( std::string const& str );
  2671. //! Returns a substring of the original ref without whitespace. Beware lifetimes!
  2672. StringRef trim(StringRef ref);
  2673. // !!! Be aware, returns refs into original string - make sure original string outlives them
  2674. std::vector<StringRef> splitStringRef( StringRef str, char delimiter );
  2675. bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis );
  2676. struct pluralise {
  2677. pluralise( std::size_t count, std::string const& label );
  2678. friend std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser );
  2679. std::size_t m_count;
  2680. std::string m_label;
  2681. };
  2682. }
  2683. // end catch_string_manip.h
  2684. #ifndef CATCH_CONFIG_DISABLE_MATCHERS
  2685. // start catch_capture_matchers.h
  2686. // start catch_matchers.h
  2687. #include <string>
  2688. #include <vector>
  2689. namespace Catch {
  2690. namespace Matchers {
  2691. namespace Impl {
  2692. template<typename ArgT> struct MatchAllOf;
  2693. template<typename ArgT> struct MatchAnyOf;
  2694. template<typename ArgT> struct MatchNotOf;
  2695. class MatcherUntypedBase {
  2696. public:
  2697. MatcherUntypedBase() = default;
  2698. MatcherUntypedBase ( MatcherUntypedBase const& ) = default;
  2699. MatcherUntypedBase& operator = ( MatcherUntypedBase const& ) = delete;
  2700. std::string toString() const;
  2701. protected:
  2702. virtual ~MatcherUntypedBase();
  2703. virtual std::string describe() const = 0;
  2704. mutable std::string m_cachedToString;
  2705. };
  2706. #ifdef __clang__
  2707. # pragma clang diagnostic push
  2708. # pragma clang diagnostic ignored "-Wnon-virtual-dtor"
  2709. #endif
  2710. template<typename ObjectT>
  2711. struct MatcherMethod {
  2712. virtual bool match( ObjectT const& arg ) const = 0;
  2713. };
  2714. #if defined(__OBJC__)
  2715. // Hack to fix Catch GH issue #1661. Could use id for generic Object support.
  2716. // use of const for Object pointers is very uncommon and under ARC it causes some kind of signature mismatch that breaks compilation
  2717. template<>
  2718. struct MatcherMethod<NSString*> {
  2719. virtual bool match( NSString* arg ) const = 0;
  2720. };
  2721. #endif
  2722. #ifdef __clang__
  2723. # pragma clang diagnostic pop
  2724. #endif
  2725. template<typename T>
  2726. struct MatcherBase : MatcherUntypedBase, MatcherMethod<T> {
  2727. MatchAllOf<T> operator && ( MatcherBase const& other ) const;
  2728. MatchAnyOf<T> operator || ( MatcherBase const& other ) const;
  2729. MatchNotOf<T> operator ! () const;
  2730. };
  2731. template<typename ArgT>
  2732. struct MatchAllOf : MatcherBase<ArgT> {
  2733. bool match( ArgT const& arg ) const override {
  2734. for( auto matcher : m_matchers ) {
  2735. if (!matcher->match(arg))
  2736. return false;
  2737. }
  2738. return true;
  2739. }
  2740. std::string describe() const override {
  2741. std::string description;
  2742. description.reserve( 4 + m_matchers.size()*32 );
  2743. description += "( ";
  2744. bool first = true;
  2745. for( auto matcher : m_matchers ) {
  2746. if( first )
  2747. first = false;
  2748. else
  2749. description += " and ";
  2750. description += matcher->toString();
  2751. }
  2752. description += " )";
  2753. return description;
  2754. }
  2755. MatchAllOf<ArgT> operator && ( MatcherBase<ArgT> const& other ) {
  2756. auto copy(*this);
  2757. copy.m_matchers.push_back( &other );
  2758. return copy;
  2759. }
  2760. std::vector<MatcherBase<ArgT> const*> m_matchers;
  2761. };
  2762. template<typename ArgT>
  2763. struct MatchAnyOf : MatcherBase<ArgT> {
  2764. bool match( ArgT const& arg ) const override {
  2765. for( auto matcher : m_matchers ) {
  2766. if (matcher->match(arg))
  2767. return true;
  2768. }
  2769. return false;
  2770. }
  2771. std::string describe() const override {
  2772. std::string description;
  2773. description.reserve( 4 + m_matchers.size()*32 );
  2774. description += "( ";
  2775. bool first = true;
  2776. for( auto matcher : m_matchers ) {
  2777. if( first )
  2778. first = false;
  2779. else
  2780. description += " or ";
  2781. description += matcher->toString();
  2782. }
  2783. description += " )";
  2784. return description;
  2785. }
  2786. MatchAnyOf<ArgT> operator || ( MatcherBase<ArgT> const& other ) {
  2787. auto copy(*this);
  2788. copy.m_matchers.push_back( &other );
  2789. return copy;
  2790. }
  2791. std::vector<MatcherBase<ArgT> const*> m_matchers;
  2792. };
  2793. template<typename ArgT>
  2794. struct MatchNotOf : MatcherBase<ArgT> {
  2795. MatchNotOf( MatcherBase<ArgT> const& underlyingMatcher ) : m_underlyingMatcher( underlyingMatcher ) {}
  2796. bool match( ArgT const& arg ) const override {
  2797. return !m_underlyingMatcher.match( arg );
  2798. }
  2799. std::string describe() const override {
  2800. return "not " + m_underlyingMatcher.toString();
  2801. }
  2802. MatcherBase<ArgT> const& m_underlyingMatcher;
  2803. };
  2804. template<typename T>
  2805. MatchAllOf<T> MatcherBase<T>::operator && ( MatcherBase const& other ) const {
  2806. return MatchAllOf<T>() && *this && other;
  2807. }
  2808. template<typename T>
  2809. MatchAnyOf<T> MatcherBase<T>::operator || ( MatcherBase const& other ) const {
  2810. return MatchAnyOf<T>() || *this || other;
  2811. }
  2812. template<typename T>
  2813. MatchNotOf<T> MatcherBase<T>::operator ! () const {
  2814. return MatchNotOf<T>( *this );
  2815. }
  2816. } // namespace Impl
  2817. } // namespace Matchers
  2818. using namespace Matchers;
  2819. using Matchers::Impl::MatcherBase;
  2820. } // namespace Catch
  2821. // end catch_matchers.h
  2822. // start catch_matchers_exception.hpp
  2823. namespace Catch {
  2824. namespace Matchers {
  2825. namespace Exception {
  2826. class ExceptionMessageMatcher : public MatcherBase<std::exception> {
  2827. std::string m_message;
  2828. public:
  2829. ExceptionMessageMatcher(std::string const& message):
  2830. m_message(message)
  2831. {}
  2832. bool match(std::exception const& ex) const override;
  2833. std::string describe() const override;
  2834. };
  2835. } // namespace Exception
  2836. Exception::ExceptionMessageMatcher Message(std::string const& message);
  2837. } // namespace Matchers
  2838. } // namespace Catch
  2839. // end catch_matchers_exception.hpp
  2840. // start catch_matchers_floating.h
  2841. namespace Catch {
  2842. namespace Matchers {
  2843. namespace Floating {
  2844. enum class FloatingPointKind : uint8_t;
  2845. struct WithinAbsMatcher : MatcherBase<double> {
  2846. WithinAbsMatcher(double target, double margin);
  2847. bool match(double const& matchee) const override;
  2848. std::string describe() const override;
  2849. private:
  2850. double m_target;
  2851. double m_margin;
  2852. };
  2853. struct WithinUlpsMatcher : MatcherBase<double> {
  2854. WithinUlpsMatcher(double target, uint64_t ulps, FloatingPointKind baseType);
  2855. bool match(double const& matchee) const override;
  2856. std::string describe() const override;
  2857. private:
  2858. double m_target;
  2859. uint64_t m_ulps;
  2860. FloatingPointKind m_type;
  2861. };
  2862. // Given IEEE-754 format for floats and doubles, we can assume
  2863. // that float -> double promotion is lossless. Given this, we can
  2864. // assume that if we do the standard relative comparison of
  2865. // |lhs - rhs| <= epsilon * max(fabs(lhs), fabs(rhs)), then we get
  2866. // the same result if we do this for floats, as if we do this for
  2867. // doubles that were promoted from floats.
  2868. struct WithinRelMatcher : MatcherBase<double> {
  2869. WithinRelMatcher(double target, double epsilon);
  2870. bool match(double const& matchee) const override;
  2871. std::string describe() const override;
  2872. private:
  2873. double m_target;
  2874. double m_epsilon;
  2875. };
  2876. } // namespace Floating
  2877. // The following functions create the actual matcher objects.
  2878. // This allows the types to be inferred
  2879. Floating::WithinUlpsMatcher WithinULP(double target, uint64_t maxUlpDiff);
  2880. Floating::WithinUlpsMatcher WithinULP(float target, uint64_t maxUlpDiff);
  2881. Floating::WithinAbsMatcher WithinAbs(double target, double margin);
  2882. Floating::WithinRelMatcher WithinRel(double target, double eps);
  2883. // defaults epsilon to 100*numeric_limits<double>::epsilon()
  2884. Floating::WithinRelMatcher WithinRel(double target);
  2885. Floating::WithinRelMatcher WithinRel(float target, float eps);
  2886. // defaults epsilon to 100*numeric_limits<float>::epsilon()
  2887. Floating::WithinRelMatcher WithinRel(float target);
  2888. } // namespace Matchers
  2889. } // namespace Catch
  2890. // end catch_matchers_floating.h
  2891. // start catch_matchers_generic.hpp
  2892. #include <functional>
  2893. #include <string>
  2894. namespace Catch {
  2895. namespace Matchers {
  2896. namespace Generic {
  2897. namespace Detail {
  2898. std::string finalizeDescription(const std::string& desc);
  2899. }
  2900. template <typename T>
  2901. class PredicateMatcher : public MatcherBase<T> {
  2902. std::function<bool(T const&)> m_predicate;
  2903. std::string m_description;
  2904. public:
  2905. PredicateMatcher(std::function<bool(T const&)> const& elem, std::string const& descr)
  2906. :m_predicate(std::move(elem)),
  2907. m_description(Detail::finalizeDescription(descr))
  2908. {}
  2909. bool match( T const& item ) const override {
  2910. return m_predicate(item);
  2911. }
  2912. std::string describe() const override {
  2913. return m_description;
  2914. }
  2915. };
  2916. } // namespace Generic
  2917. // The following functions create the actual matcher objects.
  2918. // The user has to explicitly specify type to the function, because
  2919. // inferring std::function<bool(T const&)> is hard (but possible) and
  2920. // requires a lot of TMP.
  2921. template<typename T>
  2922. Generic::PredicateMatcher<T> Predicate(std::function<bool(T const&)> const& predicate, std::string const& description = "") {
  2923. return Generic::PredicateMatcher<T>(predicate, description);
  2924. }
  2925. } // namespace Matchers
  2926. } // namespace Catch
  2927. // end catch_matchers_generic.hpp
  2928. // start catch_matchers_string.h
  2929. #include <string>
  2930. namespace Catch {
  2931. namespace Matchers {
  2932. namespace StdString {
  2933. struct CasedString
  2934. {
  2935. CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity );
  2936. std::string adjustString( std::string const& str ) const;
  2937. std::string caseSensitivitySuffix() const;
  2938. CaseSensitive::Choice m_caseSensitivity;
  2939. std::string m_str;
  2940. };
  2941. struct StringMatcherBase : MatcherBase<std::string> {
  2942. StringMatcherBase( std::string const& operation, CasedString const& comparator );
  2943. std::string describe() const override;
  2944. CasedString m_comparator;
  2945. std::string m_operation;
  2946. };
  2947. struct EqualsMatcher : StringMatcherBase {
  2948. EqualsMatcher( CasedString const& comparator );
  2949. bool match( std::string const& source ) const override;
  2950. };
  2951. struct ContainsMatcher : StringMatcherBase {
  2952. ContainsMatcher( CasedString const& comparator );
  2953. bool match( std::string const& source ) const override;
  2954. };
  2955. struct StartsWithMatcher : StringMatcherBase {
  2956. StartsWithMatcher( CasedString const& comparator );
  2957. bool match( std::string const& source ) const override;
  2958. };
  2959. struct EndsWithMatcher : StringMatcherBase {
  2960. EndsWithMatcher( CasedString const& comparator );
  2961. bool match( std::string const& source ) const override;
  2962. };
  2963. struct RegexMatcher : MatcherBase<std::string> {
  2964. RegexMatcher( std::string regex, CaseSensitive::Choice caseSensitivity );
  2965. bool match( std::string const& matchee ) const override;
  2966. std::string describe() const override;
  2967. private:
  2968. std::string m_regex;
  2969. CaseSensitive::Choice m_caseSensitivity;
  2970. };
  2971. } // namespace StdString
  2972. // The following functions create the actual matcher objects.
  2973. // This allows the types to be inferred
  2974. StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2975. StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2976. StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2977. StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2978. StdString::RegexMatcher Matches( std::string const& regex, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2979. } // namespace Matchers
  2980. } // namespace Catch
  2981. // end catch_matchers_string.h
  2982. // start catch_matchers_vector.h
  2983. #include <algorithm>
  2984. namespace Catch {
  2985. namespace Matchers {
  2986. namespace Vector {
  2987. template<typename T, typename Alloc>
  2988. struct ContainsElementMatcher : MatcherBase<std::vector<T, Alloc>> {
  2989. ContainsElementMatcher(T const &comparator) : m_comparator( comparator) {}
  2990. bool match(std::vector<T, Alloc> const &v) const override {
  2991. for (auto const& el : v) {
  2992. if (el == m_comparator) {
  2993. return true;
  2994. }
  2995. }
  2996. return false;
  2997. }
  2998. std::string describe() const override {
  2999. return "Contains: " + ::Catch::Detail::stringify( m_comparator );
  3000. }
  3001. T const& m_comparator;
  3002. };
  3003. template<typename T, typename AllocComp, typename AllocMatch>
  3004. struct ContainsMatcher : MatcherBase<std::vector<T, AllocMatch>> {
  3005. ContainsMatcher(std::vector<T, AllocComp> const &comparator) : m_comparator( comparator ) {}
  3006. bool match(std::vector<T, AllocMatch> const &v) const override {
  3007. // !TBD: see note in EqualsMatcher
  3008. if (m_comparator.size() > v.size())
  3009. return false;
  3010. for (auto const& comparator : m_comparator) {
  3011. auto present = false;
  3012. for (const auto& el : v) {
  3013. if (el == comparator) {
  3014. present = true;
  3015. break;
  3016. }
  3017. }
  3018. if (!present) {
  3019. return false;
  3020. }
  3021. }
  3022. return true;
  3023. }
  3024. std::string describe() const override {
  3025. return "Contains: " + ::Catch::Detail::stringify( m_comparator );
  3026. }
  3027. std::vector<T, AllocComp> const& m_comparator;
  3028. };
  3029. template<typename T, typename AllocComp, typename AllocMatch>
  3030. struct EqualsMatcher : MatcherBase<std::vector<T, AllocMatch>> {
  3031. EqualsMatcher(std::vector<T, AllocComp> const &comparator) : m_comparator( comparator ) {}
  3032. bool match(std::vector<T, AllocMatch> const &v) const override {
  3033. // !TBD: This currently works if all elements can be compared using !=
  3034. // - a more general approach would be via a compare template that defaults
  3035. // to using !=. but could be specialised for, e.g. std::vector<T, Alloc> etc
  3036. // - then just call that directly
  3037. if (m_comparator.size() != v.size())
  3038. return false;
  3039. for (std::size_t i = 0; i < v.size(); ++i)
  3040. if (m_comparator[i] != v[i])
  3041. return false;
  3042. return true;
  3043. }
  3044. std::string describe() const override {
  3045. return "Equals: " + ::Catch::Detail::stringify( m_comparator );
  3046. }
  3047. std::vector<T, AllocComp> const& m_comparator;
  3048. };
  3049. template<typename T, typename AllocComp, typename AllocMatch>
  3050. struct ApproxMatcher : MatcherBase<std::vector<T, AllocMatch>> {
  3051. ApproxMatcher(std::vector<T, AllocComp> const& comparator) : m_comparator( comparator ) {}
  3052. bool match(std::vector<T, AllocMatch> const &v) const override {
  3053. if (m_comparator.size() != v.size())
  3054. return false;
  3055. for (std::size_t i = 0; i < v.size(); ++i)
  3056. if (m_comparator[i] != approx(v[i]))
  3057. return false;
  3058. return true;
  3059. }
  3060. std::string describe() const override {
  3061. return "is approx: " + ::Catch::Detail::stringify( m_comparator );
  3062. }
  3063. template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  3064. ApproxMatcher& epsilon( T const& newEpsilon ) {
  3065. approx.epsilon(newEpsilon);
  3066. return *this;
  3067. }
  3068. template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  3069. ApproxMatcher& margin( T const& newMargin ) {
  3070. approx.margin(newMargin);
  3071. return *this;
  3072. }
  3073. template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  3074. ApproxMatcher& scale( T const& newScale ) {
  3075. approx.scale(newScale);
  3076. return *this;
  3077. }
  3078. std::vector<T, AllocComp> const& m_comparator;
  3079. mutable Catch::Detail::Approx approx = Catch::Detail::Approx::custom();
  3080. };
  3081. template<typename T, typename AllocComp, typename AllocMatch>
  3082. struct UnorderedEqualsMatcher : MatcherBase<std::vector<T, AllocMatch>> {
  3083. UnorderedEqualsMatcher(std::vector<T, AllocComp> const& target) : m_target(target) {}
  3084. bool match(std::vector<T, AllocMatch> const& vec) const override {
  3085. if (m_target.size() != vec.size()) {
  3086. return false;
  3087. }
  3088. return std::is_permutation(m_target.begin(), m_target.end(), vec.begin());
  3089. }
  3090. std::string describe() const override {
  3091. return "UnorderedEquals: " + ::Catch::Detail::stringify(m_target);
  3092. }
  3093. private:
  3094. std::vector<T, AllocComp> const& m_target;
  3095. };
  3096. } // namespace Vector
  3097. // The following functions create the actual matcher objects.
  3098. // This allows the types to be inferred
  3099. template<typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp>
  3100. Vector::ContainsMatcher<T, AllocComp, AllocMatch> Contains( std::vector<T, AllocComp> const& comparator ) {
  3101. return Vector::ContainsMatcher<T, AllocComp, AllocMatch>( comparator );
  3102. }
  3103. template<typename T, typename Alloc = std::allocator<T>>
  3104. Vector::ContainsElementMatcher<T, Alloc> VectorContains( T const& comparator ) {
  3105. return Vector::ContainsElementMatcher<T, Alloc>( comparator );
  3106. }
  3107. template<typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp>
  3108. Vector::EqualsMatcher<T, AllocComp, AllocMatch> Equals( std::vector<T, AllocComp> const& comparator ) {
  3109. return Vector::EqualsMatcher<T, AllocComp, AllocMatch>( comparator );
  3110. }
  3111. template<typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp>
  3112. Vector::ApproxMatcher<T, AllocComp, AllocMatch> Approx( std::vector<T, AllocComp> const& comparator ) {
  3113. return Vector::ApproxMatcher<T, AllocComp, AllocMatch>( comparator );
  3114. }
  3115. template<typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp>
  3116. Vector::UnorderedEqualsMatcher<T, AllocComp, AllocMatch> UnorderedEquals(std::vector<T, AllocComp> const& target) {
  3117. return Vector::UnorderedEqualsMatcher<T, AllocComp, AllocMatch>( target );
  3118. }
  3119. } // namespace Matchers
  3120. } // namespace Catch
  3121. // end catch_matchers_vector.h
  3122. namespace Catch {
  3123. template<typename ArgT, typename MatcherT>
  3124. class MatchExpr : public ITransientExpression {
  3125. ArgT const& m_arg;
  3126. MatcherT m_matcher;
  3127. StringRef m_matcherString;
  3128. public:
  3129. MatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString )
  3130. : ITransientExpression{ true, matcher.match( arg ) },
  3131. m_arg( arg ),
  3132. m_matcher( matcher ),
  3133. m_matcherString( matcherString )
  3134. {}
  3135. void streamReconstructedExpression( std::ostream &os ) const override {
  3136. auto matcherAsString = m_matcher.toString();
  3137. os << Catch::Detail::stringify( m_arg ) << ' ';
  3138. if( matcherAsString == Detail::unprintableString )
  3139. os << m_matcherString;
  3140. else
  3141. os << matcherAsString;
  3142. }
  3143. };
  3144. using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
  3145. void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString );
  3146. template<typename ArgT, typename MatcherT>
  3147. auto makeMatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString ) -> MatchExpr<ArgT, MatcherT> {
  3148. return MatchExpr<ArgT, MatcherT>( arg, matcher, matcherString );
  3149. }
  3150. } // namespace Catch
  3151. ///////////////////////////////////////////////////////////////////////////////
  3152. #define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \
  3153. do { \
  3154. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  3155. INTERNAL_CATCH_TRY { \
  3156. catchAssertionHandler.handleExpr( Catch::makeMatchExpr( arg, matcher, #matcher##_catch_sr ) ); \
  3157. } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
  3158. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  3159. } while( false )
  3160. ///////////////////////////////////////////////////////////////////////////////
  3161. #define INTERNAL_CATCH_THROWS_MATCHES( macroName, exceptionType, resultDisposition, matcher, ... ) \
  3162. do { \
  3163. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(exceptionType) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  3164. if( catchAssertionHandler.allowThrows() ) \
  3165. try { \
  3166. static_cast<void>(__VA_ARGS__ ); \
  3167. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  3168. } \
  3169. catch( exceptionType const& ex ) { \
  3170. catchAssertionHandler.handleExpr( Catch::makeMatchExpr( ex, matcher, #matcher##_catch_sr ) ); \
  3171. } \
  3172. catch( ... ) { \
  3173. catchAssertionHandler.handleUnexpectedInflightException(); \
  3174. } \
  3175. else \
  3176. catchAssertionHandler.handleThrowingCallSkipped(); \
  3177. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  3178. } while( false )
  3179. // end catch_capture_matchers.h
  3180. #endif
  3181. // start catch_generators.hpp
  3182. // start catch_interfaces_generatortracker.h
  3183. #include <memory>
  3184. namespace Catch {
  3185. namespace Generators {
  3186. class GeneratorUntypedBase {
  3187. public:
  3188. GeneratorUntypedBase() = default;
  3189. virtual ~GeneratorUntypedBase();
  3190. // Attempts to move the generator to the next element
  3191. //
  3192. // Returns true iff the move succeeded (and a valid element
  3193. // can be retrieved).
  3194. virtual bool next() = 0;
  3195. };
  3196. using GeneratorBasePtr = std::unique_ptr<GeneratorUntypedBase>;
  3197. } // namespace Generators
  3198. struct IGeneratorTracker {
  3199. virtual ~IGeneratorTracker();
  3200. virtual auto hasGenerator() const -> bool = 0;
  3201. virtual auto getGenerator() const -> Generators::GeneratorBasePtr const& = 0;
  3202. virtual void setGenerator( Generators::GeneratorBasePtr&& generator ) = 0;
  3203. };
  3204. } // namespace Catch
  3205. // end catch_interfaces_generatortracker.h
  3206. // start catch_enforce.h
  3207. #include <exception>
  3208. namespace Catch {
  3209. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  3210. template <typename Ex>
  3211. [[noreturn]]
  3212. void throw_exception(Ex const& e) {
  3213. throw e;
  3214. }
  3215. #else // ^^ Exceptions are enabled // Exceptions are disabled vv
  3216. [[noreturn]]
  3217. void throw_exception(std::exception const& e);
  3218. #endif
  3219. [[noreturn]]
  3220. void throw_logic_error(std::string const& msg);
  3221. [[noreturn]]
  3222. void throw_domain_error(std::string const& msg);
  3223. [[noreturn]]
  3224. void throw_runtime_error(std::string const& msg);
  3225. } // namespace Catch;
  3226. #define CATCH_MAKE_MSG(...) \
  3227. (Catch::ReusableStringStream() << __VA_ARGS__).str()
  3228. #define CATCH_INTERNAL_ERROR(...) \
  3229. Catch::throw_logic_error(CATCH_MAKE_MSG( CATCH_INTERNAL_LINEINFO << ": Internal Catch2 error: " << __VA_ARGS__))
  3230. #define CATCH_ERROR(...) \
  3231. Catch::throw_domain_error(CATCH_MAKE_MSG( __VA_ARGS__ ))
  3232. #define CATCH_RUNTIME_ERROR(...) \
  3233. Catch::throw_runtime_error(CATCH_MAKE_MSG( __VA_ARGS__ ))
  3234. #define CATCH_ENFORCE( condition, ... ) \
  3235. do{ if( !(condition) ) CATCH_ERROR( __VA_ARGS__ ); } while(false)
  3236. // end catch_enforce.h
  3237. #include <memory>
  3238. #include <vector>
  3239. #include <cassert>
  3240. #include <utility>
  3241. #include <exception>
  3242. namespace Catch {
  3243. class GeneratorException : public std::exception {
  3244. const char* const m_msg = "";
  3245. public:
  3246. GeneratorException(const char* msg):
  3247. m_msg(msg)
  3248. {}
  3249. const char* what() const noexcept override final;
  3250. };
  3251. namespace Generators {
  3252. // !TBD move this into its own location?
  3253. namespace pf{
  3254. template<typename T, typename... Args>
  3255. std::unique_ptr<T> make_unique( Args&&... args ) {
  3256. return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
  3257. }
  3258. }
  3259. template<typename T>
  3260. struct IGenerator : GeneratorUntypedBase {
  3261. virtual ~IGenerator() = default;
  3262. // Returns the current element of the generator
  3263. //
  3264. // \Precondition The generator is either freshly constructed,
  3265. // or the last call to `next()` returned true
  3266. virtual T const& get() const = 0;
  3267. using type = T;
  3268. };
  3269. template<typename T>
  3270. class SingleValueGenerator final : public IGenerator<T> {
  3271. T m_value;
  3272. public:
  3273. SingleValueGenerator(T&& value) : m_value(std::move(value)) {}
  3274. T const& get() const override {
  3275. return m_value;
  3276. }
  3277. bool next() override {
  3278. return false;
  3279. }
  3280. };
  3281. template<typename T>
  3282. class FixedValuesGenerator final : public IGenerator<T> {
  3283. static_assert(!std::is_same<T, bool>::value,
  3284. "FixedValuesGenerator does not support bools because of std::vector<bool>"
  3285. "specialization, use SingleValue Generator instead.");
  3286. std::vector<T> m_values;
  3287. size_t m_idx = 0;
  3288. public:
  3289. FixedValuesGenerator( std::initializer_list<T> values ) : m_values( values ) {}
  3290. T const& get() const override {
  3291. return m_values[m_idx];
  3292. }
  3293. bool next() override {
  3294. ++m_idx;
  3295. return m_idx < m_values.size();
  3296. }
  3297. };
  3298. template <typename T>
  3299. class GeneratorWrapper final {
  3300. std::unique_ptr<IGenerator<T>> m_generator;
  3301. public:
  3302. GeneratorWrapper(std::unique_ptr<IGenerator<T>> generator):
  3303. m_generator(std::move(generator))
  3304. {}
  3305. T const& get() const {
  3306. return m_generator->get();
  3307. }
  3308. bool next() {
  3309. return m_generator->next();
  3310. }
  3311. };
  3312. template <typename T>
  3313. GeneratorWrapper<T> value(T&& value) {
  3314. return GeneratorWrapper<T>(pf::make_unique<SingleValueGenerator<T>>(std::forward<T>(value)));
  3315. }
  3316. template <typename T>
  3317. GeneratorWrapper<T> values(std::initializer_list<T> values) {
  3318. return GeneratorWrapper<T>(pf::make_unique<FixedValuesGenerator<T>>(values));
  3319. }
  3320. template<typename T>
  3321. class Generators : public IGenerator<T> {
  3322. std::vector<GeneratorWrapper<T>> m_generators;
  3323. size_t m_current = 0;
  3324. void populate(GeneratorWrapper<T>&& generator) {
  3325. m_generators.emplace_back(std::move(generator));
  3326. }
  3327. void populate(T&& val) {
  3328. m_generators.emplace_back(value(std::forward<T>(val)));
  3329. }
  3330. template<typename U>
  3331. void populate(U&& val) {
  3332. populate(T(std::forward<U>(val)));
  3333. }
  3334. template<typename U, typename... Gs>
  3335. void populate(U&& valueOrGenerator, Gs &&... moreGenerators) {
  3336. populate(std::forward<U>(valueOrGenerator));
  3337. populate(std::forward<Gs>(moreGenerators)...);
  3338. }
  3339. public:
  3340. template <typename... Gs>
  3341. Generators(Gs &&... moreGenerators) {
  3342. m_generators.reserve(sizeof...(Gs));
  3343. populate(std::forward<Gs>(moreGenerators)...);
  3344. }
  3345. T const& get() const override {
  3346. return m_generators[m_current].get();
  3347. }
  3348. bool next() override {
  3349. if (m_current >= m_generators.size()) {
  3350. return false;
  3351. }
  3352. const bool current_status = m_generators[m_current].next();
  3353. if (!current_status) {
  3354. ++m_current;
  3355. }
  3356. return m_current < m_generators.size();
  3357. }
  3358. };
  3359. template<typename... Ts>
  3360. GeneratorWrapper<std::tuple<Ts...>> table( std::initializer_list<std::tuple<typename std::decay<Ts>::type...>> tuples ) {
  3361. return values<std::tuple<Ts...>>( tuples );
  3362. }
  3363. // Tag type to signal that a generator sequence should convert arguments to a specific type
  3364. template <typename T>
  3365. struct as {};
  3366. template<typename T, typename... Gs>
  3367. auto makeGenerators( GeneratorWrapper<T>&& generator, Gs &&... moreGenerators ) -> Generators<T> {
  3368. return Generators<T>(std::move(generator), std::forward<Gs>(moreGenerators)...);
  3369. }
  3370. template<typename T>
  3371. auto makeGenerators( GeneratorWrapper<T>&& generator ) -> Generators<T> {
  3372. return Generators<T>(std::move(generator));
  3373. }
  3374. template<typename T, typename... Gs>
  3375. auto makeGenerators( T&& val, Gs &&... moreGenerators ) -> Generators<T> {
  3376. return makeGenerators( value( std::forward<T>( val ) ), std::forward<Gs>( moreGenerators )... );
  3377. }
  3378. template<typename T, typename U, typename... Gs>
  3379. auto makeGenerators( as<T>, U&& val, Gs &&... moreGenerators ) -> Generators<T> {
  3380. return makeGenerators( value( T( std::forward<U>( val ) ) ), std::forward<Gs>( moreGenerators )... );
  3381. }
  3382. auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker&;
  3383. template<typename L>
  3384. // Note: The type after -> is weird, because VS2015 cannot parse
  3385. // the expression used in the typedef inside, when it is in
  3386. // return type. Yeah.
  3387. auto generate( StringRef generatorName, SourceLineInfo const& lineInfo, L const& generatorExpression ) -> decltype(std::declval<decltype(generatorExpression())>().get()) {
  3388. using UnderlyingType = typename decltype(generatorExpression())::type;
  3389. IGeneratorTracker& tracker = acquireGeneratorTracker( generatorName, lineInfo );
  3390. if (!tracker.hasGenerator()) {
  3391. tracker.setGenerator(pf::make_unique<Generators<UnderlyingType>>(generatorExpression()));
  3392. }
  3393. auto const& generator = static_cast<IGenerator<UnderlyingType> const&>( *tracker.getGenerator() );
  3394. return generator.get();
  3395. }
  3396. } // namespace Generators
  3397. } // namespace Catch
  3398. #define GENERATE( ... ) \
  3399. Catch::Generators::generate( INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \
  3400. CATCH_INTERNAL_LINEINFO, \
  3401. [ ]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } ) //NOLINT(google-build-using-namespace)
  3402. #define GENERATE_COPY( ... ) \
  3403. Catch::Generators::generate( INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \
  3404. CATCH_INTERNAL_LINEINFO, \
  3405. [=]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } ) //NOLINT(google-build-using-namespace)
  3406. #define GENERATE_REF( ... ) \
  3407. Catch::Generators::generate( INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \
  3408. CATCH_INTERNAL_LINEINFO, \
  3409. [&]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } ) //NOLINT(google-build-using-namespace)
  3410. // end catch_generators.hpp
  3411. // start catch_generators_generic.hpp
  3412. namespace Catch {
  3413. namespace Generators {
  3414. template <typename T>
  3415. class TakeGenerator : public IGenerator<T> {
  3416. GeneratorWrapper<T> m_generator;
  3417. size_t m_returned = 0;
  3418. size_t m_target;
  3419. public:
  3420. TakeGenerator(size_t target, GeneratorWrapper<T>&& generator):
  3421. m_generator(std::move(generator)),
  3422. m_target(target)
  3423. {
  3424. assert(target != 0 && "Empty generators are not allowed");
  3425. }
  3426. T const& get() const override {
  3427. return m_generator.get();
  3428. }
  3429. bool next() override {
  3430. ++m_returned;
  3431. if (m_returned >= m_target) {
  3432. return false;
  3433. }
  3434. const auto success = m_generator.next();
  3435. // If the underlying generator does not contain enough values
  3436. // then we cut short as well
  3437. if (!success) {
  3438. m_returned = m_target;
  3439. }
  3440. return success;
  3441. }
  3442. };
  3443. template <typename T>
  3444. GeneratorWrapper<T> take(size_t target, GeneratorWrapper<T>&& generator) {
  3445. return GeneratorWrapper<T>(pf::make_unique<TakeGenerator<T>>(target, std::move(generator)));
  3446. }
  3447. template <typename T, typename Predicate>
  3448. class FilterGenerator : public IGenerator<T> {
  3449. GeneratorWrapper<T> m_generator;
  3450. Predicate m_predicate;
  3451. public:
  3452. template <typename P = Predicate>
  3453. FilterGenerator(P&& pred, GeneratorWrapper<T>&& generator):
  3454. m_generator(std::move(generator)),
  3455. m_predicate(std::forward<P>(pred))
  3456. {
  3457. if (!m_predicate(m_generator.get())) {
  3458. // It might happen that there are no values that pass the
  3459. // filter. In that case we throw an exception.
  3460. auto has_initial_value = next();
  3461. if (!has_initial_value) {
  3462. Catch::throw_exception(GeneratorException("No valid value found in filtered generator"));
  3463. }
  3464. }
  3465. }
  3466. T const& get() const override {
  3467. return m_generator.get();
  3468. }
  3469. bool next() override {
  3470. bool success = m_generator.next();
  3471. if (!success) {
  3472. return false;
  3473. }
  3474. while (!m_predicate(m_generator.get()) && (success = m_generator.next()) == true);
  3475. return success;
  3476. }
  3477. };
  3478. template <typename T, typename Predicate>
  3479. GeneratorWrapper<T> filter(Predicate&& pred, GeneratorWrapper<T>&& generator) {
  3480. return GeneratorWrapper<T>(std::unique_ptr<IGenerator<T>>(pf::make_unique<FilterGenerator<T, Predicate>>(std::forward<Predicate>(pred), std::move(generator))));
  3481. }
  3482. template <typename T>
  3483. class RepeatGenerator : public IGenerator<T> {
  3484. static_assert(!std::is_same<T, bool>::value,
  3485. "RepeatGenerator currently does not support bools"
  3486. "because of std::vector<bool> specialization");
  3487. GeneratorWrapper<T> m_generator;
  3488. mutable std::vector<T> m_returned;
  3489. size_t m_target_repeats;
  3490. size_t m_current_repeat = 0;
  3491. size_t m_repeat_index = 0;
  3492. public:
  3493. RepeatGenerator(size_t repeats, GeneratorWrapper<T>&& generator):
  3494. m_generator(std::move(generator)),
  3495. m_target_repeats(repeats)
  3496. {
  3497. assert(m_target_repeats > 0 && "Repeat generator must repeat at least once");
  3498. }
  3499. T const& get() const override {
  3500. if (m_current_repeat == 0) {
  3501. m_returned.push_back(m_generator.get());
  3502. return m_returned.back();
  3503. }
  3504. return m_returned[m_repeat_index];
  3505. }
  3506. bool next() override {
  3507. // There are 2 basic cases:
  3508. // 1) We are still reading the generator
  3509. // 2) We are reading our own cache
  3510. // In the first case, we need to poke the underlying generator.
  3511. // If it happily moves, we are left in that state, otherwise it is time to start reading from our cache
  3512. if (m_current_repeat == 0) {
  3513. const auto success = m_generator.next();
  3514. if (!success) {
  3515. ++m_current_repeat;
  3516. }
  3517. return m_current_repeat < m_target_repeats;
  3518. }
  3519. // In the second case, we need to move indices forward and check that we haven't run up against the end
  3520. ++m_repeat_index;
  3521. if (m_repeat_index == m_returned.size()) {
  3522. m_repeat_index = 0;
  3523. ++m_current_repeat;
  3524. }
  3525. return m_current_repeat < m_target_repeats;
  3526. }
  3527. };
  3528. template <typename T>
  3529. GeneratorWrapper<T> repeat(size_t repeats, GeneratorWrapper<T>&& generator) {
  3530. return GeneratorWrapper<T>(pf::make_unique<RepeatGenerator<T>>(repeats, std::move(generator)));
  3531. }
  3532. template <typename T, typename U, typename Func>
  3533. class MapGenerator : public IGenerator<T> {
  3534. // TBD: provide static assert for mapping function, for friendly error message
  3535. GeneratorWrapper<U> m_generator;
  3536. Func m_function;
  3537. // To avoid returning dangling reference, we have to save the values
  3538. T m_cache;
  3539. public:
  3540. template <typename F2 = Func>
  3541. MapGenerator(F2&& function, GeneratorWrapper<U>&& generator) :
  3542. m_generator(std::move(generator)),
  3543. m_function(std::forward<F2>(function)),
  3544. m_cache(m_function(m_generator.get()))
  3545. {}
  3546. T const& get() const override {
  3547. return m_cache;
  3548. }
  3549. bool next() override {
  3550. const auto success = m_generator.next();
  3551. if (success) {
  3552. m_cache = m_function(m_generator.get());
  3553. }
  3554. return success;
  3555. }
  3556. };
  3557. template <typename Func, typename U, typename T = FunctionReturnType<Func, U>>
  3558. GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) {
  3559. return GeneratorWrapper<T>(
  3560. pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(function), std::move(generator))
  3561. );
  3562. }
  3563. template <typename T, typename U, typename Func>
  3564. GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) {
  3565. return GeneratorWrapper<T>(
  3566. pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(function), std::move(generator))
  3567. );
  3568. }
  3569. template <typename T>
  3570. class ChunkGenerator final : public IGenerator<std::vector<T>> {
  3571. std::vector<T> m_chunk;
  3572. size_t m_chunk_size;
  3573. GeneratorWrapper<T> m_generator;
  3574. bool m_used_up = false;
  3575. public:
  3576. ChunkGenerator(size_t size, GeneratorWrapper<T> generator) :
  3577. m_chunk_size(size), m_generator(std::move(generator))
  3578. {
  3579. m_chunk.reserve(m_chunk_size);
  3580. if (m_chunk_size != 0) {
  3581. m_chunk.push_back(m_generator.get());
  3582. for (size_t i = 1; i < m_chunk_size; ++i) {
  3583. if (!m_generator.next()) {
  3584. Catch::throw_exception(GeneratorException("Not enough values to initialize the first chunk"));
  3585. }
  3586. m_chunk.push_back(m_generator.get());
  3587. }
  3588. }
  3589. }
  3590. std::vector<T> const& get() const override {
  3591. return m_chunk;
  3592. }
  3593. bool next() override {
  3594. m_chunk.clear();
  3595. for (size_t idx = 0; idx < m_chunk_size; ++idx) {
  3596. if (!m_generator.next()) {
  3597. return false;
  3598. }
  3599. m_chunk.push_back(m_generator.get());
  3600. }
  3601. return true;
  3602. }
  3603. };
  3604. template <typename T>
  3605. GeneratorWrapper<std::vector<T>> chunk(size_t size, GeneratorWrapper<T>&& generator) {
  3606. return GeneratorWrapper<std::vector<T>>(
  3607. pf::make_unique<ChunkGenerator<T>>(size, std::move(generator))
  3608. );
  3609. }
  3610. } // namespace Generators
  3611. } // namespace Catch
  3612. // end catch_generators_generic.hpp
  3613. // start catch_generators_specific.hpp
  3614. // start catch_context.h
  3615. #include <memory>
  3616. namespace Catch {
  3617. struct IResultCapture;
  3618. struct IRunner;
  3619. struct IConfig;
  3620. struct IMutableContext;
  3621. using IConfigPtr = std::shared_ptr<IConfig const>;
  3622. struct IContext
  3623. {
  3624. virtual ~IContext();
  3625. virtual IResultCapture* getResultCapture() = 0;
  3626. virtual IRunner* getRunner() = 0;
  3627. virtual IConfigPtr const& getConfig() const = 0;
  3628. };
  3629. struct IMutableContext : IContext
  3630. {
  3631. virtual ~IMutableContext();
  3632. virtual void setResultCapture( IResultCapture* resultCapture ) = 0;
  3633. virtual void setRunner( IRunner* runner ) = 0;
  3634. virtual void setConfig( IConfigPtr const& config ) = 0;
  3635. private:
  3636. static IMutableContext *currentContext;
  3637. friend IMutableContext& getCurrentMutableContext();
  3638. friend void cleanUpContext();
  3639. static void createContext();
  3640. };
  3641. inline IMutableContext& getCurrentMutableContext()
  3642. {
  3643. if( !IMutableContext::currentContext )
  3644. IMutableContext::createContext();
  3645. // NOLINTNEXTLINE(clang-analyzer-core.uninitialized.UndefReturn)
  3646. return *IMutableContext::currentContext;
  3647. }
  3648. inline IContext& getCurrentContext()
  3649. {
  3650. return getCurrentMutableContext();
  3651. }
  3652. void cleanUpContext();
  3653. class SimplePcg32;
  3654. SimplePcg32& rng();
  3655. }
  3656. // end catch_context.h
  3657. // start catch_interfaces_config.h
  3658. // start catch_option.hpp
  3659. namespace Catch {
  3660. // An optional type
  3661. template<typename T>
  3662. class Option {
  3663. public:
  3664. Option() : nullableValue( nullptr ) {}
  3665. Option( T const& _value )
  3666. : nullableValue( new( storage ) T( _value ) )
  3667. {}
  3668. Option( Option const& _other )
  3669. : nullableValue( _other ? new( storage ) T( *_other ) : nullptr )
  3670. {}
  3671. ~Option() {
  3672. reset();
  3673. }
  3674. Option& operator= ( Option const& _other ) {
  3675. if( &_other != this ) {
  3676. reset();
  3677. if( _other )
  3678. nullableValue = new( storage ) T( *_other );
  3679. }
  3680. return *this;
  3681. }
  3682. Option& operator = ( T const& _value ) {
  3683. reset();
  3684. nullableValue = new( storage ) T( _value );
  3685. return *this;
  3686. }
  3687. void reset() {
  3688. if( nullableValue )
  3689. nullableValue->~T();
  3690. nullableValue = nullptr;
  3691. }
  3692. T& operator*() { return *nullableValue; }
  3693. T const& operator*() const { return *nullableValue; }
  3694. T* operator->() { return nullableValue; }
  3695. const T* operator->() const { return nullableValue; }
  3696. T valueOr( T const& defaultValue ) const {
  3697. return nullableValue ? *nullableValue : defaultValue;
  3698. }
  3699. bool some() const { return nullableValue != nullptr; }
  3700. bool none() const { return nullableValue == nullptr; }
  3701. bool operator !() const { return nullableValue == nullptr; }
  3702. explicit operator bool() const {
  3703. return some();
  3704. }
  3705. private:
  3706. T *nullableValue;
  3707. alignas(alignof(T)) char storage[sizeof(T)];
  3708. };
  3709. } // end namespace Catch
  3710. // end catch_option.hpp
  3711. #include <chrono>
  3712. #include <iosfwd>
  3713. #include <string>
  3714. #include <vector>
  3715. #include <memory>
  3716. namespace Catch {
  3717. enum class Verbosity {
  3718. Quiet = 0,
  3719. Normal,
  3720. High
  3721. };
  3722. struct WarnAbout { enum What {
  3723. Nothing = 0x00,
  3724. NoAssertions = 0x01,
  3725. NoTests = 0x02
  3726. }; };
  3727. struct ShowDurations { enum OrNot {
  3728. DefaultForReporter,
  3729. Always,
  3730. Never
  3731. }; };
  3732. struct RunTests { enum InWhatOrder {
  3733. InDeclarationOrder,
  3734. InLexicographicalOrder,
  3735. InRandomOrder
  3736. }; };
  3737. struct UseColour { enum YesOrNo {
  3738. Auto,
  3739. Yes,
  3740. No
  3741. }; };
  3742. struct WaitForKeypress { enum When {
  3743. Never,
  3744. BeforeStart = 1,
  3745. BeforeExit = 2,
  3746. BeforeStartAndExit = BeforeStart | BeforeExit
  3747. }; };
  3748. class TestSpec;
  3749. struct IConfig : NonCopyable {
  3750. virtual ~IConfig();
  3751. virtual bool allowThrows() const = 0;
  3752. virtual std::ostream& stream() const = 0;
  3753. virtual std::string name() const = 0;
  3754. virtual bool includeSuccessfulResults() const = 0;
  3755. virtual bool shouldDebugBreak() const = 0;
  3756. virtual bool warnAboutMissingAssertions() const = 0;
  3757. virtual bool warnAboutNoTests() const = 0;
  3758. virtual int abortAfter() const = 0;
  3759. virtual bool showInvisibles() const = 0;
  3760. virtual ShowDurations::OrNot showDurations() const = 0;
  3761. virtual double minDuration() const = 0;
  3762. virtual TestSpec const& testSpec() const = 0;
  3763. virtual bool hasTestFilters() const = 0;
  3764. virtual std::vector<std::string> const& getTestsOrTags() const = 0;
  3765. virtual RunTests::InWhatOrder runOrder() const = 0;
  3766. virtual unsigned int rngSeed() const = 0;
  3767. virtual UseColour::YesOrNo useColour() const = 0;
  3768. virtual std::vector<std::string> const& getSectionsToRun() const = 0;
  3769. virtual Verbosity verbosity() const = 0;
  3770. virtual bool benchmarkNoAnalysis() const = 0;
  3771. virtual int benchmarkSamples() const = 0;
  3772. virtual double benchmarkConfidenceInterval() const = 0;
  3773. virtual unsigned int benchmarkResamples() const = 0;
  3774. virtual std::chrono::milliseconds benchmarkWarmupTime() const = 0;
  3775. };
  3776. using IConfigPtr = std::shared_ptr<IConfig const>;
  3777. }
  3778. // end catch_interfaces_config.h
  3779. // start catch_random_number_generator.h
  3780. #include <cstdint>
  3781. namespace Catch {
  3782. // This is a simple implementation of C++11 Uniform Random Number
  3783. // Generator. It does not provide all operators, because Catch2
  3784. // does not use it, but it should behave as expected inside stdlib's
  3785. // distributions.
  3786. // The implementation is based on the PCG family (http://pcg-random.org)
  3787. class SimplePcg32 {
  3788. using state_type = std::uint64_t;
  3789. public:
  3790. using result_type = std::uint32_t;
  3791. static constexpr result_type (min)() {
  3792. return 0;
  3793. }
  3794. static constexpr result_type (max)() {
  3795. return static_cast<result_type>(-1);
  3796. }
  3797. // Provide some default initial state for the default constructor
  3798. SimplePcg32():SimplePcg32(0xed743cc4U) {}
  3799. explicit SimplePcg32(result_type seed_);
  3800. void seed(result_type seed_);
  3801. void discard(uint64_t skip);
  3802. result_type operator()();
  3803. private:
  3804. friend bool operator==(SimplePcg32 const& lhs, SimplePcg32 const& rhs);
  3805. friend bool operator!=(SimplePcg32 const& lhs, SimplePcg32 const& rhs);
  3806. // In theory we also need operator<< and operator>>
  3807. // In practice we do not use them, so we will skip them for now
  3808. std::uint64_t m_state;
  3809. // This part of the state determines which "stream" of the numbers
  3810. // is chosen -- we take it as a constant for Catch2, so we only
  3811. // need to deal with seeding the main state.
  3812. // Picked by reading 8 bytes from `/dev/random` :-)
  3813. static const std::uint64_t s_inc = (0x13ed0cc53f939476ULL << 1ULL) | 1ULL;
  3814. };
  3815. } // end namespace Catch
  3816. // end catch_random_number_generator.h
  3817. #include <random>
  3818. namespace Catch {
  3819. namespace Generators {
  3820. template <typename Float>
  3821. class RandomFloatingGenerator final : public IGenerator<Float> {
  3822. Catch::SimplePcg32& m_rng;
  3823. std::uniform_real_distribution<Float> m_dist;
  3824. Float m_current_number;
  3825. public:
  3826. RandomFloatingGenerator(Float a, Float b):
  3827. m_rng(rng()),
  3828. m_dist(a, b) {
  3829. static_cast<void>(next());
  3830. }
  3831. Float const& get() const override {
  3832. return m_current_number;
  3833. }
  3834. bool next() override {
  3835. m_current_number = m_dist(m_rng);
  3836. return true;
  3837. }
  3838. };
  3839. template <typename Integer>
  3840. class RandomIntegerGenerator final : public IGenerator<Integer> {
  3841. Catch::SimplePcg32& m_rng;
  3842. std::uniform_int_distribution<Integer> m_dist;
  3843. Integer m_current_number;
  3844. public:
  3845. RandomIntegerGenerator(Integer a, Integer b):
  3846. m_rng(rng()),
  3847. m_dist(a, b) {
  3848. static_cast<void>(next());
  3849. }
  3850. Integer const& get() const override {
  3851. return m_current_number;
  3852. }
  3853. bool next() override {
  3854. m_current_number = m_dist(m_rng);
  3855. return true;
  3856. }
  3857. };
  3858. // TODO: Ideally this would be also constrained against the various char types,
  3859. // but I don't expect users to run into that in practice.
  3860. template <typename T>
  3861. typename std::enable_if<std::is_integral<T>::value && !std::is_same<T, bool>::value,
  3862. GeneratorWrapper<T>>::type
  3863. random(T a, T b) {
  3864. return GeneratorWrapper<T>(
  3865. pf::make_unique<RandomIntegerGenerator<T>>(a, b)
  3866. );
  3867. }
  3868. template <typename T>
  3869. typename std::enable_if<std::is_floating_point<T>::value,
  3870. GeneratorWrapper<T>>::type
  3871. random(T a, T b) {
  3872. return GeneratorWrapper<T>(
  3873. pf::make_unique<RandomFloatingGenerator<T>>(a, b)
  3874. );
  3875. }
  3876. template <typename T>
  3877. class RangeGenerator final : public IGenerator<T> {
  3878. T m_current;
  3879. T m_end;
  3880. T m_step;
  3881. bool m_positive;
  3882. public:
  3883. RangeGenerator(T const& start, T const& end, T const& step):
  3884. m_current(start),
  3885. m_end(end),
  3886. m_step(step),
  3887. m_positive(m_step > T(0))
  3888. {
  3889. assert(m_current != m_end && "Range start and end cannot be equal");
  3890. assert(m_step != T(0) && "Step size cannot be zero");
  3891. assert(((m_positive && m_current <= m_end) || (!m_positive && m_current >= m_end)) && "Step moves away from end");
  3892. }
  3893. RangeGenerator(T const& start, T const& end):
  3894. RangeGenerator(start, end, (start < end) ? T(1) : T(-1))
  3895. {}
  3896. T const& get() const override {
  3897. return m_current;
  3898. }
  3899. bool next() override {
  3900. m_current += m_step;
  3901. return (m_positive) ? (m_current < m_end) : (m_current > m_end);
  3902. }
  3903. };
  3904. template <typename T>
  3905. GeneratorWrapper<T> range(T const& start, T const& end, T const& step) {
  3906. static_assert(std::is_arithmetic<T>::value && !std::is_same<T, bool>::value, "Type must be numeric");
  3907. return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end, step));
  3908. }
  3909. template <typename T>
  3910. GeneratorWrapper<T> range(T const& start, T const& end) {
  3911. static_assert(std::is_integral<T>::value && !std::is_same<T, bool>::value, "Type must be an integer");
  3912. return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end));
  3913. }
  3914. template <typename T>
  3915. class IteratorGenerator final : public IGenerator<T> {
  3916. static_assert(!std::is_same<T, bool>::value,
  3917. "IteratorGenerator currently does not support bools"
  3918. "because of std::vector<bool> specialization");
  3919. std::vector<T> m_elems;
  3920. size_t m_current = 0;
  3921. public:
  3922. template <typename InputIterator, typename InputSentinel>
  3923. IteratorGenerator(InputIterator first, InputSentinel last):m_elems(first, last) {
  3924. if (m_elems.empty()) {
  3925. Catch::throw_exception(GeneratorException("IteratorGenerator received no valid values"));
  3926. }
  3927. }
  3928. T const& get() const override {
  3929. return m_elems[m_current];
  3930. }
  3931. bool next() override {
  3932. ++m_current;
  3933. return m_current != m_elems.size();
  3934. }
  3935. };
  3936. template <typename InputIterator,
  3937. typename InputSentinel,
  3938. typename ResultType = typename std::iterator_traits<InputIterator>::value_type>
  3939. GeneratorWrapper<ResultType> from_range(InputIterator from, InputSentinel to) {
  3940. return GeneratorWrapper<ResultType>(pf::make_unique<IteratorGenerator<ResultType>>(from, to));
  3941. }
  3942. template <typename Container,
  3943. typename ResultType = typename Container::value_type>
  3944. GeneratorWrapper<ResultType> from_range(Container const& cnt) {
  3945. return GeneratorWrapper<ResultType>(pf::make_unique<IteratorGenerator<ResultType>>(cnt.begin(), cnt.end()));
  3946. }
  3947. } // namespace Generators
  3948. } // namespace Catch
  3949. // end catch_generators_specific.hpp
  3950. // These files are included here so the single_include script doesn't put them
  3951. // in the conditionally compiled sections
  3952. // start catch_test_case_info.h
  3953. #include <string>
  3954. #include <vector>
  3955. #include <memory>
  3956. #ifdef __clang__
  3957. #pragma clang diagnostic push
  3958. #pragma clang diagnostic ignored "-Wpadded"
  3959. #endif
  3960. namespace Catch {
  3961. struct ITestInvoker;
  3962. struct TestCaseInfo {
  3963. enum SpecialProperties{
  3964. None = 0,
  3965. IsHidden = 1 << 1,
  3966. ShouldFail = 1 << 2,
  3967. MayFail = 1 << 3,
  3968. Throws = 1 << 4,
  3969. NonPortable = 1 << 5,
  3970. Benchmark = 1 << 6
  3971. };
  3972. TestCaseInfo( std::string const& _name,
  3973. std::string const& _className,
  3974. std::string const& _description,
  3975. std::vector<std::string> const& _tags,
  3976. SourceLineInfo const& _lineInfo );
  3977. friend void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags );
  3978. bool isHidden() const;
  3979. bool throws() const;
  3980. bool okToFail() const;
  3981. bool expectedToFail() const;
  3982. std::string tagsAsString() const;
  3983. std::string name;
  3984. std::string className;
  3985. std::string description;
  3986. std::vector<std::string> tags;
  3987. std::vector<std::string> lcaseTags;
  3988. SourceLineInfo lineInfo;
  3989. SpecialProperties properties;
  3990. };
  3991. class TestCase : public TestCaseInfo {
  3992. public:
  3993. TestCase( ITestInvoker* testCase, TestCaseInfo&& info );
  3994. TestCase withName( std::string const& _newName ) const;
  3995. void invoke() const;
  3996. TestCaseInfo const& getTestCaseInfo() const;
  3997. bool operator == ( TestCase const& other ) const;
  3998. bool operator < ( TestCase const& other ) const;
  3999. private:
  4000. std::shared_ptr<ITestInvoker> test;
  4001. };
  4002. TestCase makeTestCase( ITestInvoker* testCase,
  4003. std::string const& className,
  4004. NameAndTags const& nameAndTags,
  4005. SourceLineInfo const& lineInfo );
  4006. }
  4007. #ifdef __clang__
  4008. #pragma clang diagnostic pop
  4009. #endif
  4010. // end catch_test_case_info.h
  4011. // start catch_interfaces_runner.h
  4012. namespace Catch {
  4013. struct IRunner {
  4014. virtual ~IRunner();
  4015. virtual bool aborting() const = 0;
  4016. };
  4017. }
  4018. // end catch_interfaces_runner.h
  4019. #ifdef __OBJC__
  4020. // start catch_objc.hpp
  4021. #import <objc/runtime.h>
  4022. #include <string>
  4023. // NB. Any general catch headers included here must be included
  4024. // in catch.hpp first to make sure they are included by the single
  4025. // header for non obj-usage
  4026. ///////////////////////////////////////////////////////////////////////////////
  4027. // This protocol is really only here for (self) documenting purposes, since
  4028. // all its methods are optional.
  4029. @protocol OcFixture
  4030. @optional
  4031. -(void) setUp;
  4032. -(void) tearDown;
  4033. @end
  4034. namespace Catch {
  4035. class OcMethod : public ITestInvoker {
  4036. public:
  4037. OcMethod( Class cls, SEL sel ) : m_cls( cls ), m_sel( sel ) {}
  4038. virtual void invoke() const {
  4039. id obj = [[m_cls alloc] init];
  4040. performOptionalSelector( obj, @selector(setUp) );
  4041. performOptionalSelector( obj, m_sel );
  4042. performOptionalSelector( obj, @selector(tearDown) );
  4043. arcSafeRelease( obj );
  4044. }
  4045. private:
  4046. virtual ~OcMethod() {}
  4047. Class m_cls;
  4048. SEL m_sel;
  4049. };
  4050. namespace Detail{
  4051. inline std::string getAnnotation( Class cls,
  4052. std::string const& annotationName,
  4053. std::string const& testCaseName ) {
  4054. NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()];
  4055. SEL sel = NSSelectorFromString( selStr );
  4056. arcSafeRelease( selStr );
  4057. id value = performOptionalSelector( cls, sel );
  4058. if( value )
  4059. return [(NSString*)value UTF8String];
  4060. return "";
  4061. }
  4062. }
  4063. inline std::size_t registerTestMethods() {
  4064. std::size_t noTestMethods = 0;
  4065. int noClasses = objc_getClassList( nullptr, 0 );
  4066. Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc( sizeof(Class) * noClasses);
  4067. objc_getClassList( classes, noClasses );
  4068. for( int c = 0; c < noClasses; c++ ) {
  4069. Class cls = classes[c];
  4070. {
  4071. u_int count;
  4072. Method* methods = class_copyMethodList( cls, &count );
  4073. for( u_int m = 0; m < count ; m++ ) {
  4074. SEL selector = method_getName(methods[m]);
  4075. std::string methodName = sel_getName(selector);
  4076. if( startsWith( methodName, "Catch_TestCase_" ) ) {
  4077. std::string testCaseName = methodName.substr( 15 );
  4078. std::string name = Detail::getAnnotation( cls, "Name", testCaseName );
  4079. std::string desc = Detail::getAnnotation( cls, "Description", testCaseName );
  4080. const char* className = class_getName( cls );
  4081. getMutableRegistryHub().registerTest( makeTestCase( new OcMethod( cls, selector ), className, NameAndTags( name.c_str(), desc.c_str() ), SourceLineInfo("",0) ) );
  4082. noTestMethods++;
  4083. }
  4084. }
  4085. free(methods);
  4086. }
  4087. }
  4088. return noTestMethods;
  4089. }
  4090. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  4091. namespace Matchers {
  4092. namespace Impl {
  4093. namespace NSStringMatchers {
  4094. struct StringHolder : MatcherBase<NSString*>{
  4095. StringHolder( NSString* substr ) : m_substr( [substr copy] ){}
  4096. StringHolder( StringHolder const& other ) : m_substr( [other.m_substr copy] ){}
  4097. StringHolder() {
  4098. arcSafeRelease( m_substr );
  4099. }
  4100. bool match( NSString* str ) const override {
  4101. return false;
  4102. }
  4103. NSString* CATCH_ARC_STRONG m_substr;
  4104. };
  4105. struct Equals : StringHolder {
  4106. Equals( NSString* substr ) : StringHolder( substr ){}
  4107. bool match( NSString* str ) const override {
  4108. return (str != nil || m_substr == nil ) &&
  4109. [str isEqualToString:m_substr];
  4110. }
  4111. std::string describe() const override {
  4112. return "equals string: " + Catch::Detail::stringify( m_substr );
  4113. }
  4114. };
  4115. struct Contains : StringHolder {
  4116. Contains( NSString* substr ) : StringHolder( substr ){}
  4117. bool match( NSString* str ) const override {
  4118. return (str != nil || m_substr == nil ) &&
  4119. [str rangeOfString:m_substr].location != NSNotFound;
  4120. }
  4121. std::string describe() const override {
  4122. return "contains string: " + Catch::Detail::stringify( m_substr );
  4123. }
  4124. };
  4125. struct StartsWith : StringHolder {
  4126. StartsWith( NSString* substr ) : StringHolder( substr ){}
  4127. bool match( NSString* str ) const override {
  4128. return (str != nil || m_substr == nil ) &&
  4129. [str rangeOfString:m_substr].location == 0;
  4130. }
  4131. std::string describe() const override {
  4132. return "starts with: " + Catch::Detail::stringify( m_substr );
  4133. }
  4134. };
  4135. struct EndsWith : StringHolder {
  4136. EndsWith( NSString* substr ) : StringHolder( substr ){}
  4137. bool match( NSString* str ) const override {
  4138. return (str != nil || m_substr == nil ) &&
  4139. [str rangeOfString:m_substr].location == [str length] - [m_substr length];
  4140. }
  4141. std::string describe() const override {
  4142. return "ends with: " + Catch::Detail::stringify( m_substr );
  4143. }
  4144. };
  4145. } // namespace NSStringMatchers
  4146. } // namespace Impl
  4147. inline Impl::NSStringMatchers::Equals
  4148. Equals( NSString* substr ){ return Impl::NSStringMatchers::Equals( substr ); }
  4149. inline Impl::NSStringMatchers::Contains
  4150. Contains( NSString* substr ){ return Impl::NSStringMatchers::Contains( substr ); }
  4151. inline Impl::NSStringMatchers::StartsWith
  4152. StartsWith( NSString* substr ){ return Impl::NSStringMatchers::StartsWith( substr ); }
  4153. inline Impl::NSStringMatchers::EndsWith
  4154. EndsWith( NSString* substr ){ return Impl::NSStringMatchers::EndsWith( substr ); }
  4155. } // namespace Matchers
  4156. using namespace Matchers;
  4157. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  4158. } // namespace Catch
  4159. ///////////////////////////////////////////////////////////////////////////////
  4160. #define OC_MAKE_UNIQUE_NAME( root, uniqueSuffix ) root##uniqueSuffix
  4161. #define OC_TEST_CASE2( name, desc, uniqueSuffix ) \
  4162. +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Name_test_, uniqueSuffix ) \
  4163. { \
  4164. return @ name; \
  4165. } \
  4166. +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Description_test_, uniqueSuffix ) \
  4167. { \
  4168. return @ desc; \
  4169. } \
  4170. -(void) OC_MAKE_UNIQUE_NAME( Catch_TestCase_test_, uniqueSuffix )
  4171. #define OC_TEST_CASE( name, desc ) OC_TEST_CASE2( name, desc, __LINE__ )
  4172. // end catch_objc.hpp
  4173. #endif
  4174. // Benchmarking needs the externally-facing parts of reporters to work
  4175. #if defined(CATCH_CONFIG_EXTERNAL_INTERFACES) || defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  4176. // start catch_external_interfaces.h
  4177. // start catch_reporter_bases.hpp
  4178. // start catch_interfaces_reporter.h
  4179. // start catch_config.hpp
  4180. // start catch_test_spec_parser.h
  4181. #ifdef __clang__
  4182. #pragma clang diagnostic push
  4183. #pragma clang diagnostic ignored "-Wpadded"
  4184. #endif
  4185. // start catch_test_spec.h
  4186. #ifdef __clang__
  4187. #pragma clang diagnostic push
  4188. #pragma clang diagnostic ignored "-Wpadded"
  4189. #endif
  4190. // start catch_wildcard_pattern.h
  4191. namespace Catch
  4192. {
  4193. class WildcardPattern {
  4194. enum WildcardPosition {
  4195. NoWildcard = 0,
  4196. WildcardAtStart = 1,
  4197. WildcardAtEnd = 2,
  4198. WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd
  4199. };
  4200. public:
  4201. WildcardPattern( std::string const& pattern, CaseSensitive::Choice caseSensitivity );
  4202. virtual ~WildcardPattern() = default;
  4203. virtual bool matches( std::string const& str ) const;
  4204. private:
  4205. std::string normaliseString( std::string const& str ) const;
  4206. CaseSensitive::Choice m_caseSensitivity;
  4207. WildcardPosition m_wildcard = NoWildcard;
  4208. std::string m_pattern;
  4209. };
  4210. }
  4211. // end catch_wildcard_pattern.h
  4212. #include <string>
  4213. #include <vector>
  4214. #include <memory>
  4215. namespace Catch {
  4216. struct IConfig;
  4217. class TestSpec {
  4218. class Pattern {
  4219. public:
  4220. explicit Pattern( std::string const& name );
  4221. virtual ~Pattern();
  4222. virtual bool matches( TestCaseInfo const& testCase ) const = 0;
  4223. std::string const& name() const;
  4224. private:
  4225. std::string const m_name;
  4226. };
  4227. using PatternPtr = std::shared_ptr<Pattern>;
  4228. class NamePattern : public Pattern {
  4229. public:
  4230. explicit NamePattern( std::string const& name, std::string const& filterString );
  4231. bool matches( TestCaseInfo const& testCase ) const override;
  4232. private:
  4233. WildcardPattern m_wildcardPattern;
  4234. };
  4235. class TagPattern : public Pattern {
  4236. public:
  4237. explicit TagPattern( std::string const& tag, std::string const& filterString );
  4238. bool matches( TestCaseInfo const& testCase ) const override;
  4239. private:
  4240. std::string m_tag;
  4241. };
  4242. class ExcludedPattern : public Pattern {
  4243. public:
  4244. explicit ExcludedPattern( PatternPtr const& underlyingPattern );
  4245. bool matches( TestCaseInfo const& testCase ) const override;
  4246. private:
  4247. PatternPtr m_underlyingPattern;
  4248. };
  4249. struct Filter {
  4250. std::vector<PatternPtr> m_patterns;
  4251. bool matches( TestCaseInfo const& testCase ) const;
  4252. std::string name() const;
  4253. };
  4254. public:
  4255. struct FilterMatch {
  4256. std::string name;
  4257. std::vector<TestCase const*> tests;
  4258. };
  4259. using Matches = std::vector<FilterMatch>;
  4260. using vectorStrings = std::vector<std::string>;
  4261. bool hasFilters() const;
  4262. bool matches( TestCaseInfo const& testCase ) const;
  4263. Matches matchesByFilter( std::vector<TestCase> const& testCases, IConfig const& config ) const;
  4264. const vectorStrings & getInvalidArgs() const;
  4265. private:
  4266. std::vector<Filter> m_filters;
  4267. std::vector<std::string> m_invalidArgs;
  4268. friend class TestSpecParser;
  4269. };
  4270. }
  4271. #ifdef __clang__
  4272. #pragma clang diagnostic pop
  4273. #endif
  4274. // end catch_test_spec.h
  4275. // start catch_interfaces_tag_alias_registry.h
  4276. #include <string>
  4277. namespace Catch {
  4278. struct TagAlias;
  4279. struct ITagAliasRegistry {
  4280. virtual ~ITagAliasRegistry();
  4281. // Nullptr if not present
  4282. virtual TagAlias const* find( std::string const& alias ) const = 0;
  4283. virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const = 0;
  4284. static ITagAliasRegistry const& get();
  4285. };
  4286. } // end namespace Catch
  4287. // end catch_interfaces_tag_alias_registry.h
  4288. namespace Catch {
  4289. class TestSpecParser {
  4290. enum Mode{ None, Name, QuotedName, Tag, EscapedName };
  4291. Mode m_mode = None;
  4292. Mode lastMode = None;
  4293. bool m_exclusion = false;
  4294. std::size_t m_pos = 0;
  4295. std::size_t m_realPatternPos = 0;
  4296. std::string m_arg;
  4297. std::string m_substring;
  4298. std::string m_patternName;
  4299. std::vector<std::size_t> m_escapeChars;
  4300. TestSpec::Filter m_currentFilter;
  4301. TestSpec m_testSpec;
  4302. ITagAliasRegistry const* m_tagAliases = nullptr;
  4303. public:
  4304. TestSpecParser( ITagAliasRegistry const& tagAliases );
  4305. TestSpecParser& parse( std::string const& arg );
  4306. TestSpec testSpec();
  4307. private:
  4308. bool visitChar( char c );
  4309. void startNewMode( Mode mode );
  4310. bool processNoneChar( char c );
  4311. void processNameChar( char c );
  4312. bool processOtherChar( char c );
  4313. void endMode();
  4314. void escape();
  4315. bool isControlChar( char c ) const;
  4316. void saveLastMode();
  4317. void revertBackToLastMode();
  4318. void addFilter();
  4319. bool separate();
  4320. // Handles common preprocessing of the pattern for name/tag patterns
  4321. std::string preprocessPattern();
  4322. // Adds the current pattern as a test name
  4323. void addNamePattern();
  4324. // Adds the current pattern as a tag
  4325. void addTagPattern();
  4326. inline void addCharToPattern(char c) {
  4327. m_substring += c;
  4328. m_patternName += c;
  4329. m_realPatternPos++;
  4330. }
  4331. };
  4332. TestSpec parseTestSpec( std::string const& arg );
  4333. } // namespace Catch
  4334. #ifdef __clang__
  4335. #pragma clang diagnostic pop
  4336. #endif
  4337. // end catch_test_spec_parser.h
  4338. // Libstdc++ doesn't like incomplete classes for unique_ptr
  4339. #include <memory>
  4340. #include <vector>
  4341. #include <string>
  4342. #ifndef CATCH_CONFIG_CONSOLE_WIDTH
  4343. #define CATCH_CONFIG_CONSOLE_WIDTH 80
  4344. #endif
  4345. namespace Catch {
  4346. struct IStream;
  4347. struct ConfigData {
  4348. bool listTests = false;
  4349. bool listTags = false;
  4350. bool listReporters = false;
  4351. bool listTestNamesOnly = false;
  4352. bool showSuccessfulTests = false;
  4353. bool shouldDebugBreak = false;
  4354. bool noThrow = false;
  4355. bool showHelp = false;
  4356. bool showInvisibles = false;
  4357. bool filenamesAsTags = false;
  4358. bool libIdentify = false;
  4359. int abortAfter = -1;
  4360. unsigned int rngSeed = 0;
  4361. bool benchmarkNoAnalysis = false;
  4362. unsigned int benchmarkSamples = 100;
  4363. double benchmarkConfidenceInterval = 0.95;
  4364. unsigned int benchmarkResamples = 100000;
  4365. std::chrono::milliseconds::rep benchmarkWarmupTime = 100;
  4366. Verbosity verbosity = Verbosity::Normal;
  4367. WarnAbout::What warnings = WarnAbout::Nothing;
  4368. ShowDurations::OrNot showDurations = ShowDurations::DefaultForReporter;
  4369. double minDuration = -1;
  4370. RunTests::InWhatOrder runOrder = RunTests::InDeclarationOrder;
  4371. UseColour::YesOrNo useColour = UseColour::Auto;
  4372. WaitForKeypress::When waitForKeypress = WaitForKeypress::Never;
  4373. std::string outputFilename;
  4374. std::string name;
  4375. std::string processName;
  4376. #ifndef CATCH_CONFIG_DEFAULT_REPORTER
  4377. #define CATCH_CONFIG_DEFAULT_REPORTER "console"
  4378. #endif
  4379. std::string reporterName = CATCH_CONFIG_DEFAULT_REPORTER;
  4380. #undef CATCH_CONFIG_DEFAULT_REPORTER
  4381. std::vector<std::string> testsOrTags;
  4382. std::vector<std::string> sectionsToRun;
  4383. };
  4384. class Config : public IConfig {
  4385. public:
  4386. Config() = default;
  4387. Config( ConfigData const& data );
  4388. virtual ~Config() = default;
  4389. std::string const& getFilename() const;
  4390. bool listTests() const;
  4391. bool listTestNamesOnly() const;
  4392. bool listTags() const;
  4393. bool listReporters() const;
  4394. std::string getProcessName() const;
  4395. std::string const& getReporterName() const;
  4396. std::vector<std::string> const& getTestsOrTags() const override;
  4397. std::vector<std::string> const& getSectionsToRun() const override;
  4398. TestSpec const& testSpec() const override;
  4399. bool hasTestFilters() const override;
  4400. bool showHelp() const;
  4401. // IConfig interface
  4402. bool allowThrows() const override;
  4403. std::ostream& stream() const override;
  4404. std::string name() const override;
  4405. bool includeSuccessfulResults() const override;
  4406. bool warnAboutMissingAssertions() const override;
  4407. bool warnAboutNoTests() const override;
  4408. ShowDurations::OrNot showDurations() const override;
  4409. double minDuration() const override;
  4410. RunTests::InWhatOrder runOrder() const override;
  4411. unsigned int rngSeed() const override;
  4412. UseColour::YesOrNo useColour() const override;
  4413. bool shouldDebugBreak() const override;
  4414. int abortAfter() const override;
  4415. bool showInvisibles() const override;
  4416. Verbosity verbosity() const override;
  4417. bool benchmarkNoAnalysis() const override;
  4418. int benchmarkSamples() const override;
  4419. double benchmarkConfidenceInterval() const override;
  4420. unsigned int benchmarkResamples() const override;
  4421. std::chrono::milliseconds benchmarkWarmupTime() const override;
  4422. private:
  4423. IStream const* openStream();
  4424. ConfigData m_data;
  4425. std::unique_ptr<IStream const> m_stream;
  4426. TestSpec m_testSpec;
  4427. bool m_hasTestFilters = false;
  4428. };
  4429. } // end namespace Catch
  4430. // end catch_config.hpp
  4431. // start catch_assertionresult.h
  4432. #include <string>
  4433. namespace Catch {
  4434. struct AssertionResultData
  4435. {
  4436. AssertionResultData() = delete;
  4437. AssertionResultData( ResultWas::OfType _resultType, LazyExpression const& _lazyExpression );
  4438. std::string message;
  4439. mutable std::string reconstructedExpression;
  4440. LazyExpression lazyExpression;
  4441. ResultWas::OfType resultType;
  4442. std::string reconstructExpression() const;
  4443. };
  4444. class AssertionResult {
  4445. public:
  4446. AssertionResult() = delete;
  4447. AssertionResult( AssertionInfo const& info, AssertionResultData const& data );
  4448. bool isOk() const;
  4449. bool succeeded() const;
  4450. ResultWas::OfType getResultType() const;
  4451. bool hasExpression() const;
  4452. bool hasMessage() const;
  4453. std::string getExpression() const;
  4454. std::string getExpressionInMacro() const;
  4455. bool hasExpandedExpression() const;
  4456. std::string getExpandedExpression() const;
  4457. std::string getMessage() const;
  4458. SourceLineInfo getSourceInfo() const;
  4459. StringRef getTestMacroName() const;
  4460. //protected:
  4461. AssertionInfo m_info;
  4462. AssertionResultData m_resultData;
  4463. };
  4464. } // end namespace Catch
  4465. // end catch_assertionresult.h
  4466. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  4467. // start catch_estimate.hpp
  4468. // Statistics estimates
  4469. namespace Catch {
  4470. namespace Benchmark {
  4471. template <typename Duration>
  4472. struct Estimate {
  4473. Duration point;
  4474. Duration lower_bound;
  4475. Duration upper_bound;
  4476. double confidence_interval;
  4477. template <typename Duration2>
  4478. operator Estimate<Duration2>() const {
  4479. return { point, lower_bound, upper_bound, confidence_interval };
  4480. }
  4481. };
  4482. } // namespace Benchmark
  4483. } // namespace Catch
  4484. // end catch_estimate.hpp
  4485. // start catch_outlier_classification.hpp
  4486. // Outlier information
  4487. namespace Catch {
  4488. namespace Benchmark {
  4489. struct OutlierClassification {
  4490. int samples_seen = 0;
  4491. int low_severe = 0; // more than 3 times IQR below Q1
  4492. int low_mild = 0; // 1.5 to 3 times IQR below Q1
  4493. int high_mild = 0; // 1.5 to 3 times IQR above Q3
  4494. int high_severe = 0; // more than 3 times IQR above Q3
  4495. int total() const {
  4496. return low_severe + low_mild + high_mild + high_severe;
  4497. }
  4498. };
  4499. } // namespace Benchmark
  4500. } // namespace Catch
  4501. // end catch_outlier_classification.hpp
  4502. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  4503. #include <string>
  4504. #include <iosfwd>
  4505. #include <map>
  4506. #include <set>
  4507. #include <memory>
  4508. #include <algorithm>
  4509. namespace Catch {
  4510. struct ReporterConfig {
  4511. explicit ReporterConfig( IConfigPtr const& _fullConfig );
  4512. ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream );
  4513. std::ostream& stream() const;
  4514. IConfigPtr fullConfig() const;
  4515. private:
  4516. std::ostream* m_stream;
  4517. IConfigPtr m_fullConfig;
  4518. };
  4519. struct ReporterPreferences {
  4520. bool shouldRedirectStdOut = false;
  4521. bool shouldReportAllAssertions = false;
  4522. };
  4523. template<typename T>
  4524. struct LazyStat : Option<T> {
  4525. LazyStat& operator=( T const& _value ) {
  4526. Option<T>::operator=( _value );
  4527. used = false;
  4528. return *this;
  4529. }
  4530. void reset() {
  4531. Option<T>::reset();
  4532. used = false;
  4533. }
  4534. bool used = false;
  4535. };
  4536. struct TestRunInfo {
  4537. TestRunInfo( std::string const& _name );
  4538. std::string name;
  4539. };
  4540. struct GroupInfo {
  4541. GroupInfo( std::string const& _name,
  4542. std::size_t _groupIndex,
  4543. std::size_t _groupsCount );
  4544. std::string name;
  4545. std::size_t groupIndex;
  4546. std::size_t groupsCounts;
  4547. };
  4548. struct AssertionStats {
  4549. AssertionStats( AssertionResult const& _assertionResult,
  4550. std::vector<MessageInfo> const& _infoMessages,
  4551. Totals const& _totals );
  4552. AssertionStats( AssertionStats const& ) = default;
  4553. AssertionStats( AssertionStats && ) = default;
  4554. AssertionStats& operator = ( AssertionStats const& ) = delete;
  4555. AssertionStats& operator = ( AssertionStats && ) = delete;
  4556. virtual ~AssertionStats();
  4557. AssertionResult assertionResult;
  4558. std::vector<MessageInfo> infoMessages;
  4559. Totals totals;
  4560. };
  4561. struct SectionStats {
  4562. SectionStats( SectionInfo const& _sectionInfo,
  4563. Counts const& _assertions,
  4564. double _durationInSeconds,
  4565. bool _missingAssertions );
  4566. SectionStats( SectionStats const& ) = default;
  4567. SectionStats( SectionStats && ) = default;
  4568. SectionStats& operator = ( SectionStats const& ) = default;
  4569. SectionStats& operator = ( SectionStats && ) = default;
  4570. virtual ~SectionStats();
  4571. SectionInfo sectionInfo;
  4572. Counts assertions;
  4573. double durationInSeconds;
  4574. bool missingAssertions;
  4575. };
  4576. struct TestCaseStats {
  4577. TestCaseStats( TestCaseInfo const& _testInfo,
  4578. Totals const& _totals,
  4579. std::string const& _stdOut,
  4580. std::string const& _stdErr,
  4581. bool _aborting );
  4582. TestCaseStats( TestCaseStats const& ) = default;
  4583. TestCaseStats( TestCaseStats && ) = default;
  4584. TestCaseStats& operator = ( TestCaseStats const& ) = default;
  4585. TestCaseStats& operator = ( TestCaseStats && ) = default;
  4586. virtual ~TestCaseStats();
  4587. TestCaseInfo testInfo;
  4588. Totals totals;
  4589. std::string stdOut;
  4590. std::string stdErr;
  4591. bool aborting;
  4592. };
  4593. struct TestGroupStats {
  4594. TestGroupStats( GroupInfo const& _groupInfo,
  4595. Totals const& _totals,
  4596. bool _aborting );
  4597. TestGroupStats( GroupInfo const& _groupInfo );
  4598. TestGroupStats( TestGroupStats const& ) = default;
  4599. TestGroupStats( TestGroupStats && ) = default;
  4600. TestGroupStats& operator = ( TestGroupStats const& ) = default;
  4601. TestGroupStats& operator = ( TestGroupStats && ) = default;
  4602. virtual ~TestGroupStats();
  4603. GroupInfo groupInfo;
  4604. Totals totals;
  4605. bool aborting;
  4606. };
  4607. struct TestRunStats {
  4608. TestRunStats( TestRunInfo const& _runInfo,
  4609. Totals const& _totals,
  4610. bool _aborting );
  4611. TestRunStats( TestRunStats const& ) = default;
  4612. TestRunStats( TestRunStats && ) = default;
  4613. TestRunStats& operator = ( TestRunStats const& ) = default;
  4614. TestRunStats& operator = ( TestRunStats && ) = default;
  4615. virtual ~TestRunStats();
  4616. TestRunInfo runInfo;
  4617. Totals totals;
  4618. bool aborting;
  4619. };
  4620. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  4621. struct BenchmarkInfo {
  4622. std::string name;
  4623. double estimatedDuration;
  4624. int iterations;
  4625. int samples;
  4626. unsigned int resamples;
  4627. double clockResolution;
  4628. double clockCost;
  4629. };
  4630. template <class Duration>
  4631. struct BenchmarkStats {
  4632. BenchmarkInfo info;
  4633. std::vector<Duration> samples;
  4634. Benchmark::Estimate<Duration> mean;
  4635. Benchmark::Estimate<Duration> standardDeviation;
  4636. Benchmark::OutlierClassification outliers;
  4637. double outlierVariance;
  4638. template <typename Duration2>
  4639. operator BenchmarkStats<Duration2>() const {
  4640. std::vector<Duration2> samples2;
  4641. samples2.reserve(samples.size());
  4642. std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration d) { return Duration2(d); });
  4643. return {
  4644. info,
  4645. std::move(samples2),
  4646. mean,
  4647. standardDeviation,
  4648. outliers,
  4649. outlierVariance,
  4650. };
  4651. }
  4652. };
  4653. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  4654. struct IStreamingReporter {
  4655. virtual ~IStreamingReporter() = default;
  4656. // Implementing class must also provide the following static methods:
  4657. // static std::string getDescription();
  4658. // static std::set<Verbosity> getSupportedVerbosities()
  4659. virtual ReporterPreferences getPreferences() const = 0;
  4660. virtual void noMatchingTestCases( std::string const& spec ) = 0;
  4661. virtual void reportInvalidArguments(std::string const&) {}
  4662. virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0;
  4663. virtual void testGroupStarting( GroupInfo const& groupInfo ) = 0;
  4664. virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0;
  4665. virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0;
  4666. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  4667. virtual void benchmarkPreparing( std::string const& ) {}
  4668. virtual void benchmarkStarting( BenchmarkInfo const& ) {}
  4669. virtual void benchmarkEnded( BenchmarkStats<> const& ) {}
  4670. virtual void benchmarkFailed( std::string const& ) {}
  4671. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  4672. virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0;
  4673. // The return value indicates if the messages buffer should be cleared:
  4674. virtual bool assertionEnded( AssertionStats const& assertionStats ) = 0;
  4675. virtual void sectionEnded( SectionStats const& sectionStats ) = 0;
  4676. virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0;
  4677. virtual void testGroupEnded( TestGroupStats const& testGroupStats ) = 0;
  4678. virtual void testRunEnded( TestRunStats const& testRunStats ) = 0;
  4679. virtual void skipTest( TestCaseInfo const& testInfo ) = 0;
  4680. // Default empty implementation provided
  4681. virtual void fatalErrorEncountered( StringRef name );
  4682. virtual bool isMulti() const;
  4683. };
  4684. using IStreamingReporterPtr = std::unique_ptr<IStreamingReporter>;
  4685. struct IReporterFactory {
  4686. virtual ~IReporterFactory();
  4687. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const = 0;
  4688. virtual std::string getDescription() const = 0;
  4689. };
  4690. using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
  4691. struct IReporterRegistry {
  4692. using FactoryMap = std::map<std::string, IReporterFactoryPtr>;
  4693. using Listeners = std::vector<IReporterFactoryPtr>;
  4694. virtual ~IReporterRegistry();
  4695. virtual IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const = 0;
  4696. virtual FactoryMap const& getFactories() const = 0;
  4697. virtual Listeners const& getListeners() const = 0;
  4698. };
  4699. } // end namespace Catch
  4700. // end catch_interfaces_reporter.h
  4701. #include <algorithm>
  4702. #include <cstring>
  4703. #include <cfloat>
  4704. #include <cstdio>
  4705. #include <cassert>
  4706. #include <memory>
  4707. #include <ostream>
  4708. namespace Catch {
  4709. void prepareExpandedExpression(AssertionResult& result);
  4710. // Returns double formatted as %.3f (format expected on output)
  4711. std::string getFormattedDuration( double duration );
  4712. //! Should the reporter show
  4713. bool shouldShowDuration( IConfig const& config, double duration );
  4714. std::string serializeFilters( std::vector<std::string> const& container );
  4715. template<typename DerivedT>
  4716. struct StreamingReporterBase : IStreamingReporter {
  4717. StreamingReporterBase( ReporterConfig const& _config )
  4718. : m_config( _config.fullConfig() ),
  4719. stream( _config.stream() )
  4720. {
  4721. m_reporterPrefs.shouldRedirectStdOut = false;
  4722. if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
  4723. CATCH_ERROR( "Verbosity level not supported by this reporter" );
  4724. }
  4725. ReporterPreferences getPreferences() const override {
  4726. return m_reporterPrefs;
  4727. }
  4728. static std::set<Verbosity> getSupportedVerbosities() {
  4729. return { Verbosity::Normal };
  4730. }
  4731. ~StreamingReporterBase() override = default;
  4732. void noMatchingTestCases(std::string const&) override {}
  4733. void reportInvalidArguments(std::string const&) override {}
  4734. void testRunStarting(TestRunInfo const& _testRunInfo) override {
  4735. currentTestRunInfo = _testRunInfo;
  4736. }
  4737. void testGroupStarting(GroupInfo const& _groupInfo) override {
  4738. currentGroupInfo = _groupInfo;
  4739. }
  4740. void testCaseStarting(TestCaseInfo const& _testInfo) override {
  4741. currentTestCaseInfo = _testInfo;
  4742. }
  4743. void sectionStarting(SectionInfo const& _sectionInfo) override {
  4744. m_sectionStack.push_back(_sectionInfo);
  4745. }
  4746. void sectionEnded(SectionStats const& /* _sectionStats */) override {
  4747. m_sectionStack.pop_back();
  4748. }
  4749. void testCaseEnded(TestCaseStats const& /* _testCaseStats */) override {
  4750. currentTestCaseInfo.reset();
  4751. }
  4752. void testGroupEnded(TestGroupStats const& /* _testGroupStats */) override {
  4753. currentGroupInfo.reset();
  4754. }
  4755. void testRunEnded(TestRunStats const& /* _testRunStats */) override {
  4756. currentTestCaseInfo.reset();
  4757. currentGroupInfo.reset();
  4758. currentTestRunInfo.reset();
  4759. }
  4760. void skipTest(TestCaseInfo const&) override {
  4761. // Don't do anything with this by default.
  4762. // It can optionally be overridden in the derived class.
  4763. }
  4764. IConfigPtr m_config;
  4765. std::ostream& stream;
  4766. LazyStat<TestRunInfo> currentTestRunInfo;
  4767. LazyStat<GroupInfo> currentGroupInfo;
  4768. LazyStat<TestCaseInfo> currentTestCaseInfo;
  4769. std::vector<SectionInfo> m_sectionStack;
  4770. ReporterPreferences m_reporterPrefs;
  4771. };
  4772. template<typename DerivedT>
  4773. struct CumulativeReporterBase : IStreamingReporter {
  4774. template<typename T, typename ChildNodeT>
  4775. struct Node {
  4776. explicit Node( T const& _value ) : value( _value ) {}
  4777. virtual ~Node() {}
  4778. using ChildNodes = std::vector<std::shared_ptr<ChildNodeT>>;
  4779. T value;
  4780. ChildNodes children;
  4781. };
  4782. struct SectionNode {
  4783. explicit SectionNode(SectionStats const& _stats) : stats(_stats) {}
  4784. virtual ~SectionNode() = default;
  4785. bool operator == (SectionNode const& other) const {
  4786. return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;
  4787. }
  4788. bool operator == (std::shared_ptr<SectionNode> const& other) const {
  4789. return operator==(*other);
  4790. }
  4791. SectionStats stats;
  4792. using ChildSections = std::vector<std::shared_ptr<SectionNode>>;
  4793. using Assertions = std::vector<AssertionStats>;
  4794. ChildSections childSections;
  4795. Assertions assertions;
  4796. std::string stdOut;
  4797. std::string stdErr;
  4798. };
  4799. struct BySectionInfo {
  4800. BySectionInfo( SectionInfo const& other ) : m_other( other ) {}
  4801. BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {}
  4802. bool operator() (std::shared_ptr<SectionNode> const& node) const {
  4803. return ((node->stats.sectionInfo.name == m_other.name) &&
  4804. (node->stats.sectionInfo.lineInfo == m_other.lineInfo));
  4805. }
  4806. void operator=(BySectionInfo const&) = delete;
  4807. private:
  4808. SectionInfo const& m_other;
  4809. };
  4810. using TestCaseNode = Node<TestCaseStats, SectionNode>;
  4811. using TestGroupNode = Node<TestGroupStats, TestCaseNode>;
  4812. using TestRunNode = Node<TestRunStats, TestGroupNode>;
  4813. CumulativeReporterBase( ReporterConfig const& _config )
  4814. : m_config( _config.fullConfig() ),
  4815. stream( _config.stream() )
  4816. {
  4817. m_reporterPrefs.shouldRedirectStdOut = false;
  4818. if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
  4819. CATCH_ERROR( "Verbosity level not supported by this reporter" );
  4820. }
  4821. ~CumulativeReporterBase() override = default;
  4822. ReporterPreferences getPreferences() const override {
  4823. return m_reporterPrefs;
  4824. }
  4825. static std::set<Verbosity> getSupportedVerbosities() {
  4826. return { Verbosity::Normal };
  4827. }
  4828. void testRunStarting( TestRunInfo const& ) override {}
  4829. void testGroupStarting( GroupInfo const& ) override {}
  4830. void testCaseStarting( TestCaseInfo const& ) override {}
  4831. void sectionStarting( SectionInfo const& sectionInfo ) override {
  4832. SectionStats incompleteStats( sectionInfo, Counts(), 0, false );
  4833. std::shared_ptr<SectionNode> node;
  4834. if( m_sectionStack.empty() ) {
  4835. if( !m_rootSection )
  4836. m_rootSection = std::make_shared<SectionNode>( incompleteStats );
  4837. node = m_rootSection;
  4838. }
  4839. else {
  4840. SectionNode& parentNode = *m_sectionStack.back();
  4841. auto it =
  4842. std::find_if( parentNode.childSections.begin(),
  4843. parentNode.childSections.end(),
  4844. BySectionInfo( sectionInfo ) );
  4845. if( it == parentNode.childSections.end() ) {
  4846. node = std::make_shared<SectionNode>( incompleteStats );
  4847. parentNode.childSections.push_back( node );
  4848. }
  4849. else
  4850. node = *it;
  4851. }
  4852. m_sectionStack.push_back( node );
  4853. m_deepestSection = std::move(node);
  4854. }
  4855. void assertionStarting(AssertionInfo const&) override {}
  4856. bool assertionEnded(AssertionStats const& assertionStats) override {
  4857. assert(!m_sectionStack.empty());
  4858. // AssertionResult holds a pointer to a temporary DecomposedExpression,
  4859. // which getExpandedExpression() calls to build the expression string.
  4860. // Our section stack copy of the assertionResult will likely outlive the
  4861. // temporary, so it must be expanded or discarded now to avoid calling
  4862. // a destroyed object later.
  4863. prepareExpandedExpression(const_cast<AssertionResult&>( assertionStats.assertionResult ) );
  4864. SectionNode& sectionNode = *m_sectionStack.back();
  4865. sectionNode.assertions.push_back(assertionStats);
  4866. return true;
  4867. }
  4868. void sectionEnded(SectionStats const& sectionStats) override {
  4869. assert(!m_sectionStack.empty());
  4870. SectionNode& node = *m_sectionStack.back();
  4871. node.stats = sectionStats;
  4872. m_sectionStack.pop_back();
  4873. }
  4874. void testCaseEnded(TestCaseStats const& testCaseStats) override {
  4875. auto node = std::make_shared<TestCaseNode>(testCaseStats);
  4876. assert(m_sectionStack.size() == 0);
  4877. node->children.push_back(m_rootSection);
  4878. m_testCases.push_back(node);
  4879. m_rootSection.reset();
  4880. assert(m_deepestSection);
  4881. m_deepestSection->stdOut = testCaseStats.stdOut;
  4882. m_deepestSection->stdErr = testCaseStats.stdErr;
  4883. }
  4884. void testGroupEnded(TestGroupStats const& testGroupStats) override {
  4885. auto node = std::make_shared<TestGroupNode>(testGroupStats);
  4886. node->children.swap(m_testCases);
  4887. m_testGroups.push_back(node);
  4888. }
  4889. void testRunEnded(TestRunStats const& testRunStats) override {
  4890. auto node = std::make_shared<TestRunNode>(testRunStats);
  4891. node->children.swap(m_testGroups);
  4892. m_testRuns.push_back(node);
  4893. testRunEndedCumulative();
  4894. }
  4895. virtual void testRunEndedCumulative() = 0;
  4896. void skipTest(TestCaseInfo const&) override {}
  4897. IConfigPtr m_config;
  4898. std::ostream& stream;
  4899. std::vector<AssertionStats> m_assertions;
  4900. std::vector<std::vector<std::shared_ptr<SectionNode>>> m_sections;
  4901. std::vector<std::shared_ptr<TestCaseNode>> m_testCases;
  4902. std::vector<std::shared_ptr<TestGroupNode>> m_testGroups;
  4903. std::vector<std::shared_ptr<TestRunNode>> m_testRuns;
  4904. std::shared_ptr<SectionNode> m_rootSection;
  4905. std::shared_ptr<SectionNode> m_deepestSection;
  4906. std::vector<std::shared_ptr<SectionNode>> m_sectionStack;
  4907. ReporterPreferences m_reporterPrefs;
  4908. };
  4909. template<char C>
  4910. char const* getLineOfChars() {
  4911. static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
  4912. if( !*line ) {
  4913. std::memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 );
  4914. line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0;
  4915. }
  4916. return line;
  4917. }
  4918. struct TestEventListenerBase : StreamingReporterBase<TestEventListenerBase> {
  4919. TestEventListenerBase( ReporterConfig const& _config );
  4920. static std::set<Verbosity> getSupportedVerbosities();
  4921. void assertionStarting(AssertionInfo const&) override;
  4922. bool assertionEnded(AssertionStats const&) override;
  4923. };
  4924. } // end namespace Catch
  4925. // end catch_reporter_bases.hpp
  4926. // start catch_console_colour.h
  4927. namespace Catch {
  4928. struct Colour {
  4929. enum Code {
  4930. None = 0,
  4931. White,
  4932. Red,
  4933. Green,
  4934. Blue,
  4935. Cyan,
  4936. Yellow,
  4937. Grey,
  4938. Bright = 0x10,
  4939. BrightRed = Bright | Red,
  4940. BrightGreen = Bright | Green,
  4941. LightGrey = Bright | Grey,
  4942. BrightWhite = Bright | White,
  4943. BrightYellow = Bright | Yellow,
  4944. // By intention
  4945. FileName = LightGrey,
  4946. Warning = BrightYellow,
  4947. ResultError = BrightRed,
  4948. ResultSuccess = BrightGreen,
  4949. ResultExpectedFailure = Warning,
  4950. Error = BrightRed,
  4951. Success = Green,
  4952. OriginalExpression = Cyan,
  4953. ReconstructedExpression = BrightYellow,
  4954. SecondaryText = LightGrey,
  4955. Headers = White
  4956. };
  4957. // Use constructed object for RAII guard
  4958. Colour( Code _colourCode );
  4959. Colour( Colour&& other ) noexcept;
  4960. Colour& operator=( Colour&& other ) noexcept;
  4961. ~Colour();
  4962. // Use static method for one-shot changes
  4963. static void use( Code _colourCode );
  4964. private:
  4965. bool m_moved = false;
  4966. };
  4967. std::ostream& operator << ( std::ostream& os, Colour const& );
  4968. } // end namespace Catch
  4969. // end catch_console_colour.h
  4970. // start catch_reporter_registrars.hpp
  4971. namespace Catch {
  4972. template<typename T>
  4973. class ReporterRegistrar {
  4974. class ReporterFactory : public IReporterFactory {
  4975. IStreamingReporterPtr create( ReporterConfig const& config ) const override {
  4976. return std::unique_ptr<T>( new T( config ) );
  4977. }
  4978. std::string getDescription() const override {
  4979. return T::getDescription();
  4980. }
  4981. };
  4982. public:
  4983. explicit ReporterRegistrar( std::string const& name ) {
  4984. getMutableRegistryHub().registerReporter( name, std::make_shared<ReporterFactory>() );
  4985. }
  4986. };
  4987. template<typename T>
  4988. class ListenerRegistrar {
  4989. class ListenerFactory : public IReporterFactory {
  4990. IStreamingReporterPtr create( ReporterConfig const& config ) const override {
  4991. return std::unique_ptr<T>( new T( config ) );
  4992. }
  4993. std::string getDescription() const override {
  4994. return std::string();
  4995. }
  4996. };
  4997. public:
  4998. ListenerRegistrar() {
  4999. getMutableRegistryHub().registerListener( std::make_shared<ListenerFactory>() );
  5000. }
  5001. };
  5002. }
  5003. #if !defined(CATCH_CONFIG_DISABLE)
  5004. #define CATCH_REGISTER_REPORTER( name, reporterType ) \
  5005. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
  5006. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  5007. namespace{ Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); } \
  5008. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
  5009. #define CATCH_REGISTER_LISTENER( listenerType ) \
  5010. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
  5011. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  5012. namespace{ Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; } \
  5013. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
  5014. #else // CATCH_CONFIG_DISABLE
  5015. #define CATCH_REGISTER_REPORTER(name, reporterType)
  5016. #define CATCH_REGISTER_LISTENER(listenerType)
  5017. #endif // CATCH_CONFIG_DISABLE
  5018. // end catch_reporter_registrars.hpp
  5019. // Allow users to base their work off existing reporters
  5020. // start catch_reporter_compact.h
  5021. namespace Catch {
  5022. struct CompactReporter : StreamingReporterBase<CompactReporter> {
  5023. using StreamingReporterBase::StreamingReporterBase;
  5024. ~CompactReporter() override;
  5025. static std::string getDescription();
  5026. void noMatchingTestCases(std::string const& spec) override;
  5027. void assertionStarting(AssertionInfo const&) override;
  5028. bool assertionEnded(AssertionStats const& _assertionStats) override;
  5029. void sectionEnded(SectionStats const& _sectionStats) override;
  5030. void testRunEnded(TestRunStats const& _testRunStats) override;
  5031. };
  5032. } // end namespace Catch
  5033. // end catch_reporter_compact.h
  5034. // start catch_reporter_console.h
  5035. #if defined(_MSC_VER)
  5036. #pragma warning(push)
  5037. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  5038. // Note that 4062 (not all labels are handled
  5039. // and default is missing) is enabled
  5040. #endif
  5041. namespace Catch {
  5042. // Fwd decls
  5043. struct SummaryColumn;
  5044. class TablePrinter;
  5045. struct ConsoleReporter : StreamingReporterBase<ConsoleReporter> {
  5046. std::unique_ptr<TablePrinter> m_tablePrinter;
  5047. ConsoleReporter(ReporterConfig const& config);
  5048. ~ConsoleReporter() override;
  5049. static std::string getDescription();
  5050. void noMatchingTestCases(std::string const& spec) override;
  5051. void reportInvalidArguments(std::string const&arg) override;
  5052. void assertionStarting(AssertionInfo const&) override;
  5053. bool assertionEnded(AssertionStats const& _assertionStats) override;
  5054. void sectionStarting(SectionInfo const& _sectionInfo) override;
  5055. void sectionEnded(SectionStats const& _sectionStats) override;
  5056. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  5057. void benchmarkPreparing(std::string const& name) override;
  5058. void benchmarkStarting(BenchmarkInfo const& info) override;
  5059. void benchmarkEnded(BenchmarkStats<> const& stats) override;
  5060. void benchmarkFailed(std::string const& error) override;
  5061. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  5062. void testCaseEnded(TestCaseStats const& _testCaseStats) override;
  5063. void testGroupEnded(TestGroupStats const& _testGroupStats) override;
  5064. void testRunEnded(TestRunStats const& _testRunStats) override;
  5065. void testRunStarting(TestRunInfo const& _testRunInfo) override;
  5066. private:
  5067. void lazyPrint();
  5068. void lazyPrintWithoutClosingBenchmarkTable();
  5069. void lazyPrintRunInfo();
  5070. void lazyPrintGroupInfo();
  5071. void printTestCaseAndSectionHeader();
  5072. void printClosedHeader(std::string const& _name);
  5073. void printOpenHeader(std::string const& _name);
  5074. // if string has a : in first line will set indent to follow it on
  5075. // subsequent lines
  5076. void printHeaderString(std::string const& _string, std::size_t indent = 0);
  5077. void printTotals(Totals const& totals);
  5078. void printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row);
  5079. void printTotalsDivider(Totals const& totals);
  5080. void printSummaryDivider();
  5081. void printTestFilters();
  5082. private:
  5083. bool m_headerPrinted = false;
  5084. };
  5085. } // end namespace Catch
  5086. #if defined(_MSC_VER)
  5087. #pragma warning(pop)
  5088. #endif
  5089. // end catch_reporter_console.h
  5090. // start catch_reporter_junit.h
  5091. // start catch_xmlwriter.h
  5092. #include <vector>
  5093. namespace Catch {
  5094. enum class XmlFormatting {
  5095. None = 0x00,
  5096. Indent = 0x01,
  5097. Newline = 0x02,
  5098. };
  5099. XmlFormatting operator | (XmlFormatting lhs, XmlFormatting rhs);
  5100. XmlFormatting operator & (XmlFormatting lhs, XmlFormatting rhs);
  5101. class XmlEncode {
  5102. public:
  5103. enum ForWhat { ForTextNodes, ForAttributes };
  5104. XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes );
  5105. void encodeTo( std::ostream& os ) const;
  5106. friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode );
  5107. private:
  5108. std::string m_str;
  5109. ForWhat m_forWhat;
  5110. };
  5111. class XmlWriter {
  5112. public:
  5113. class ScopedElement {
  5114. public:
  5115. ScopedElement( XmlWriter* writer, XmlFormatting fmt );
  5116. ScopedElement( ScopedElement&& other ) noexcept;
  5117. ScopedElement& operator=( ScopedElement&& other ) noexcept;
  5118. ~ScopedElement();
  5119. ScopedElement& writeText( std::string const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent );
  5120. template<typename T>
  5121. ScopedElement& writeAttribute( std::string const& name, T const& attribute ) {
  5122. m_writer->writeAttribute( name, attribute );
  5123. return *this;
  5124. }
  5125. private:
  5126. mutable XmlWriter* m_writer = nullptr;
  5127. XmlFormatting m_fmt;
  5128. };
  5129. XmlWriter( std::ostream& os = Catch::cout() );
  5130. ~XmlWriter();
  5131. XmlWriter( XmlWriter const& ) = delete;
  5132. XmlWriter& operator=( XmlWriter const& ) = delete;
  5133. XmlWriter& startElement( std::string const& name, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
  5134. ScopedElement scopedElement( std::string const& name, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
  5135. XmlWriter& endElement(XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
  5136. XmlWriter& writeAttribute( std::string const& name, std::string const& attribute );
  5137. XmlWriter& writeAttribute( std::string const& name, bool attribute );
  5138. template<typename T>
  5139. XmlWriter& writeAttribute( std::string const& name, T const& attribute ) {
  5140. ReusableStringStream rss;
  5141. rss << attribute;
  5142. return writeAttribute( name, rss.str() );
  5143. }
  5144. XmlWriter& writeText( std::string const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
  5145. XmlWriter& writeComment(std::string const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
  5146. void writeStylesheetRef( std::string const& url );
  5147. XmlWriter& writeBlankLine();
  5148. void ensureTagClosed();
  5149. private:
  5150. void applyFormatting(XmlFormatting fmt);
  5151. void writeDeclaration();
  5152. void newlineIfNecessary();
  5153. bool m_tagIsOpen = false;
  5154. bool m_needsNewline = false;
  5155. std::vector<std::string> m_tags;
  5156. std::string m_indent;
  5157. std::ostream& m_os;
  5158. };
  5159. }
  5160. // end catch_xmlwriter.h
  5161. namespace Catch {
  5162. class JunitReporter : public CumulativeReporterBase<JunitReporter> {
  5163. public:
  5164. JunitReporter(ReporterConfig const& _config);
  5165. ~JunitReporter() override;
  5166. static std::string getDescription();
  5167. void noMatchingTestCases(std::string const& /*spec*/) override;
  5168. void testRunStarting(TestRunInfo const& runInfo) override;
  5169. void testGroupStarting(GroupInfo const& groupInfo) override;
  5170. void testCaseStarting(TestCaseInfo const& testCaseInfo) override;
  5171. bool assertionEnded(AssertionStats const& assertionStats) override;
  5172. void testCaseEnded(TestCaseStats const& testCaseStats) override;
  5173. void testGroupEnded(TestGroupStats const& testGroupStats) override;
  5174. void testRunEndedCumulative() override;
  5175. void writeGroup(TestGroupNode const& groupNode, double suiteTime);
  5176. void writeTestCase(TestCaseNode const& testCaseNode);
  5177. void writeSection(std::string const& className,
  5178. std::string const& rootName,
  5179. SectionNode const& sectionNode);
  5180. void writeAssertions(SectionNode const& sectionNode);
  5181. void writeAssertion(AssertionStats const& stats);
  5182. XmlWriter xml;
  5183. Timer suiteTimer;
  5184. std::string stdOutForSuite;
  5185. std::string stdErrForSuite;
  5186. unsigned int unexpectedExceptions = 0;
  5187. bool m_okToFail = false;
  5188. };
  5189. } // end namespace Catch
  5190. // end catch_reporter_junit.h
  5191. // start catch_reporter_xml.h
  5192. namespace Catch {
  5193. class XmlReporter : public StreamingReporterBase<XmlReporter> {
  5194. public:
  5195. XmlReporter(ReporterConfig const& _config);
  5196. ~XmlReporter() override;
  5197. static std::string getDescription();
  5198. virtual std::string getStylesheetRef() const;
  5199. void writeSourceInfo(SourceLineInfo const& sourceInfo);
  5200. public: // StreamingReporterBase
  5201. void noMatchingTestCases(std::string const& s) override;
  5202. void testRunStarting(TestRunInfo const& testInfo) override;
  5203. void testGroupStarting(GroupInfo const& groupInfo) override;
  5204. void testCaseStarting(TestCaseInfo const& testInfo) override;
  5205. void sectionStarting(SectionInfo const& sectionInfo) override;
  5206. void assertionStarting(AssertionInfo const&) override;
  5207. bool assertionEnded(AssertionStats const& assertionStats) override;
  5208. void sectionEnded(SectionStats const& sectionStats) override;
  5209. void testCaseEnded(TestCaseStats const& testCaseStats) override;
  5210. void testGroupEnded(TestGroupStats const& testGroupStats) override;
  5211. void testRunEnded(TestRunStats const& testRunStats) override;
  5212. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  5213. void benchmarkPreparing(std::string const& name) override;
  5214. void benchmarkStarting(BenchmarkInfo const&) override;
  5215. void benchmarkEnded(BenchmarkStats<> const&) override;
  5216. void benchmarkFailed(std::string const&) override;
  5217. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  5218. private:
  5219. Timer m_testCaseTimer;
  5220. XmlWriter m_xml;
  5221. int m_sectionDepth = 0;
  5222. };
  5223. } // end namespace Catch
  5224. // end catch_reporter_xml.h
  5225. // end catch_external_interfaces.h
  5226. #endif
  5227. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  5228. // start catch_benchmarking_all.hpp
  5229. // A proxy header that includes all of the benchmarking headers to allow
  5230. // concise include of the benchmarking features. You should prefer the
  5231. // individual includes in standard use.
  5232. // start catch_benchmark.hpp
  5233. // Benchmark
  5234. // start catch_chronometer.hpp
  5235. // User-facing chronometer
  5236. // start catch_clock.hpp
  5237. // Clocks
  5238. #include <chrono>
  5239. #include <ratio>
  5240. namespace Catch {
  5241. namespace Benchmark {
  5242. template <typename Clock>
  5243. using ClockDuration = typename Clock::duration;
  5244. template <typename Clock>
  5245. using FloatDuration = std::chrono::duration<double, typename Clock::period>;
  5246. template <typename Clock>
  5247. using TimePoint = typename Clock::time_point;
  5248. using default_clock = std::chrono::steady_clock;
  5249. template <typename Clock>
  5250. struct now {
  5251. TimePoint<Clock> operator()() const {
  5252. return Clock::now();
  5253. }
  5254. };
  5255. using fp_seconds = std::chrono::duration<double, std::ratio<1>>;
  5256. } // namespace Benchmark
  5257. } // namespace Catch
  5258. // end catch_clock.hpp
  5259. // start catch_optimizer.hpp
  5260. // Hinting the optimizer
  5261. #if defined(_MSC_VER)
  5262. # include <atomic> // atomic_thread_fence
  5263. #endif
  5264. namespace Catch {
  5265. namespace Benchmark {
  5266. #if defined(__GNUC__) || defined(__clang__)
  5267. template <typename T>
  5268. inline void keep_memory(T* p) {
  5269. asm volatile("" : : "g"(p) : "memory");
  5270. }
  5271. inline void keep_memory() {
  5272. asm volatile("" : : : "memory");
  5273. }
  5274. namespace Detail {
  5275. inline void optimizer_barrier() { keep_memory(); }
  5276. } // namespace Detail
  5277. #elif defined(_MSC_VER)
  5278. #pragma optimize("", off)
  5279. template <typename T>
  5280. inline void keep_memory(T* p) {
  5281. // thanks @milleniumbug
  5282. *reinterpret_cast<char volatile*>(p) = *reinterpret_cast<char const volatile*>(p);
  5283. }
  5284. // TODO equivalent keep_memory()
  5285. #pragma optimize("", on)
  5286. namespace Detail {
  5287. inline void optimizer_barrier() {
  5288. std::atomic_thread_fence(std::memory_order_seq_cst);
  5289. }
  5290. } // namespace Detail
  5291. #endif
  5292. template <typename T>
  5293. inline void deoptimize_value(T&& x) {
  5294. keep_memory(&x);
  5295. }
  5296. template <typename Fn, typename... Args>
  5297. inline auto invoke_deoptimized(Fn&& fn, Args&&... args) -> typename std::enable_if<!std::is_same<void, decltype(fn(args...))>::value>::type {
  5298. deoptimize_value(std::forward<Fn>(fn) (std::forward<Args...>(args...)));
  5299. }
  5300. template <typename Fn, typename... Args>
  5301. inline auto invoke_deoptimized(Fn&& fn, Args&&... args) -> typename std::enable_if<std::is_same<void, decltype(fn(args...))>::value>::type {
  5302. std::forward<Fn>(fn) (std::forward<Args...>(args...));
  5303. }
  5304. } // namespace Benchmark
  5305. } // namespace Catch
  5306. // end catch_optimizer.hpp
  5307. // start catch_complete_invoke.hpp
  5308. // Invoke with a special case for void
  5309. #include <type_traits>
  5310. #include <utility>
  5311. namespace Catch {
  5312. namespace Benchmark {
  5313. namespace Detail {
  5314. template <typename T>
  5315. struct CompleteType { using type = T; };
  5316. template <>
  5317. struct CompleteType<void> { struct type {}; };
  5318. template <typename T>
  5319. using CompleteType_t = typename CompleteType<T>::type;
  5320. template <typename Result>
  5321. struct CompleteInvoker {
  5322. template <typename Fun, typename... Args>
  5323. static Result invoke(Fun&& fun, Args&&... args) {
  5324. return std::forward<Fun>(fun)(std::forward<Args>(args)...);
  5325. }
  5326. };
  5327. template <>
  5328. struct CompleteInvoker<void> {
  5329. template <typename Fun, typename... Args>
  5330. static CompleteType_t<void> invoke(Fun&& fun, Args&&... args) {
  5331. std::forward<Fun>(fun)(std::forward<Args>(args)...);
  5332. return {};
  5333. }
  5334. };
  5335. // invoke and not return void :(
  5336. template <typename Fun, typename... Args>
  5337. CompleteType_t<FunctionReturnType<Fun, Args...>> complete_invoke(Fun&& fun, Args&&... args) {
  5338. return CompleteInvoker<FunctionReturnType<Fun, Args...>>::invoke(std::forward<Fun>(fun), std::forward<Args>(args)...);
  5339. }
  5340. const std::string benchmarkErrorMsg = "a benchmark failed to run successfully";
  5341. } // namespace Detail
  5342. template <typename Fun>
  5343. Detail::CompleteType_t<FunctionReturnType<Fun>> user_code(Fun&& fun) {
  5344. CATCH_TRY{
  5345. return Detail::complete_invoke(std::forward<Fun>(fun));
  5346. } CATCH_CATCH_ALL{
  5347. getResultCapture().benchmarkFailed(translateActiveException());
  5348. CATCH_RUNTIME_ERROR(Detail::benchmarkErrorMsg);
  5349. }
  5350. }
  5351. } // namespace Benchmark
  5352. } // namespace Catch
  5353. // end catch_complete_invoke.hpp
  5354. namespace Catch {
  5355. namespace Benchmark {
  5356. namespace Detail {
  5357. struct ChronometerConcept {
  5358. virtual void start() = 0;
  5359. virtual void finish() = 0;
  5360. virtual ~ChronometerConcept() = default;
  5361. };
  5362. template <typename Clock>
  5363. struct ChronometerModel final : public ChronometerConcept {
  5364. void start() override { started = Clock::now(); }
  5365. void finish() override { finished = Clock::now(); }
  5366. ClockDuration<Clock> elapsed() const { return finished - started; }
  5367. TimePoint<Clock> started;
  5368. TimePoint<Clock> finished;
  5369. };
  5370. } // namespace Detail
  5371. struct Chronometer {
  5372. public:
  5373. template <typename Fun>
  5374. void measure(Fun&& fun) { measure(std::forward<Fun>(fun), is_callable<Fun(int)>()); }
  5375. int runs() const { return k; }
  5376. Chronometer(Detail::ChronometerConcept& meter, int k)
  5377. : impl(&meter)
  5378. , k(k) {}
  5379. private:
  5380. template <typename Fun>
  5381. void measure(Fun&& fun, std::false_type) {
  5382. measure([&fun](int) { return fun(); }, std::true_type());
  5383. }
  5384. template <typename Fun>
  5385. void measure(Fun&& fun, std::true_type) {
  5386. Detail::optimizer_barrier();
  5387. impl->start();
  5388. for (int i = 0; i < k; ++i) invoke_deoptimized(fun, i);
  5389. impl->finish();
  5390. Detail::optimizer_barrier();
  5391. }
  5392. Detail::ChronometerConcept* impl;
  5393. int k;
  5394. };
  5395. } // namespace Benchmark
  5396. } // namespace Catch
  5397. // end catch_chronometer.hpp
  5398. // start catch_environment.hpp
  5399. // Environment information
  5400. namespace Catch {
  5401. namespace Benchmark {
  5402. template <typename Duration>
  5403. struct EnvironmentEstimate {
  5404. Duration mean;
  5405. OutlierClassification outliers;
  5406. template <typename Duration2>
  5407. operator EnvironmentEstimate<Duration2>() const {
  5408. return { mean, outliers };
  5409. }
  5410. };
  5411. template <typename Clock>
  5412. struct Environment {
  5413. using clock_type = Clock;
  5414. EnvironmentEstimate<FloatDuration<Clock>> clock_resolution;
  5415. EnvironmentEstimate<FloatDuration<Clock>> clock_cost;
  5416. };
  5417. } // namespace Benchmark
  5418. } // namespace Catch
  5419. // end catch_environment.hpp
  5420. // start catch_execution_plan.hpp
  5421. // Execution plan
  5422. // start catch_benchmark_function.hpp
  5423. // Dumb std::function implementation for consistent call overhead
  5424. #include <cassert>
  5425. #include <type_traits>
  5426. #include <utility>
  5427. #include <memory>
  5428. namespace Catch {
  5429. namespace Benchmark {
  5430. namespace Detail {
  5431. template <typename T>
  5432. using Decay = typename std::decay<T>::type;
  5433. template <typename T, typename U>
  5434. struct is_related
  5435. : std::is_same<Decay<T>, Decay<U>> {};
  5436. /// We need to reinvent std::function because every piece of code that might add overhead
  5437. /// in a measurement context needs to have consistent performance characteristics so that we
  5438. /// can account for it in the measurement.
  5439. /// Implementations of std::function with optimizations that aren't always applicable, like
  5440. /// small buffer optimizations, are not uncommon.
  5441. /// This is effectively an implementation of std::function without any such optimizations;
  5442. /// it may be slow, but it is consistently slow.
  5443. struct BenchmarkFunction {
  5444. private:
  5445. struct callable {
  5446. virtual void call(Chronometer meter) const = 0;
  5447. virtual callable* clone() const = 0;
  5448. virtual ~callable() = default;
  5449. };
  5450. template <typename Fun>
  5451. struct model : public callable {
  5452. model(Fun&& fun) : fun(std::move(fun)) {}
  5453. model(Fun const& fun) : fun(fun) {}
  5454. model<Fun>* clone() const override { return new model<Fun>(*this); }
  5455. void call(Chronometer meter) const override {
  5456. call(meter, is_callable<Fun(Chronometer)>());
  5457. }
  5458. void call(Chronometer meter, std::true_type) const {
  5459. fun(meter);
  5460. }
  5461. void call(Chronometer meter, std::false_type) const {
  5462. meter.measure(fun);
  5463. }
  5464. Fun fun;
  5465. };
  5466. struct do_nothing { void operator()() const {} };
  5467. template <typename T>
  5468. BenchmarkFunction(model<T>* c) : f(c) {}
  5469. public:
  5470. BenchmarkFunction()
  5471. : f(new model<do_nothing>{ {} }) {}
  5472. template <typename Fun,
  5473. typename std::enable_if<!is_related<Fun, BenchmarkFunction>::value, int>::type = 0>
  5474. BenchmarkFunction(Fun&& fun)
  5475. : f(new model<typename std::decay<Fun>::type>(std::forward<Fun>(fun))) {}
  5476. BenchmarkFunction(BenchmarkFunction&& that)
  5477. : f(std::move(that.f)) {}
  5478. BenchmarkFunction(BenchmarkFunction const& that)
  5479. : f(that.f->clone()) {}
  5480. BenchmarkFunction& operator=(BenchmarkFunction&& that) {
  5481. f = std::move(that.f);
  5482. return *this;
  5483. }
  5484. BenchmarkFunction& operator=(BenchmarkFunction const& that) {
  5485. f.reset(that.f->clone());
  5486. return *this;
  5487. }
  5488. void operator()(Chronometer meter) const { f->call(meter); }
  5489. private:
  5490. std::unique_ptr<callable> f;
  5491. };
  5492. } // namespace Detail
  5493. } // namespace Benchmark
  5494. } // namespace Catch
  5495. // end catch_benchmark_function.hpp
  5496. // start catch_repeat.hpp
  5497. // repeat algorithm
  5498. #include <type_traits>
  5499. #include <utility>
  5500. namespace Catch {
  5501. namespace Benchmark {
  5502. namespace Detail {
  5503. template <typename Fun>
  5504. struct repeater {
  5505. void operator()(int k) const {
  5506. for (int i = 0; i < k; ++i) {
  5507. fun();
  5508. }
  5509. }
  5510. Fun fun;
  5511. };
  5512. template <typename Fun>
  5513. repeater<typename std::decay<Fun>::type> repeat(Fun&& fun) {
  5514. return { std::forward<Fun>(fun) };
  5515. }
  5516. } // namespace Detail
  5517. } // namespace Benchmark
  5518. } // namespace Catch
  5519. // end catch_repeat.hpp
  5520. // start catch_run_for_at_least.hpp
  5521. // Run a function for a minimum amount of time
  5522. // start catch_measure.hpp
  5523. // Measure
  5524. // start catch_timing.hpp
  5525. // Timing
  5526. #include <tuple>
  5527. #include <type_traits>
  5528. namespace Catch {
  5529. namespace Benchmark {
  5530. template <typename Duration, typename Result>
  5531. struct Timing {
  5532. Duration elapsed;
  5533. Result result;
  5534. int iterations;
  5535. };
  5536. template <typename Clock, typename Func, typename... Args>
  5537. using TimingOf = Timing<ClockDuration<Clock>, Detail::CompleteType_t<FunctionReturnType<Func, Args...>>>;
  5538. } // namespace Benchmark
  5539. } // namespace Catch
  5540. // end catch_timing.hpp
  5541. #include <utility>
  5542. namespace Catch {
  5543. namespace Benchmark {
  5544. namespace Detail {
  5545. template <typename Clock, typename Fun, typename... Args>
  5546. TimingOf<Clock, Fun, Args...> measure(Fun&& fun, Args&&... args) {
  5547. auto start = Clock::now();
  5548. auto&& r = Detail::complete_invoke(fun, std::forward<Args>(args)...);
  5549. auto end = Clock::now();
  5550. auto delta = end - start;
  5551. return { delta, std::forward<decltype(r)>(r), 1 };
  5552. }
  5553. } // namespace Detail
  5554. } // namespace Benchmark
  5555. } // namespace Catch
  5556. // end catch_measure.hpp
  5557. #include <utility>
  5558. #include <type_traits>
  5559. namespace Catch {
  5560. namespace Benchmark {
  5561. namespace Detail {
  5562. template <typename Clock, typename Fun>
  5563. TimingOf<Clock, Fun, int> measure_one(Fun&& fun, int iters, std::false_type) {
  5564. return Detail::measure<Clock>(fun, iters);
  5565. }
  5566. template <typename Clock, typename Fun>
  5567. TimingOf<Clock, Fun, Chronometer> measure_one(Fun&& fun, int iters, std::true_type) {
  5568. Detail::ChronometerModel<Clock> meter;
  5569. auto&& result = Detail::complete_invoke(fun, Chronometer(meter, iters));
  5570. return { meter.elapsed(), std::move(result), iters };
  5571. }
  5572. template <typename Clock, typename Fun>
  5573. using run_for_at_least_argument_t = typename std::conditional<is_callable<Fun(Chronometer)>::value, Chronometer, int>::type;
  5574. struct optimized_away_error : std::exception {
  5575. const char* what() const noexcept override {
  5576. return "could not measure benchmark, maybe it was optimized away";
  5577. }
  5578. };
  5579. template <typename Clock, typename Fun>
  5580. TimingOf<Clock, Fun, run_for_at_least_argument_t<Clock, Fun>> run_for_at_least(ClockDuration<Clock> how_long, int seed, Fun&& fun) {
  5581. auto iters = seed;
  5582. while (iters < (1 << 30)) {
  5583. auto&& Timing = measure_one<Clock>(fun, iters, is_callable<Fun(Chronometer)>());
  5584. if (Timing.elapsed >= how_long) {
  5585. return { Timing.elapsed, std::move(Timing.result), iters };
  5586. }
  5587. iters *= 2;
  5588. }
  5589. throw optimized_away_error{};
  5590. }
  5591. } // namespace Detail
  5592. } // namespace Benchmark
  5593. } // namespace Catch
  5594. // end catch_run_for_at_least.hpp
  5595. #include <algorithm>
  5596. namespace Catch {
  5597. namespace Benchmark {
  5598. template <typename Duration>
  5599. struct ExecutionPlan {
  5600. int iterations_per_sample;
  5601. Duration estimated_duration;
  5602. Detail::BenchmarkFunction benchmark;
  5603. Duration warmup_time;
  5604. int warmup_iterations;
  5605. template <typename Duration2>
  5606. operator ExecutionPlan<Duration2>() const {
  5607. return { iterations_per_sample, estimated_duration, benchmark, warmup_time, warmup_iterations };
  5608. }
  5609. template <typename Clock>
  5610. std::vector<FloatDuration<Clock>> run(const IConfig &cfg, Environment<FloatDuration<Clock>> env) const {
  5611. // warmup a bit
  5612. Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_iterations, Detail::repeat(now<Clock>{}));
  5613. std::vector<FloatDuration<Clock>> times;
  5614. times.reserve(cfg.benchmarkSamples());
  5615. std::generate_n(std::back_inserter(times), cfg.benchmarkSamples(), [this, env] {
  5616. Detail::ChronometerModel<Clock> model;
  5617. this->benchmark(Chronometer(model, iterations_per_sample));
  5618. auto sample_time = model.elapsed() - env.clock_cost.mean;
  5619. if (sample_time < FloatDuration<Clock>::zero()) sample_time = FloatDuration<Clock>::zero();
  5620. return sample_time / iterations_per_sample;
  5621. });
  5622. return times;
  5623. }
  5624. };
  5625. } // namespace Benchmark
  5626. } // namespace Catch
  5627. // end catch_execution_plan.hpp
  5628. // start catch_estimate_clock.hpp
  5629. // Environment measurement
  5630. // start catch_stats.hpp
  5631. // Statistical analysis tools
  5632. #include <algorithm>
  5633. #include <functional>
  5634. #include <vector>
  5635. #include <iterator>
  5636. #include <numeric>
  5637. #include <tuple>
  5638. #include <cmath>
  5639. #include <utility>
  5640. #include <cstddef>
  5641. #include <random>
  5642. namespace Catch {
  5643. namespace Benchmark {
  5644. namespace Detail {
  5645. using sample = std::vector<double>;
  5646. double weighted_average_quantile(int k, int q, std::vector<double>::iterator first, std::vector<double>::iterator last);
  5647. template <typename Iterator>
  5648. OutlierClassification classify_outliers(Iterator first, Iterator last) {
  5649. std::vector<double> copy(first, last);
  5650. auto q1 = weighted_average_quantile(1, 4, copy.begin(), copy.end());
  5651. auto q3 = weighted_average_quantile(3, 4, copy.begin(), copy.end());
  5652. auto iqr = q3 - q1;
  5653. auto los = q1 - (iqr * 3.);
  5654. auto lom = q1 - (iqr * 1.5);
  5655. auto him = q3 + (iqr * 1.5);
  5656. auto his = q3 + (iqr * 3.);
  5657. OutlierClassification o;
  5658. for (; first != last; ++first) {
  5659. auto&& t = *first;
  5660. if (t < los) ++o.low_severe;
  5661. else if (t < lom) ++o.low_mild;
  5662. else if (t > his) ++o.high_severe;
  5663. else if (t > him) ++o.high_mild;
  5664. ++o.samples_seen;
  5665. }
  5666. return o;
  5667. }
  5668. template <typename Iterator>
  5669. double mean(Iterator first, Iterator last) {
  5670. auto count = last - first;
  5671. double sum = std::accumulate(first, last, 0.);
  5672. return sum / count;
  5673. }
  5674. template <typename URng, typename Iterator, typename Estimator>
  5675. sample resample(URng& rng, int resamples, Iterator first, Iterator last, Estimator& estimator) {
  5676. auto n = last - first;
  5677. std::uniform_int_distribution<decltype(n)> dist(0, n - 1);
  5678. sample out;
  5679. out.reserve(resamples);
  5680. std::generate_n(std::back_inserter(out), resamples, [n, first, &estimator, &dist, &rng] {
  5681. std::vector<double> resampled;
  5682. resampled.reserve(n);
  5683. std::generate_n(std::back_inserter(resampled), n, [first, &dist, &rng] { return first[dist(rng)]; });
  5684. return estimator(resampled.begin(), resampled.end());
  5685. });
  5686. std::sort(out.begin(), out.end());
  5687. return out;
  5688. }
  5689. template <typename Estimator, typename Iterator>
  5690. sample jackknife(Estimator&& estimator, Iterator first, Iterator last) {
  5691. auto n = last - first;
  5692. auto second = std::next(first);
  5693. sample results;
  5694. results.reserve(n);
  5695. for (auto it = first; it != last; ++it) {
  5696. std::iter_swap(it, first);
  5697. results.push_back(estimator(second, last));
  5698. }
  5699. return results;
  5700. }
  5701. inline double normal_cdf(double x) {
  5702. return std::erfc(-x / std::sqrt(2.0)) / 2.0;
  5703. }
  5704. double erfc_inv(double x);
  5705. double normal_quantile(double p);
  5706. template <typename Iterator, typename Estimator>
  5707. Estimate<double> bootstrap(double confidence_level, Iterator first, Iterator last, sample const& resample, Estimator&& estimator) {
  5708. auto n_samples = last - first;
  5709. double point = estimator(first, last);
  5710. // Degenerate case with a single sample
  5711. if (n_samples == 1) return { point, point, point, confidence_level };
  5712. sample jack = jackknife(estimator, first, last);
  5713. double jack_mean = mean(jack.begin(), jack.end());
  5714. double sum_squares, sum_cubes;
  5715. 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> {
  5716. auto d = jack_mean - x;
  5717. auto d2 = d * d;
  5718. auto d3 = d2 * d;
  5719. return { sqcb.first + d2, sqcb.second + d3 };
  5720. });
  5721. double accel = sum_cubes / (6 * std::pow(sum_squares, 1.5));
  5722. int n = static_cast<int>(resample.size());
  5723. double prob_n = std::count_if(resample.begin(), resample.end(), [point](double x) { return x < point; }) / (double)n;
  5724. // degenerate case with uniform samples
  5725. if (prob_n == 0) return { point, point, point, confidence_level };
  5726. double bias = normal_quantile(prob_n);
  5727. double z1 = normal_quantile((1. - confidence_level) / 2.);
  5728. auto cumn = [n](double x) -> int {
  5729. return std::lround(normal_cdf(x) * n); };
  5730. auto a = [bias, accel](double b) { return bias + b / (1. - accel * b); };
  5731. double b1 = bias + z1;
  5732. double b2 = bias - z1;
  5733. double a1 = a(b1);
  5734. double a2 = a(b2);
  5735. auto lo = (std::max)(cumn(a1), 0);
  5736. auto hi = (std::min)(cumn(a2), n - 1);
  5737. return { point, resample[lo], resample[hi], confidence_level };
  5738. }
  5739. double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n);
  5740. struct bootstrap_analysis {
  5741. Estimate<double> mean;
  5742. Estimate<double> standard_deviation;
  5743. double outlier_variance;
  5744. };
  5745. bootstrap_analysis analyse_samples(double confidence_level, int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last);
  5746. } // namespace Detail
  5747. } // namespace Benchmark
  5748. } // namespace Catch
  5749. // end catch_stats.hpp
  5750. #include <algorithm>
  5751. #include <iterator>
  5752. #include <tuple>
  5753. #include <vector>
  5754. #include <cmath>
  5755. namespace Catch {
  5756. namespace Benchmark {
  5757. namespace Detail {
  5758. template <typename Clock>
  5759. std::vector<double> resolution(int k) {
  5760. std::vector<TimePoint<Clock>> times;
  5761. times.reserve(k + 1);
  5762. std::generate_n(std::back_inserter(times), k + 1, now<Clock>{});
  5763. std::vector<double> deltas;
  5764. deltas.reserve(k);
  5765. std::transform(std::next(times.begin()), times.end(), times.begin(),
  5766. std::back_inserter(deltas),
  5767. [](TimePoint<Clock> a, TimePoint<Clock> b) { return static_cast<double>((a - b).count()); });
  5768. return deltas;
  5769. }
  5770. const auto warmup_iterations = 10000;
  5771. const auto warmup_time = std::chrono::milliseconds(100);
  5772. const auto minimum_ticks = 1000;
  5773. const auto warmup_seed = 10000;
  5774. const auto clock_resolution_estimation_time = std::chrono::milliseconds(500);
  5775. const auto clock_cost_estimation_time_limit = std::chrono::seconds(1);
  5776. const auto clock_cost_estimation_tick_limit = 100000;
  5777. const auto clock_cost_estimation_time = std::chrono::milliseconds(10);
  5778. const auto clock_cost_estimation_iterations = 10000;
  5779. template <typename Clock>
  5780. int warmup() {
  5781. return run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_seed, &resolution<Clock>)
  5782. .iterations;
  5783. }
  5784. template <typename Clock>
  5785. EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_resolution(int iterations) {
  5786. auto r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_resolution_estimation_time), iterations, &resolution<Clock>)
  5787. .result;
  5788. return {
  5789. FloatDuration<Clock>(mean(r.begin(), r.end())),
  5790. classify_outliers(r.begin(), r.end()),
  5791. };
  5792. }
  5793. template <typename Clock>
  5794. EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_cost(FloatDuration<Clock> resolution) {
  5795. auto time_limit = (std::min)(
  5796. resolution * clock_cost_estimation_tick_limit,
  5797. FloatDuration<Clock>(clock_cost_estimation_time_limit));
  5798. auto time_clock = [](int k) {
  5799. return Detail::measure<Clock>([k] {
  5800. for (int i = 0; i < k; ++i) {
  5801. volatile auto ignored = Clock::now();
  5802. (void)ignored;
  5803. }
  5804. }).elapsed;
  5805. };
  5806. time_clock(1);
  5807. int iters = clock_cost_estimation_iterations;
  5808. auto&& r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_cost_estimation_time), iters, time_clock);
  5809. std::vector<double> times;
  5810. int nsamples = static_cast<int>(std::ceil(time_limit / r.elapsed));
  5811. times.reserve(nsamples);
  5812. std::generate_n(std::back_inserter(times), nsamples, [time_clock, &r] {
  5813. return static_cast<double>((time_clock(r.iterations) / r.iterations).count());
  5814. });
  5815. return {
  5816. FloatDuration<Clock>(mean(times.begin(), times.end())),
  5817. classify_outliers(times.begin(), times.end()),
  5818. };
  5819. }
  5820. template <typename Clock>
  5821. Environment<FloatDuration<Clock>> measure_environment() {
  5822. static Environment<FloatDuration<Clock>>* env = nullptr;
  5823. if (env) {
  5824. return *env;
  5825. }
  5826. auto iters = Detail::warmup<Clock>();
  5827. auto resolution = Detail::estimate_clock_resolution<Clock>(iters);
  5828. auto cost = Detail::estimate_clock_cost<Clock>(resolution.mean);
  5829. env = new Environment<FloatDuration<Clock>>{ resolution, cost };
  5830. return *env;
  5831. }
  5832. } // namespace Detail
  5833. } // namespace Benchmark
  5834. } // namespace Catch
  5835. // end catch_estimate_clock.hpp
  5836. // start catch_analyse.hpp
  5837. // Run and analyse one benchmark
  5838. // start catch_sample_analysis.hpp
  5839. // Benchmark results
  5840. #include <algorithm>
  5841. #include <vector>
  5842. #include <string>
  5843. #include <iterator>
  5844. namespace Catch {
  5845. namespace Benchmark {
  5846. template <typename Duration>
  5847. struct SampleAnalysis {
  5848. std::vector<Duration> samples;
  5849. Estimate<Duration> mean;
  5850. Estimate<Duration> standard_deviation;
  5851. OutlierClassification outliers;
  5852. double outlier_variance;
  5853. template <typename Duration2>
  5854. operator SampleAnalysis<Duration2>() const {
  5855. std::vector<Duration2> samples2;
  5856. samples2.reserve(samples.size());
  5857. std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration d) { return Duration2(d); });
  5858. return {
  5859. std::move(samples2),
  5860. mean,
  5861. standard_deviation,
  5862. outliers,
  5863. outlier_variance,
  5864. };
  5865. }
  5866. };
  5867. } // namespace Benchmark
  5868. } // namespace Catch
  5869. // end catch_sample_analysis.hpp
  5870. #include <algorithm>
  5871. #include <iterator>
  5872. #include <vector>
  5873. namespace Catch {
  5874. namespace Benchmark {
  5875. namespace Detail {
  5876. template <typename Duration, typename Iterator>
  5877. SampleAnalysis<Duration> analyse(const IConfig &cfg, Environment<Duration>, Iterator first, Iterator last) {
  5878. if (!cfg.benchmarkNoAnalysis()) {
  5879. std::vector<double> samples;
  5880. samples.reserve(last - first);
  5881. std::transform(first, last, std::back_inserter(samples), [](Duration d) { return d.count(); });
  5882. auto analysis = Catch::Benchmark::Detail::analyse_samples(cfg.benchmarkConfidenceInterval(), cfg.benchmarkResamples(), samples.begin(), samples.end());
  5883. auto outliers = Catch::Benchmark::Detail::classify_outliers(samples.begin(), samples.end());
  5884. auto wrap_estimate = [](Estimate<double> e) {
  5885. return Estimate<Duration> {
  5886. Duration(e.point),
  5887. Duration(e.lower_bound),
  5888. Duration(e.upper_bound),
  5889. e.confidence_interval,
  5890. };
  5891. };
  5892. std::vector<Duration> samples2;
  5893. samples2.reserve(samples.size());
  5894. std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](double d) { return Duration(d); });
  5895. return {
  5896. std::move(samples2),
  5897. wrap_estimate(analysis.mean),
  5898. wrap_estimate(analysis.standard_deviation),
  5899. outliers,
  5900. analysis.outlier_variance,
  5901. };
  5902. } else {
  5903. std::vector<Duration> samples;
  5904. samples.reserve(last - first);
  5905. Duration mean = Duration(0);
  5906. int i = 0;
  5907. for (auto it = first; it < last; ++it, ++i) {
  5908. samples.push_back(Duration(*it));
  5909. mean += Duration(*it);
  5910. }
  5911. mean /= i;
  5912. return {
  5913. std::move(samples),
  5914. Estimate<Duration>{mean, mean, mean, 0.0},
  5915. Estimate<Duration>{Duration(0), Duration(0), Duration(0), 0.0},
  5916. OutlierClassification{},
  5917. 0.0
  5918. };
  5919. }
  5920. }
  5921. } // namespace Detail
  5922. } // namespace Benchmark
  5923. } // namespace Catch
  5924. // end catch_analyse.hpp
  5925. #include <algorithm>
  5926. #include <functional>
  5927. #include <string>
  5928. #include <vector>
  5929. #include <cmath>
  5930. namespace Catch {
  5931. namespace Benchmark {
  5932. struct Benchmark {
  5933. Benchmark(std::string &&name)
  5934. : name(std::move(name)) {}
  5935. template <class FUN>
  5936. Benchmark(std::string &&name, FUN &&func)
  5937. : fun(std::move(func)), name(std::move(name)) {}
  5938. template <typename Clock>
  5939. ExecutionPlan<FloatDuration<Clock>> prepare(const IConfig &cfg, Environment<FloatDuration<Clock>> env) const {
  5940. auto min_time = env.clock_resolution.mean * Detail::minimum_ticks;
  5941. auto run_time = std::max(min_time, std::chrono::duration_cast<decltype(min_time)>(cfg.benchmarkWarmupTime()));
  5942. auto&& test = Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(run_time), 1, fun);
  5943. int new_iters = static_cast<int>(std::ceil(min_time * test.iterations / test.elapsed));
  5944. return { new_iters, test.elapsed / test.iterations * new_iters * cfg.benchmarkSamples(), fun, std::chrono::duration_cast<FloatDuration<Clock>>(cfg.benchmarkWarmupTime()), Detail::warmup_iterations };
  5945. }
  5946. template <typename Clock = default_clock>
  5947. void run() {
  5948. IConfigPtr cfg = getCurrentContext().getConfig();
  5949. auto env = Detail::measure_environment<Clock>();
  5950. getResultCapture().benchmarkPreparing(name);
  5951. CATCH_TRY{
  5952. auto plan = user_code([&] {
  5953. return prepare<Clock>(*cfg, env);
  5954. });
  5955. BenchmarkInfo info {
  5956. name,
  5957. plan.estimated_duration.count(),
  5958. plan.iterations_per_sample,
  5959. cfg->benchmarkSamples(),
  5960. cfg->benchmarkResamples(),
  5961. env.clock_resolution.mean.count(),
  5962. env.clock_cost.mean.count()
  5963. };
  5964. getResultCapture().benchmarkStarting(info);
  5965. auto samples = user_code([&] {
  5966. return plan.template run<Clock>(*cfg, env);
  5967. });
  5968. auto analysis = Detail::analyse(*cfg, env, samples.begin(), samples.end());
  5969. BenchmarkStats<FloatDuration<Clock>> stats{ info, analysis.samples, analysis.mean, analysis.standard_deviation, analysis.outliers, analysis.outlier_variance };
  5970. getResultCapture().benchmarkEnded(stats);
  5971. } CATCH_CATCH_ALL{
  5972. if (translateActiveException() != Detail::benchmarkErrorMsg) // benchmark errors have been reported, otherwise rethrow.
  5973. std::rethrow_exception(std::current_exception());
  5974. }
  5975. }
  5976. // sets lambda to be used in fun *and* executes benchmark!
  5977. template <typename Fun,
  5978. typename std::enable_if<!Detail::is_related<Fun, Benchmark>::value, int>::type = 0>
  5979. Benchmark & operator=(Fun func) {
  5980. fun = Detail::BenchmarkFunction(func);
  5981. run();
  5982. return *this;
  5983. }
  5984. explicit operator bool() {
  5985. return true;
  5986. }
  5987. private:
  5988. Detail::BenchmarkFunction fun;
  5989. std::string name;
  5990. };
  5991. }
  5992. } // namespace Catch
  5993. #define INTERNAL_CATCH_GET_1_ARG(arg1, arg2, ...) arg1
  5994. #define INTERNAL_CATCH_GET_2_ARG(arg1, arg2, ...) arg2
  5995. #define INTERNAL_CATCH_BENCHMARK(BenchmarkName, name, benchmarkIndex)\
  5996. if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \
  5997. BenchmarkName = [&](int benchmarkIndex)
  5998. #define INTERNAL_CATCH_BENCHMARK_ADVANCED(BenchmarkName, name)\
  5999. if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \
  6000. BenchmarkName = [&]
  6001. // end catch_benchmark.hpp
  6002. // start catch_constructor.hpp
  6003. // Constructor and destructor helpers
  6004. #include <type_traits>
  6005. namespace Catch {
  6006. namespace Benchmark {
  6007. namespace Detail {
  6008. template <typename T, bool Destruct>
  6009. struct ObjectStorage
  6010. {
  6011. using TStorage = typename std::aligned_storage<sizeof(T), std::alignment_of<T>::value>::type;
  6012. ObjectStorage() : data() {}
  6013. ObjectStorage(const ObjectStorage& other)
  6014. {
  6015. new(&data) T(other.stored_object());
  6016. }
  6017. ObjectStorage(ObjectStorage&& other)
  6018. {
  6019. new(&data) T(std::move(other.stored_object()));
  6020. }
  6021. ~ObjectStorage() { destruct_on_exit<T>(); }
  6022. template <typename... Args>
  6023. void construct(Args&&... args)
  6024. {
  6025. new (&data) T(std::forward<Args>(args)...);
  6026. }
  6027. template <bool AllowManualDestruction = !Destruct>
  6028. typename std::enable_if<AllowManualDestruction>::type destruct()
  6029. {
  6030. stored_object().~T();
  6031. }
  6032. private:
  6033. // If this is a constructor benchmark, destruct the underlying object
  6034. template <typename U>
  6035. void destruct_on_exit(typename std::enable_if<Destruct, U>::type* = 0) { destruct<true>(); }
  6036. // Otherwise, don't
  6037. template <typename U>
  6038. void destruct_on_exit(typename std::enable_if<!Destruct, U>::type* = 0) { }
  6039. T& stored_object() {
  6040. return *static_cast<T*>(static_cast<void*>(&data));
  6041. }
  6042. T const& stored_object() const {
  6043. return *static_cast<T*>(static_cast<void*>(&data));
  6044. }
  6045. TStorage data;
  6046. };
  6047. }
  6048. template <typename T>
  6049. using storage_for = Detail::ObjectStorage<T, true>;
  6050. template <typename T>
  6051. using destructable_object = Detail::ObjectStorage<T, false>;
  6052. }
  6053. }
  6054. // end catch_constructor.hpp
  6055. // end catch_benchmarking_all.hpp
  6056. #endif
  6057. #endif // ! CATCH_CONFIG_IMPL_ONLY
  6058. #ifdef CATCH_IMPL
  6059. // start catch_impl.hpp
  6060. #ifdef __clang__
  6061. #pragma clang diagnostic push
  6062. #pragma clang diagnostic ignored "-Wweak-vtables"
  6063. #endif
  6064. // Keep these here for external reporters
  6065. // start catch_test_case_tracker.h
  6066. #include <string>
  6067. #include <vector>
  6068. #include <memory>
  6069. namespace Catch {
  6070. namespace TestCaseTracking {
  6071. struct NameAndLocation {
  6072. std::string name;
  6073. SourceLineInfo location;
  6074. NameAndLocation( std::string const& _name, SourceLineInfo const& _location );
  6075. friend bool operator==(NameAndLocation const& lhs, NameAndLocation const& rhs) {
  6076. return lhs.name == rhs.name
  6077. && lhs.location == rhs.location;
  6078. }
  6079. };
  6080. class ITracker;
  6081. using ITrackerPtr = std::shared_ptr<ITracker>;
  6082. class ITracker {
  6083. NameAndLocation m_nameAndLocation;
  6084. public:
  6085. ITracker(NameAndLocation const& nameAndLoc) :
  6086. m_nameAndLocation(nameAndLoc)
  6087. {}
  6088. // static queries
  6089. NameAndLocation const& nameAndLocation() const {
  6090. return m_nameAndLocation;
  6091. }
  6092. virtual ~ITracker();
  6093. // dynamic queries
  6094. virtual bool isComplete() const = 0; // Successfully completed or failed
  6095. virtual bool isSuccessfullyCompleted() const = 0;
  6096. virtual bool isOpen() const = 0; // Started but not complete
  6097. virtual bool hasChildren() const = 0;
  6098. virtual bool hasStarted() const = 0;
  6099. virtual ITracker& parent() = 0;
  6100. // actions
  6101. virtual void close() = 0; // Successfully complete
  6102. virtual void fail() = 0;
  6103. virtual void markAsNeedingAnotherRun() = 0;
  6104. virtual void addChild( ITrackerPtr const& child ) = 0;
  6105. virtual ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) = 0;
  6106. virtual void openChild() = 0;
  6107. // Debug/ checking
  6108. virtual bool isSectionTracker() const = 0;
  6109. virtual bool isGeneratorTracker() const = 0;
  6110. };
  6111. class TrackerContext {
  6112. enum RunState {
  6113. NotStarted,
  6114. Executing,
  6115. CompletedCycle
  6116. };
  6117. ITrackerPtr m_rootTracker;
  6118. ITracker* m_currentTracker = nullptr;
  6119. RunState m_runState = NotStarted;
  6120. public:
  6121. ITracker& startRun();
  6122. void endRun();
  6123. void startCycle();
  6124. void completeCycle();
  6125. bool completedCycle() const;
  6126. ITracker& currentTracker();
  6127. void setCurrentTracker( ITracker* tracker );
  6128. };
  6129. class TrackerBase : public ITracker {
  6130. protected:
  6131. enum CycleState {
  6132. NotStarted,
  6133. Executing,
  6134. ExecutingChildren,
  6135. NeedsAnotherRun,
  6136. CompletedSuccessfully,
  6137. Failed
  6138. };
  6139. using Children = std::vector<ITrackerPtr>;
  6140. TrackerContext& m_ctx;
  6141. ITracker* m_parent;
  6142. Children m_children;
  6143. CycleState m_runState = NotStarted;
  6144. public:
  6145. TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  6146. bool isComplete() const override;
  6147. bool isSuccessfullyCompleted() const override;
  6148. bool isOpen() const override;
  6149. bool hasChildren() const override;
  6150. bool hasStarted() const override {
  6151. return m_runState != NotStarted;
  6152. }
  6153. void addChild( ITrackerPtr const& child ) override;
  6154. ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) override;
  6155. ITracker& parent() override;
  6156. void openChild() override;
  6157. bool isSectionTracker() const override;
  6158. bool isGeneratorTracker() const override;
  6159. void open();
  6160. void close() override;
  6161. void fail() override;
  6162. void markAsNeedingAnotherRun() override;
  6163. private:
  6164. void moveToParent();
  6165. void moveToThis();
  6166. };
  6167. class SectionTracker : public TrackerBase {
  6168. std::vector<std::string> m_filters;
  6169. std::string m_trimmed_name;
  6170. public:
  6171. SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  6172. bool isSectionTracker() const override;
  6173. bool isComplete() const override;
  6174. static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation );
  6175. void tryOpen();
  6176. void addInitialFilters( std::vector<std::string> const& filters );
  6177. void addNextFilters( std::vector<std::string> const& filters );
  6178. //! Returns filters active in this tracker
  6179. std::vector<std::string> const& getFilters() const;
  6180. //! Returns whitespace-trimmed name of the tracked section
  6181. std::string const& trimmedName() const;
  6182. };
  6183. } // namespace TestCaseTracking
  6184. using TestCaseTracking::ITracker;
  6185. using TestCaseTracking::TrackerContext;
  6186. using TestCaseTracking::SectionTracker;
  6187. } // namespace Catch
  6188. // end catch_test_case_tracker.h
  6189. // start catch_leak_detector.h
  6190. namespace Catch {
  6191. struct LeakDetector {
  6192. LeakDetector();
  6193. ~LeakDetector();
  6194. };
  6195. }
  6196. // end catch_leak_detector.h
  6197. // Cpp files will be included in the single-header file here
  6198. // start catch_stats.cpp
  6199. // Statistical analysis tools
  6200. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  6201. #include <cassert>
  6202. #include <random>
  6203. #if defined(CATCH_CONFIG_USE_ASYNC)
  6204. #include <future>
  6205. #endif
  6206. namespace {
  6207. double erf_inv(double x) {
  6208. // Code accompanying the article "Approximating the erfinv function" in GPU Computing Gems, Volume 2
  6209. double w, p;
  6210. w = -log((1.0 - x) * (1.0 + x));
  6211. if (w < 6.250000) {
  6212. w = w - 3.125000;
  6213. p = -3.6444120640178196996e-21;
  6214. p = -1.685059138182016589e-19 + p * w;
  6215. p = 1.2858480715256400167e-18 + p * w;
  6216. p = 1.115787767802518096e-17 + p * w;
  6217. p = -1.333171662854620906e-16 + p * w;
  6218. p = 2.0972767875968561637e-17 + p * w;
  6219. p = 6.6376381343583238325e-15 + p * w;
  6220. p = -4.0545662729752068639e-14 + p * w;
  6221. p = -8.1519341976054721522e-14 + p * w;
  6222. p = 2.6335093153082322977e-12 + p * w;
  6223. p = -1.2975133253453532498e-11 + p * w;
  6224. p = -5.4154120542946279317e-11 + p * w;
  6225. p = 1.051212273321532285e-09 + p * w;
  6226. p = -4.1126339803469836976e-09 + p * w;
  6227. p = -2.9070369957882005086e-08 + p * w;
  6228. p = 4.2347877827932403518e-07 + p * w;
  6229. p = -1.3654692000834678645e-06 + p * w;
  6230. p = -1.3882523362786468719e-05 + p * w;
  6231. p = 0.0001867342080340571352 + p * w;
  6232. p = -0.00074070253416626697512 + p * w;
  6233. p = -0.0060336708714301490533 + p * w;
  6234. p = 0.24015818242558961693 + p * w;
  6235. p = 1.6536545626831027356 + p * w;
  6236. } else if (w < 16.000000) {
  6237. w = sqrt(w) - 3.250000;
  6238. p = 2.2137376921775787049e-09;
  6239. p = 9.0756561938885390979e-08 + p * w;
  6240. p = -2.7517406297064545428e-07 + p * w;
  6241. p = 1.8239629214389227755e-08 + p * w;
  6242. p = 1.5027403968909827627e-06 + p * w;
  6243. p = -4.013867526981545969e-06 + p * w;
  6244. p = 2.9234449089955446044e-06 + p * w;
  6245. p = 1.2475304481671778723e-05 + p * w;
  6246. p = -4.7318229009055733981e-05 + p * w;
  6247. p = 6.8284851459573175448e-05 + p * w;
  6248. p = 2.4031110387097893999e-05 + p * w;
  6249. p = -0.0003550375203628474796 + p * w;
  6250. p = 0.00095328937973738049703 + p * w;
  6251. p = -0.0016882755560235047313 + p * w;
  6252. p = 0.0024914420961078508066 + p * w;
  6253. p = -0.0037512085075692412107 + p * w;
  6254. p = 0.005370914553590063617 + p * w;
  6255. p = 1.0052589676941592334 + p * w;
  6256. p = 3.0838856104922207635 + p * w;
  6257. } else {
  6258. w = sqrt(w) - 5.000000;
  6259. p = -2.7109920616438573243e-11;
  6260. p = -2.5556418169965252055e-10 + p * w;
  6261. p = 1.5076572693500548083e-09 + p * w;
  6262. p = -3.7894654401267369937e-09 + p * w;
  6263. p = 7.6157012080783393804e-09 + p * w;
  6264. p = -1.4960026627149240478e-08 + p * w;
  6265. p = 2.9147953450901080826e-08 + p * w;
  6266. p = -6.7711997758452339498e-08 + p * w;
  6267. p = 2.2900482228026654717e-07 + p * w;
  6268. p = -9.9298272942317002539e-07 + p * w;
  6269. p = 4.5260625972231537039e-06 + p * w;
  6270. p = -1.9681778105531670567e-05 + p * w;
  6271. p = 7.5995277030017761139e-05 + p * w;
  6272. p = -0.00021503011930044477347 + p * w;
  6273. p = -0.00013871931833623122026 + p * w;
  6274. p = 1.0103004648645343977 + p * w;
  6275. p = 4.8499064014085844221 + p * w;
  6276. }
  6277. return p * x;
  6278. }
  6279. double standard_deviation(std::vector<double>::iterator first, std::vector<double>::iterator last) {
  6280. auto m = Catch::Benchmark::Detail::mean(first, last);
  6281. double variance = std::accumulate(first, last, 0., [m](double a, double b) {
  6282. double diff = b - m;
  6283. return a + diff * diff;
  6284. }) / (last - first);
  6285. return std::sqrt(variance);
  6286. }
  6287. }
  6288. namespace Catch {
  6289. namespace Benchmark {
  6290. namespace Detail {
  6291. double weighted_average_quantile(int k, int q, std::vector<double>::iterator first, std::vector<double>::iterator last) {
  6292. auto count = last - first;
  6293. double idx = (count - 1) * k / static_cast<double>(q);
  6294. int j = static_cast<int>(idx);
  6295. double g = idx - j;
  6296. std::nth_element(first, first + j, last);
  6297. auto xj = first[j];
  6298. if (g == 0) return xj;
  6299. auto xj1 = *std::min_element(first + (j + 1), last);
  6300. return xj + g * (xj1 - xj);
  6301. }
  6302. double erfc_inv(double x) {
  6303. return erf_inv(1.0 - x);
  6304. }
  6305. double normal_quantile(double p) {
  6306. static const double ROOT_TWO = std::sqrt(2.0);
  6307. double result = 0.0;
  6308. assert(p >= 0 && p <= 1);
  6309. if (p < 0 || p > 1) {
  6310. return result;
  6311. }
  6312. result = -erfc_inv(2.0 * p);
  6313. // result *= normal distribution standard deviation (1.0) * sqrt(2)
  6314. result *= /*sd * */ ROOT_TWO;
  6315. // result += normal disttribution mean (0)
  6316. return result;
  6317. }
  6318. double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n) {
  6319. double sb = stddev.point;
  6320. double mn = mean.point / n;
  6321. double mg_min = mn / 2.;
  6322. double sg = (std::min)(mg_min / 4., sb / std::sqrt(n));
  6323. double sg2 = sg * sg;
  6324. double sb2 = sb * sb;
  6325. auto c_max = [n, mn, sb2, sg2](double x) -> double {
  6326. double k = mn - x;
  6327. double d = k * k;
  6328. double nd = n * d;
  6329. double k0 = -n * nd;
  6330. double k1 = sb2 - n * sg2 + nd;
  6331. double det = k1 * k1 - 4 * sg2 * k0;
  6332. return (int)(-2. * k0 / (k1 + std::sqrt(det)));
  6333. };
  6334. auto var_out = [n, sb2, sg2](double c) {
  6335. double nc = n - c;
  6336. return (nc / n) * (sb2 - nc * sg2);
  6337. };
  6338. return (std::min)(var_out(1), var_out((std::min)(c_max(0.), c_max(mg_min)))) / sb2;
  6339. }
  6340. bootstrap_analysis analyse_samples(double confidence_level, int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last) {
  6341. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION
  6342. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  6343. static std::random_device entropy;
  6344. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
  6345. auto n = static_cast<int>(last - first); // seriously, one can't use integral types without hell in C++
  6346. auto mean = &Detail::mean<std::vector<double>::iterator>;
  6347. auto stddev = &standard_deviation;
  6348. #if defined(CATCH_CONFIG_USE_ASYNC)
  6349. auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
  6350. auto seed = entropy();
  6351. return std::async(std::launch::async, [=] {
  6352. std::mt19937 rng(seed);
  6353. auto resampled = resample(rng, n_resamples, first, last, f);
  6354. return bootstrap(confidence_level, first, last, resampled, f);
  6355. });
  6356. };
  6357. auto mean_future = Estimate(mean);
  6358. auto stddev_future = Estimate(stddev);
  6359. auto mean_estimate = mean_future.get();
  6360. auto stddev_estimate = stddev_future.get();
  6361. #else
  6362. auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
  6363. auto seed = entropy();
  6364. std::mt19937 rng(seed);
  6365. auto resampled = resample(rng, n_resamples, first, last, f);
  6366. return bootstrap(confidence_level, first, last, resampled, f);
  6367. };
  6368. auto mean_estimate = Estimate(mean);
  6369. auto stddev_estimate = Estimate(stddev);
  6370. #endif // CATCH_USE_ASYNC
  6371. double outlier_variance = Detail::outlier_variance(mean_estimate, stddev_estimate, n);
  6372. return { mean_estimate, stddev_estimate, outlier_variance };
  6373. }
  6374. } // namespace Detail
  6375. } // namespace Benchmark
  6376. } // namespace Catch
  6377. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  6378. // end catch_stats.cpp
  6379. // start catch_approx.cpp
  6380. #include <cmath>
  6381. #include <limits>
  6382. namespace {
  6383. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  6384. // But without the subtraction to allow for INFINITY in comparison
  6385. bool marginComparison(double lhs, double rhs, double margin) {
  6386. return (lhs + margin >= rhs) && (rhs + margin >= lhs);
  6387. }
  6388. }
  6389. namespace Catch {
  6390. namespace Detail {
  6391. Approx::Approx ( double value )
  6392. : m_epsilon( std::numeric_limits<float>::epsilon()*100 ),
  6393. m_margin( 0.0 ),
  6394. m_scale( 0.0 ),
  6395. m_value( value )
  6396. {}
  6397. Approx Approx::custom() {
  6398. return Approx( 0 );
  6399. }
  6400. Approx Approx::operator-() const {
  6401. auto temp(*this);
  6402. temp.m_value = -temp.m_value;
  6403. return temp;
  6404. }
  6405. std::string Approx::toString() const {
  6406. ReusableStringStream rss;
  6407. rss << "Approx( " << ::Catch::Detail::stringify( m_value ) << " )";
  6408. return rss.str();
  6409. }
  6410. bool Approx::equalityComparisonImpl(const double other) const {
  6411. // First try with fixed margin, then compute margin based on epsilon, scale and Approx's value
  6412. // Thanks to Richard Harris for his help refining the scaled margin value
  6413. return marginComparison(m_value, other, m_margin)
  6414. || marginComparison(m_value, other, m_epsilon * (m_scale + std::fabs(std::isinf(m_value)? 0 : m_value)));
  6415. }
  6416. void Approx::setMargin(double newMargin) {
  6417. CATCH_ENFORCE(newMargin >= 0,
  6418. "Invalid Approx::margin: " << newMargin << '.'
  6419. << " Approx::Margin has to be non-negative.");
  6420. m_margin = newMargin;
  6421. }
  6422. void Approx::setEpsilon(double newEpsilon) {
  6423. CATCH_ENFORCE(newEpsilon >= 0 && newEpsilon <= 1.0,
  6424. "Invalid Approx::epsilon: " << newEpsilon << '.'
  6425. << " Approx::epsilon has to be in [0, 1]");
  6426. m_epsilon = newEpsilon;
  6427. }
  6428. } // end namespace Detail
  6429. namespace literals {
  6430. Detail::Approx operator "" _a(long double val) {
  6431. return Detail::Approx(val);
  6432. }
  6433. Detail::Approx operator "" _a(unsigned long long val) {
  6434. return Detail::Approx(val);
  6435. }
  6436. } // end namespace literals
  6437. std::string StringMaker<Catch::Detail::Approx>::convert(Catch::Detail::Approx const& value) {
  6438. return value.toString();
  6439. }
  6440. } // end namespace Catch
  6441. // end catch_approx.cpp
  6442. // start catch_assertionhandler.cpp
  6443. // start catch_debugger.h
  6444. namespace Catch {
  6445. bool isDebuggerActive();
  6446. }
  6447. #ifdef CATCH_PLATFORM_MAC
  6448. #if defined(__i386__) || defined(__x86_64__)
  6449. #define CATCH_TRAP() __asm__("int $3\n" : : ) /* NOLINT */
  6450. #elif defined(__aarch64__)
  6451. #define CATCH_TRAP() __asm__(".inst 0xd4200000")
  6452. #endif
  6453. #elif defined(CATCH_PLATFORM_IPHONE)
  6454. // use inline assembler
  6455. #if defined(__i386__) || defined(__x86_64__)
  6456. #define CATCH_TRAP() __asm__("int $3")
  6457. #elif defined(__aarch64__)
  6458. #define CATCH_TRAP() __asm__(".inst 0xd4200000")
  6459. #elif defined(__arm__) && !defined(__thumb__)
  6460. #define CATCH_TRAP() __asm__(".inst 0xe7f001f0")
  6461. #elif defined(__arm__) && defined(__thumb__)
  6462. #define CATCH_TRAP() __asm__(".inst 0xde01")
  6463. #endif
  6464. #elif defined(CATCH_PLATFORM_LINUX)
  6465. // If we can use inline assembler, do it because this allows us to break
  6466. // directly at the location of the failing check instead of breaking inside
  6467. // raise() called from it, i.e. one stack frame below.
  6468. #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64))
  6469. #define CATCH_TRAP() asm volatile ("int $3") /* NOLINT */
  6470. #else // Fall back to the generic way.
  6471. #include <signal.h>
  6472. #define CATCH_TRAP() raise(SIGTRAP)
  6473. #endif
  6474. #elif defined(_MSC_VER)
  6475. #define CATCH_TRAP() __debugbreak()
  6476. #elif defined(__MINGW32__)
  6477. extern "C" __declspec(dllimport) void __stdcall DebugBreak();
  6478. #define CATCH_TRAP() DebugBreak()
  6479. #endif
  6480. #ifndef CATCH_BREAK_INTO_DEBUGGER
  6481. #ifdef CATCH_TRAP
  6482. #define CATCH_BREAK_INTO_DEBUGGER() []{ if( Catch::isDebuggerActive() ) { CATCH_TRAP(); } }()
  6483. #else
  6484. #define CATCH_BREAK_INTO_DEBUGGER() []{}()
  6485. #endif
  6486. #endif
  6487. // end catch_debugger.h
  6488. // start catch_run_context.h
  6489. // start catch_fatal_condition.h
  6490. #include <cassert>
  6491. namespace Catch {
  6492. // Wrapper for platform-specific fatal error (signals/SEH) handlers
  6493. //
  6494. // Tries to be cooperative with other handlers, and not step over
  6495. // other handlers. This means that unknown structured exceptions
  6496. // are passed on, previous signal handlers are called, and so on.
  6497. //
  6498. // Can only be instantiated once, and assumes that once a signal
  6499. // is caught, the binary will end up terminating. Thus, there
  6500. class FatalConditionHandler {
  6501. bool m_started = false;
  6502. // Install/disengage implementation for specific platform.
  6503. // Should be if-defed to work on current platform, can assume
  6504. // engage-disengage 1:1 pairing.
  6505. void engage_platform();
  6506. void disengage_platform();
  6507. public:
  6508. // Should also have platform-specific implementations as needed
  6509. FatalConditionHandler();
  6510. ~FatalConditionHandler();
  6511. void engage() {
  6512. assert(!m_started && "Handler cannot be installed twice.");
  6513. m_started = true;
  6514. engage_platform();
  6515. }
  6516. void disengage() {
  6517. assert(m_started && "Handler cannot be uninstalled without being installed first");
  6518. m_started = false;
  6519. disengage_platform();
  6520. }
  6521. };
  6522. //! Simple RAII guard for (dis)engaging the FatalConditionHandler
  6523. class FatalConditionHandlerGuard {
  6524. FatalConditionHandler* m_handler;
  6525. public:
  6526. FatalConditionHandlerGuard(FatalConditionHandler* handler):
  6527. m_handler(handler) {
  6528. m_handler->engage();
  6529. }
  6530. ~FatalConditionHandlerGuard() {
  6531. m_handler->disengage();
  6532. }
  6533. };
  6534. } // end namespace Catch
  6535. // end catch_fatal_condition.h
  6536. #include <string>
  6537. namespace Catch {
  6538. struct IMutableContext;
  6539. ///////////////////////////////////////////////////////////////////////////
  6540. class RunContext : public IResultCapture, public IRunner {
  6541. public:
  6542. RunContext( RunContext const& ) = delete;
  6543. RunContext& operator =( RunContext const& ) = delete;
  6544. explicit RunContext( IConfigPtr const& _config, IStreamingReporterPtr&& reporter );
  6545. ~RunContext() override;
  6546. void testGroupStarting( std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount );
  6547. void testGroupEnded( std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount );
  6548. Totals runTest(TestCase const& testCase);
  6549. IConfigPtr config() const;
  6550. IStreamingReporter& reporter() const;
  6551. public: // IResultCapture
  6552. // Assertion handlers
  6553. void handleExpr
  6554. ( AssertionInfo const& info,
  6555. ITransientExpression const& expr,
  6556. AssertionReaction& reaction ) override;
  6557. void handleMessage
  6558. ( AssertionInfo const& info,
  6559. ResultWas::OfType resultType,
  6560. StringRef const& message,
  6561. AssertionReaction& reaction ) override;
  6562. void handleUnexpectedExceptionNotThrown
  6563. ( AssertionInfo const& info,
  6564. AssertionReaction& reaction ) override;
  6565. void handleUnexpectedInflightException
  6566. ( AssertionInfo const& info,
  6567. std::string const& message,
  6568. AssertionReaction& reaction ) override;
  6569. void handleIncomplete
  6570. ( AssertionInfo const& info ) override;
  6571. void handleNonExpr
  6572. ( AssertionInfo const &info,
  6573. ResultWas::OfType resultType,
  6574. AssertionReaction &reaction ) override;
  6575. bool sectionStarted( SectionInfo const& sectionInfo, Counts& assertions ) override;
  6576. void sectionEnded( SectionEndInfo const& endInfo ) override;
  6577. void sectionEndedEarly( SectionEndInfo const& endInfo ) override;
  6578. auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker& override;
  6579. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  6580. void benchmarkPreparing( std::string const& name ) override;
  6581. void benchmarkStarting( BenchmarkInfo const& info ) override;
  6582. void benchmarkEnded( BenchmarkStats<> const& stats ) override;
  6583. void benchmarkFailed( std::string const& error ) override;
  6584. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  6585. void pushScopedMessage( MessageInfo const& message ) override;
  6586. void popScopedMessage( MessageInfo const& message ) override;
  6587. void emplaceUnscopedMessage( MessageBuilder const& builder ) override;
  6588. std::string getCurrentTestName() const override;
  6589. const AssertionResult* getLastResult() const override;
  6590. void exceptionEarlyReported() override;
  6591. void handleFatalErrorCondition( StringRef message ) override;
  6592. bool lastAssertionPassed() override;
  6593. void assertionPassed() override;
  6594. public:
  6595. // !TBD We need to do this another way!
  6596. bool aborting() const final;
  6597. private:
  6598. void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr );
  6599. void invokeActiveTestCase();
  6600. void resetAssertionInfo();
  6601. bool testForMissingAssertions( Counts& assertions );
  6602. void assertionEnded( AssertionResult const& result );
  6603. void reportExpr
  6604. ( AssertionInfo const &info,
  6605. ResultWas::OfType resultType,
  6606. ITransientExpression const *expr,
  6607. bool negated );
  6608. void populateReaction( AssertionReaction& reaction );
  6609. private:
  6610. void handleUnfinishedSections();
  6611. TestRunInfo m_runInfo;
  6612. IMutableContext& m_context;
  6613. TestCase const* m_activeTestCase = nullptr;
  6614. ITracker* m_testCaseTracker = nullptr;
  6615. Option<AssertionResult> m_lastResult;
  6616. IConfigPtr m_config;
  6617. Totals m_totals;
  6618. IStreamingReporterPtr m_reporter;
  6619. std::vector<MessageInfo> m_messages;
  6620. std::vector<ScopedMessage> m_messageScopes; /* Keeps owners of so-called unscoped messages. */
  6621. AssertionInfo m_lastAssertionInfo;
  6622. std::vector<SectionEndInfo> m_unfinishedSections;
  6623. std::vector<ITracker*> m_activeSections;
  6624. TrackerContext m_trackerContext;
  6625. FatalConditionHandler m_fatalConditionhandler;
  6626. bool m_lastAssertionPassed = false;
  6627. bool m_shouldReportUnexpected = true;
  6628. bool m_includeSuccessfulResults;
  6629. };
  6630. void seedRng(IConfig const& config);
  6631. unsigned int rngSeed();
  6632. } // end namespace Catch
  6633. // end catch_run_context.h
  6634. namespace Catch {
  6635. namespace {
  6636. auto operator <<( std::ostream& os, ITransientExpression const& expr ) -> std::ostream& {
  6637. expr.streamReconstructedExpression( os );
  6638. return os;
  6639. }
  6640. }
  6641. LazyExpression::LazyExpression( bool isNegated )
  6642. : m_isNegated( isNegated )
  6643. {}
  6644. LazyExpression::LazyExpression( LazyExpression const& other ) : m_isNegated( other.m_isNegated ) {}
  6645. LazyExpression::operator bool() const {
  6646. return m_transientExpression != nullptr;
  6647. }
  6648. auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream& {
  6649. if( lazyExpr.m_isNegated )
  6650. os << "!";
  6651. if( lazyExpr ) {
  6652. if( lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression() )
  6653. os << "(" << *lazyExpr.m_transientExpression << ")";
  6654. else
  6655. os << *lazyExpr.m_transientExpression;
  6656. }
  6657. else {
  6658. os << "{** error - unchecked empty expression requested **}";
  6659. }
  6660. return os;
  6661. }
  6662. AssertionHandler::AssertionHandler
  6663. ( StringRef const& macroName,
  6664. SourceLineInfo const& lineInfo,
  6665. StringRef capturedExpression,
  6666. ResultDisposition::Flags resultDisposition )
  6667. : m_assertionInfo{ macroName, lineInfo, capturedExpression, resultDisposition },
  6668. m_resultCapture( getResultCapture() )
  6669. {}
  6670. void AssertionHandler::handleExpr( ITransientExpression const& expr ) {
  6671. m_resultCapture.handleExpr( m_assertionInfo, expr, m_reaction );
  6672. }
  6673. void AssertionHandler::handleMessage(ResultWas::OfType resultType, StringRef const& message) {
  6674. m_resultCapture.handleMessage( m_assertionInfo, resultType, message, m_reaction );
  6675. }
  6676. auto AssertionHandler::allowThrows() const -> bool {
  6677. return getCurrentContext().getConfig()->allowThrows();
  6678. }
  6679. void AssertionHandler::complete() {
  6680. setCompleted();
  6681. if( m_reaction.shouldDebugBreak ) {
  6682. // If you find your debugger stopping you here then go one level up on the
  6683. // call-stack for the code that caused it (typically a failed assertion)
  6684. // (To go back to the test and change execution, jump over the throw, next)
  6685. CATCH_BREAK_INTO_DEBUGGER();
  6686. }
  6687. if (m_reaction.shouldThrow) {
  6688. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  6689. throw Catch::TestFailureException();
  6690. #else
  6691. CATCH_ERROR( "Test failure requires aborting test!" );
  6692. #endif
  6693. }
  6694. }
  6695. void AssertionHandler::setCompleted() {
  6696. m_completed = true;
  6697. }
  6698. void AssertionHandler::handleUnexpectedInflightException() {
  6699. m_resultCapture.handleUnexpectedInflightException( m_assertionInfo, Catch::translateActiveException(), m_reaction );
  6700. }
  6701. void AssertionHandler::handleExceptionThrownAsExpected() {
  6702. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  6703. }
  6704. void AssertionHandler::handleExceptionNotThrownAsExpected() {
  6705. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  6706. }
  6707. void AssertionHandler::handleUnexpectedExceptionNotThrown() {
  6708. m_resultCapture.handleUnexpectedExceptionNotThrown( m_assertionInfo, m_reaction );
  6709. }
  6710. void AssertionHandler::handleThrowingCallSkipped() {
  6711. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  6712. }
  6713. // This is the overload that takes a string and infers the Equals matcher from it
  6714. // The more general overload, that takes any string matcher, is in catch_capture_matchers.cpp
  6715. void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString ) {
  6716. handleExceptionMatchExpr( handler, Matchers::Equals( str ), matcherString );
  6717. }
  6718. } // namespace Catch
  6719. // end catch_assertionhandler.cpp
  6720. // start catch_assertionresult.cpp
  6721. namespace Catch {
  6722. AssertionResultData::AssertionResultData(ResultWas::OfType _resultType, LazyExpression const & _lazyExpression):
  6723. lazyExpression(_lazyExpression),
  6724. resultType(_resultType) {}
  6725. std::string AssertionResultData::reconstructExpression() const {
  6726. if( reconstructedExpression.empty() ) {
  6727. if( lazyExpression ) {
  6728. ReusableStringStream rss;
  6729. rss << lazyExpression;
  6730. reconstructedExpression = rss.str();
  6731. }
  6732. }
  6733. return reconstructedExpression;
  6734. }
  6735. AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data )
  6736. : m_info( info ),
  6737. m_resultData( data )
  6738. {}
  6739. // Result was a success
  6740. bool AssertionResult::succeeded() const {
  6741. return Catch::isOk( m_resultData.resultType );
  6742. }
  6743. // Result was a success, or failure is suppressed
  6744. bool AssertionResult::isOk() const {
  6745. return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition );
  6746. }
  6747. ResultWas::OfType AssertionResult::getResultType() const {
  6748. return m_resultData.resultType;
  6749. }
  6750. bool AssertionResult::hasExpression() const {
  6751. return !m_info.capturedExpression.empty();
  6752. }
  6753. bool AssertionResult::hasMessage() const {
  6754. return !m_resultData.message.empty();
  6755. }
  6756. std::string AssertionResult::getExpression() const {
  6757. // Possibly overallocating by 3 characters should be basically free
  6758. std::string expr; expr.reserve(m_info.capturedExpression.size() + 3);
  6759. if (isFalseTest(m_info.resultDisposition)) {
  6760. expr += "!(";
  6761. }
  6762. expr += m_info.capturedExpression;
  6763. if (isFalseTest(m_info.resultDisposition)) {
  6764. expr += ')';
  6765. }
  6766. return expr;
  6767. }
  6768. std::string AssertionResult::getExpressionInMacro() const {
  6769. std::string expr;
  6770. if( m_info.macroName.empty() )
  6771. expr = static_cast<std::string>(m_info.capturedExpression);
  6772. else {
  6773. expr.reserve( m_info.macroName.size() + m_info.capturedExpression.size() + 4 );
  6774. expr += m_info.macroName;
  6775. expr += "( ";
  6776. expr += m_info.capturedExpression;
  6777. expr += " )";
  6778. }
  6779. return expr;
  6780. }
  6781. bool AssertionResult::hasExpandedExpression() const {
  6782. return hasExpression() && getExpandedExpression() != getExpression();
  6783. }
  6784. std::string AssertionResult::getExpandedExpression() const {
  6785. std::string expr = m_resultData.reconstructExpression();
  6786. return expr.empty()
  6787. ? getExpression()
  6788. : expr;
  6789. }
  6790. std::string AssertionResult::getMessage() const {
  6791. return m_resultData.message;
  6792. }
  6793. SourceLineInfo AssertionResult::getSourceInfo() const {
  6794. return m_info.lineInfo;
  6795. }
  6796. StringRef AssertionResult::getTestMacroName() const {
  6797. return m_info.macroName;
  6798. }
  6799. } // end namespace Catch
  6800. // end catch_assertionresult.cpp
  6801. // start catch_capture_matchers.cpp
  6802. namespace Catch {
  6803. using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
  6804. // This is the general overload that takes a any string matcher
  6805. // There is another overload, in catch_assertionhandler.h/.cpp, that only takes a string and infers
  6806. // the Equals matcher (so the header does not mention matchers)
  6807. void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString ) {
  6808. std::string exceptionMessage = Catch::translateActiveException();
  6809. MatchExpr<std::string, StringMatcher const&> expr( exceptionMessage, matcher, matcherString );
  6810. handler.handleExpr( expr );
  6811. }
  6812. } // namespace Catch
  6813. // end catch_capture_matchers.cpp
  6814. // start catch_commandline.cpp
  6815. // start catch_commandline.h
  6816. // start catch_clara.h
  6817. // Use Catch's value for console width (store Clara's off to the side, if present)
  6818. #ifdef CLARA_CONFIG_CONSOLE_WIDTH
  6819. #define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  6820. #undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  6821. #endif
  6822. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH-1
  6823. #ifdef __clang__
  6824. #pragma clang diagnostic push
  6825. #pragma clang diagnostic ignored "-Wweak-vtables"
  6826. #pragma clang diagnostic ignored "-Wexit-time-destructors"
  6827. #pragma clang diagnostic ignored "-Wshadow"
  6828. #endif
  6829. // start clara.hpp
  6830. // Copyright 2017 Two Blue Cubes Ltd. All rights reserved.
  6831. //
  6832. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  6833. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6834. //
  6835. // See https://github.com/philsquared/Clara for more details
  6836. // Clara v1.1.5
  6837. #ifndef CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  6838. #define CATCH_CLARA_CONFIG_CONSOLE_WIDTH 80
  6839. #endif
  6840. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  6841. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  6842. #endif
  6843. #ifndef CLARA_CONFIG_OPTIONAL_TYPE
  6844. #ifdef __has_include
  6845. #if __has_include(<optional>) && __cplusplus >= 201703L
  6846. #include <optional>
  6847. #define CLARA_CONFIG_OPTIONAL_TYPE std::optional
  6848. #endif
  6849. #endif
  6850. #endif
  6851. // ----------- #included from clara_textflow.hpp -----------
  6852. // TextFlowCpp
  6853. //
  6854. // A single-header library for wrapping and laying out basic text, by Phil Nash
  6855. //
  6856. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  6857. // file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6858. //
  6859. // This project is hosted at https://github.com/philsquared/textflowcpp
  6860. #include <cassert>
  6861. #include <ostream>
  6862. #include <sstream>
  6863. #include <vector>
  6864. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  6865. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80
  6866. #endif
  6867. namespace Catch {
  6868. namespace clara {
  6869. namespace TextFlow {
  6870. inline auto isWhitespace(char c) -> bool {
  6871. static std::string chars = " \t\n\r";
  6872. return chars.find(c) != std::string::npos;
  6873. }
  6874. inline auto isBreakableBefore(char c) -> bool {
  6875. static std::string chars = "[({<|";
  6876. return chars.find(c) != std::string::npos;
  6877. }
  6878. inline auto isBreakableAfter(char c) -> bool {
  6879. static std::string chars = "])}>.,:;*+-=&/\\";
  6880. return chars.find(c) != std::string::npos;
  6881. }
  6882. class Columns;
  6883. class Column {
  6884. std::vector<std::string> m_strings;
  6885. size_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH;
  6886. size_t m_indent = 0;
  6887. size_t m_initialIndent = std::string::npos;
  6888. public:
  6889. class iterator {
  6890. friend Column;
  6891. Column const& m_column;
  6892. size_t m_stringIndex = 0;
  6893. size_t m_pos = 0;
  6894. size_t m_len = 0;
  6895. size_t m_end = 0;
  6896. bool m_suffix = false;
  6897. iterator(Column const& column, size_t stringIndex)
  6898. : m_column(column),
  6899. m_stringIndex(stringIndex) {}
  6900. auto line() const -> std::string const& { return m_column.m_strings[m_stringIndex]; }
  6901. auto isBoundary(size_t at) const -> bool {
  6902. assert(at > 0);
  6903. assert(at <= line().size());
  6904. return at == line().size() ||
  6905. (isWhitespace(line()[at]) && !isWhitespace(line()[at - 1])) ||
  6906. isBreakableBefore(line()[at]) ||
  6907. isBreakableAfter(line()[at - 1]);
  6908. }
  6909. void calcLength() {
  6910. assert(m_stringIndex < m_column.m_strings.size());
  6911. m_suffix = false;
  6912. auto width = m_column.m_width - indent();
  6913. m_end = m_pos;
  6914. if (line()[m_pos] == '\n') {
  6915. ++m_end;
  6916. }
  6917. while (m_end < line().size() && line()[m_end] != '\n')
  6918. ++m_end;
  6919. if (m_end < m_pos + width) {
  6920. m_len = m_end - m_pos;
  6921. } else {
  6922. size_t len = width;
  6923. while (len > 0 && !isBoundary(m_pos + len))
  6924. --len;
  6925. while (len > 0 && isWhitespace(line()[m_pos + len - 1]))
  6926. --len;
  6927. if (len > 0) {
  6928. m_len = len;
  6929. } else {
  6930. m_suffix = true;
  6931. m_len = width - 1;
  6932. }
  6933. }
  6934. }
  6935. auto indent() const -> size_t {
  6936. auto initial = m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos;
  6937. return initial == std::string::npos ? m_column.m_indent : initial;
  6938. }
  6939. auto addIndentAndSuffix(std::string const &plain) const -> std::string {
  6940. return std::string(indent(), ' ') + (m_suffix ? plain + "-" : plain);
  6941. }
  6942. public:
  6943. using difference_type = std::ptrdiff_t;
  6944. using value_type = std::string;
  6945. using pointer = value_type * ;
  6946. using reference = value_type & ;
  6947. using iterator_category = std::forward_iterator_tag;
  6948. explicit iterator(Column const& column) : m_column(column) {
  6949. assert(m_column.m_width > m_column.m_indent);
  6950. assert(m_column.m_initialIndent == std::string::npos || m_column.m_width > m_column.m_initialIndent);
  6951. calcLength();
  6952. if (m_len == 0)
  6953. m_stringIndex++; // Empty string
  6954. }
  6955. auto operator *() const -> std::string {
  6956. assert(m_stringIndex < m_column.m_strings.size());
  6957. assert(m_pos <= m_end);
  6958. return addIndentAndSuffix(line().substr(m_pos, m_len));
  6959. }
  6960. auto operator ++() -> iterator& {
  6961. m_pos += m_len;
  6962. if (m_pos < line().size() && line()[m_pos] == '\n')
  6963. m_pos += 1;
  6964. else
  6965. while (m_pos < line().size() && isWhitespace(line()[m_pos]))
  6966. ++m_pos;
  6967. if (m_pos == line().size()) {
  6968. m_pos = 0;
  6969. ++m_stringIndex;
  6970. }
  6971. if (m_stringIndex < m_column.m_strings.size())
  6972. calcLength();
  6973. return *this;
  6974. }
  6975. auto operator ++(int) -> iterator {
  6976. iterator prev(*this);
  6977. operator++();
  6978. return prev;
  6979. }
  6980. auto operator ==(iterator const& other) const -> bool {
  6981. return
  6982. m_pos == other.m_pos &&
  6983. m_stringIndex == other.m_stringIndex &&
  6984. &m_column == &other.m_column;
  6985. }
  6986. auto operator !=(iterator const& other) const -> bool {
  6987. return !operator==(other);
  6988. }
  6989. };
  6990. using const_iterator = iterator;
  6991. explicit Column(std::string const& text) { m_strings.push_back(text); }
  6992. auto width(size_t newWidth) -> Column& {
  6993. assert(newWidth > 0);
  6994. m_width = newWidth;
  6995. return *this;
  6996. }
  6997. auto indent(size_t newIndent) -> Column& {
  6998. m_indent = newIndent;
  6999. return *this;
  7000. }
  7001. auto initialIndent(size_t newIndent) -> Column& {
  7002. m_initialIndent = newIndent;
  7003. return *this;
  7004. }
  7005. auto width() const -> size_t { return m_width; }
  7006. auto begin() const -> iterator { return iterator(*this); }
  7007. auto end() const -> iterator { return { *this, m_strings.size() }; }
  7008. inline friend std::ostream& operator << (std::ostream& os, Column const& col) {
  7009. bool first = true;
  7010. for (auto line : col) {
  7011. if (first)
  7012. first = false;
  7013. else
  7014. os << "\n";
  7015. os << line;
  7016. }
  7017. return os;
  7018. }
  7019. auto operator + (Column const& other)->Columns;
  7020. auto toString() const -> std::string {
  7021. std::ostringstream oss;
  7022. oss << *this;
  7023. return oss.str();
  7024. }
  7025. };
  7026. class Spacer : public Column {
  7027. public:
  7028. explicit Spacer(size_t spaceWidth) : Column("") {
  7029. width(spaceWidth);
  7030. }
  7031. };
  7032. class Columns {
  7033. std::vector<Column> m_columns;
  7034. public:
  7035. class iterator {
  7036. friend Columns;
  7037. struct EndTag {};
  7038. std::vector<Column> const& m_columns;
  7039. std::vector<Column::iterator> m_iterators;
  7040. size_t m_activeIterators;
  7041. iterator(Columns const& columns, EndTag)
  7042. : m_columns(columns.m_columns),
  7043. m_activeIterators(0) {
  7044. m_iterators.reserve(m_columns.size());
  7045. for (auto const& col : m_columns)
  7046. m_iterators.push_back(col.end());
  7047. }
  7048. public:
  7049. using difference_type = std::ptrdiff_t;
  7050. using value_type = std::string;
  7051. using pointer = value_type * ;
  7052. using reference = value_type & ;
  7053. using iterator_category = std::forward_iterator_tag;
  7054. explicit iterator(Columns const& columns)
  7055. : m_columns(columns.m_columns),
  7056. m_activeIterators(m_columns.size()) {
  7057. m_iterators.reserve(m_columns.size());
  7058. for (auto const& col : m_columns)
  7059. m_iterators.push_back(col.begin());
  7060. }
  7061. auto operator ==(iterator const& other) const -> bool {
  7062. return m_iterators == other.m_iterators;
  7063. }
  7064. auto operator !=(iterator const& other) const -> bool {
  7065. return m_iterators != other.m_iterators;
  7066. }
  7067. auto operator *() const -> std::string {
  7068. std::string row, padding;
  7069. for (size_t i = 0; i < m_columns.size(); ++i) {
  7070. auto width = m_columns[i].width();
  7071. if (m_iterators[i] != m_columns[i].end()) {
  7072. std::string col = *m_iterators[i];
  7073. row += padding + col;
  7074. if (col.size() < width)
  7075. padding = std::string(width - col.size(), ' ');
  7076. else
  7077. padding = "";
  7078. } else {
  7079. padding += std::string(width, ' ');
  7080. }
  7081. }
  7082. return row;
  7083. }
  7084. auto operator ++() -> iterator& {
  7085. for (size_t i = 0; i < m_columns.size(); ++i) {
  7086. if (m_iterators[i] != m_columns[i].end())
  7087. ++m_iterators[i];
  7088. }
  7089. return *this;
  7090. }
  7091. auto operator ++(int) -> iterator {
  7092. iterator prev(*this);
  7093. operator++();
  7094. return prev;
  7095. }
  7096. };
  7097. using const_iterator = iterator;
  7098. auto begin() const -> iterator { return iterator(*this); }
  7099. auto end() const -> iterator { return { *this, iterator::EndTag() }; }
  7100. auto operator += (Column const& col) -> Columns& {
  7101. m_columns.push_back(col);
  7102. return *this;
  7103. }
  7104. auto operator + (Column const& col) -> Columns {
  7105. Columns combined = *this;
  7106. combined += col;
  7107. return combined;
  7108. }
  7109. inline friend std::ostream& operator << (std::ostream& os, Columns const& cols) {
  7110. bool first = true;
  7111. for (auto line : cols) {
  7112. if (first)
  7113. first = false;
  7114. else
  7115. os << "\n";
  7116. os << line;
  7117. }
  7118. return os;
  7119. }
  7120. auto toString() const -> std::string {
  7121. std::ostringstream oss;
  7122. oss << *this;
  7123. return oss.str();
  7124. }
  7125. };
  7126. inline auto Column::operator + (Column const& other) -> Columns {
  7127. Columns cols;
  7128. cols += *this;
  7129. cols += other;
  7130. return cols;
  7131. }
  7132. }
  7133. }
  7134. }
  7135. // ----------- end of #include from clara_textflow.hpp -----------
  7136. // ........... back in clara.hpp
  7137. #include <cctype>
  7138. #include <string>
  7139. #include <memory>
  7140. #include <set>
  7141. #include <algorithm>
  7142. #if !defined(CATCH_PLATFORM_WINDOWS) && ( defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) )
  7143. #define CATCH_PLATFORM_WINDOWS
  7144. #endif
  7145. namespace Catch { namespace clara {
  7146. namespace detail {
  7147. // Traits for extracting arg and return type of lambdas (for single argument lambdas)
  7148. template<typename L>
  7149. struct UnaryLambdaTraits : UnaryLambdaTraits<decltype( &L::operator() )> {};
  7150. template<typename ClassT, typename ReturnT, typename... Args>
  7151. struct UnaryLambdaTraits<ReturnT( ClassT::* )( Args... ) const> {
  7152. static const bool isValid = false;
  7153. };
  7154. template<typename ClassT, typename ReturnT, typename ArgT>
  7155. struct UnaryLambdaTraits<ReturnT( ClassT::* )( ArgT ) const> {
  7156. static const bool isValid = true;
  7157. using ArgType = typename std::remove_const<typename std::remove_reference<ArgT>::type>::type;
  7158. using ReturnType = ReturnT;
  7159. };
  7160. class TokenStream;
  7161. // Transport for raw args (copied from main args, or supplied via init list for testing)
  7162. class Args {
  7163. friend TokenStream;
  7164. std::string m_exeName;
  7165. std::vector<std::string> m_args;
  7166. public:
  7167. Args( int argc, char const* const* argv )
  7168. : m_exeName(argv[0]),
  7169. m_args(argv + 1, argv + argc) {}
  7170. Args( std::initializer_list<std::string> args )
  7171. : m_exeName( *args.begin() ),
  7172. m_args( args.begin()+1, args.end() )
  7173. {}
  7174. auto exeName() const -> std::string {
  7175. return m_exeName;
  7176. }
  7177. };
  7178. // Wraps a token coming from a token stream. These may not directly correspond to strings as a single string
  7179. // may encode an option + its argument if the : or = form is used
  7180. enum class TokenType {
  7181. Option, Argument
  7182. };
  7183. struct Token {
  7184. TokenType type;
  7185. std::string token;
  7186. };
  7187. inline auto isOptPrefix( char c ) -> bool {
  7188. return c == '-'
  7189. #ifdef CATCH_PLATFORM_WINDOWS
  7190. || c == '/'
  7191. #endif
  7192. ;
  7193. }
  7194. // Abstracts iterators into args as a stream of tokens, with option arguments uniformly handled
  7195. class TokenStream {
  7196. using Iterator = std::vector<std::string>::const_iterator;
  7197. Iterator it;
  7198. Iterator itEnd;
  7199. std::vector<Token> m_tokenBuffer;
  7200. void loadBuffer() {
  7201. m_tokenBuffer.resize( 0 );
  7202. // Skip any empty strings
  7203. while( it != itEnd && it->empty() )
  7204. ++it;
  7205. if( it != itEnd ) {
  7206. auto const &next = *it;
  7207. if( isOptPrefix( next[0] ) ) {
  7208. auto delimiterPos = next.find_first_of( " :=" );
  7209. if( delimiterPos != std::string::npos ) {
  7210. m_tokenBuffer.push_back( { TokenType::Option, next.substr( 0, delimiterPos ) } );
  7211. m_tokenBuffer.push_back( { TokenType::Argument, next.substr( delimiterPos + 1 ) } );
  7212. } else {
  7213. if( next[1] != '-' && next.size() > 2 ) {
  7214. std::string opt = "- ";
  7215. for( size_t i = 1; i < next.size(); ++i ) {
  7216. opt[1] = next[i];
  7217. m_tokenBuffer.push_back( { TokenType::Option, opt } );
  7218. }
  7219. } else {
  7220. m_tokenBuffer.push_back( { TokenType::Option, next } );
  7221. }
  7222. }
  7223. } else {
  7224. m_tokenBuffer.push_back( { TokenType::Argument, next } );
  7225. }
  7226. }
  7227. }
  7228. public:
  7229. explicit TokenStream( Args const &args ) : TokenStream( args.m_args.begin(), args.m_args.end() ) {}
  7230. TokenStream( Iterator it, Iterator itEnd ) : it( it ), itEnd( itEnd ) {
  7231. loadBuffer();
  7232. }
  7233. explicit operator bool() const {
  7234. return !m_tokenBuffer.empty() || it != itEnd;
  7235. }
  7236. auto count() const -> size_t { return m_tokenBuffer.size() + (itEnd - it); }
  7237. auto operator*() const -> Token {
  7238. assert( !m_tokenBuffer.empty() );
  7239. return m_tokenBuffer.front();
  7240. }
  7241. auto operator->() const -> Token const * {
  7242. assert( !m_tokenBuffer.empty() );
  7243. return &m_tokenBuffer.front();
  7244. }
  7245. auto operator++() -> TokenStream & {
  7246. if( m_tokenBuffer.size() >= 2 ) {
  7247. m_tokenBuffer.erase( m_tokenBuffer.begin() );
  7248. } else {
  7249. if( it != itEnd )
  7250. ++it;
  7251. loadBuffer();
  7252. }
  7253. return *this;
  7254. }
  7255. };
  7256. class ResultBase {
  7257. public:
  7258. enum Type {
  7259. Ok, LogicError, RuntimeError
  7260. };
  7261. protected:
  7262. ResultBase( Type type ) : m_type( type ) {}
  7263. virtual ~ResultBase() = default;
  7264. virtual void enforceOk() const = 0;
  7265. Type m_type;
  7266. };
  7267. template<typename T>
  7268. class ResultValueBase : public ResultBase {
  7269. public:
  7270. auto value() const -> T const & {
  7271. enforceOk();
  7272. return m_value;
  7273. }
  7274. protected:
  7275. ResultValueBase( Type type ) : ResultBase( type ) {}
  7276. ResultValueBase( ResultValueBase const &other ) : ResultBase( other ) {
  7277. if( m_type == ResultBase::Ok )
  7278. new( &m_value ) T( other.m_value );
  7279. }
  7280. ResultValueBase( Type, T const &value ) : ResultBase( Ok ) {
  7281. new( &m_value ) T( value );
  7282. }
  7283. auto operator=( ResultValueBase const &other ) -> ResultValueBase & {
  7284. if( m_type == ResultBase::Ok )
  7285. m_value.~T();
  7286. ResultBase::operator=(other);
  7287. if( m_type == ResultBase::Ok )
  7288. new( &m_value ) T( other.m_value );
  7289. return *this;
  7290. }
  7291. ~ResultValueBase() override {
  7292. if( m_type == Ok )
  7293. m_value.~T();
  7294. }
  7295. union {
  7296. T m_value;
  7297. };
  7298. };
  7299. template<>
  7300. class ResultValueBase<void> : public ResultBase {
  7301. protected:
  7302. using ResultBase::ResultBase;
  7303. };
  7304. template<typename T = void>
  7305. class BasicResult : public ResultValueBase<T> {
  7306. public:
  7307. template<typename U>
  7308. explicit BasicResult( BasicResult<U> const &other )
  7309. : ResultValueBase<T>( other.type() ),
  7310. m_errorMessage( other.errorMessage() )
  7311. {
  7312. assert( type() != ResultBase::Ok );
  7313. }
  7314. template<typename U>
  7315. static auto ok( U const &value ) -> BasicResult { return { ResultBase::Ok, value }; }
  7316. static auto ok() -> BasicResult { return { ResultBase::Ok }; }
  7317. static auto logicError( std::string const &message ) -> BasicResult { return { ResultBase::LogicError, message }; }
  7318. static auto runtimeError( std::string const &message ) -> BasicResult { return { ResultBase::RuntimeError, message }; }
  7319. explicit operator bool() const { return m_type == ResultBase::Ok; }
  7320. auto type() const -> ResultBase::Type { return m_type; }
  7321. auto errorMessage() const -> std::string { return m_errorMessage; }
  7322. protected:
  7323. void enforceOk() const override {
  7324. // Errors shouldn't reach this point, but if they do
  7325. // the actual error message will be in m_errorMessage
  7326. assert( m_type != ResultBase::LogicError );
  7327. assert( m_type != ResultBase::RuntimeError );
  7328. if( m_type != ResultBase::Ok )
  7329. std::abort();
  7330. }
  7331. std::string m_errorMessage; // Only populated if resultType is an error
  7332. BasicResult( ResultBase::Type type, std::string const &message )
  7333. : ResultValueBase<T>(type),
  7334. m_errorMessage(message)
  7335. {
  7336. assert( m_type != ResultBase::Ok );
  7337. }
  7338. using ResultValueBase<T>::ResultValueBase;
  7339. using ResultBase::m_type;
  7340. };
  7341. enum class ParseResultType {
  7342. Matched, NoMatch, ShortCircuitAll, ShortCircuitSame
  7343. };
  7344. class ParseState {
  7345. public:
  7346. ParseState( ParseResultType type, TokenStream const &remainingTokens )
  7347. : m_type(type),
  7348. m_remainingTokens( remainingTokens )
  7349. {}
  7350. auto type() const -> ParseResultType { return m_type; }
  7351. auto remainingTokens() const -> TokenStream { return m_remainingTokens; }
  7352. private:
  7353. ParseResultType m_type;
  7354. TokenStream m_remainingTokens;
  7355. };
  7356. using Result = BasicResult<void>;
  7357. using ParserResult = BasicResult<ParseResultType>;
  7358. using InternalParseResult = BasicResult<ParseState>;
  7359. struct HelpColumns {
  7360. std::string left;
  7361. std::string right;
  7362. };
  7363. template<typename T>
  7364. inline auto convertInto( std::string const &source, T& target ) -> ParserResult {
  7365. std::stringstream ss;
  7366. ss << source;
  7367. ss >> target;
  7368. if( ss.fail() )
  7369. return ParserResult::runtimeError( "Unable to convert '" + source + "' to destination type" );
  7370. else
  7371. return ParserResult::ok( ParseResultType::Matched );
  7372. }
  7373. inline auto convertInto( std::string const &source, std::string& target ) -> ParserResult {
  7374. target = source;
  7375. return ParserResult::ok( ParseResultType::Matched );
  7376. }
  7377. inline auto convertInto( std::string const &source, bool &target ) -> ParserResult {
  7378. std::string srcLC = source;
  7379. std::transform( srcLC.begin(), srcLC.end(), srcLC.begin(), []( unsigned char c ) { return static_cast<char>( std::tolower(c) ); } );
  7380. if (srcLC == "y" || srcLC == "1" || srcLC == "true" || srcLC == "yes" || srcLC == "on")
  7381. target = true;
  7382. else if (srcLC == "n" || srcLC == "0" || srcLC == "false" || srcLC == "no" || srcLC == "off")
  7383. target = false;
  7384. else
  7385. return ParserResult::runtimeError( "Expected a boolean value but did not recognise: '" + source + "'" );
  7386. return ParserResult::ok( ParseResultType::Matched );
  7387. }
  7388. #ifdef CLARA_CONFIG_OPTIONAL_TYPE
  7389. template<typename T>
  7390. inline auto convertInto( std::string const &source, CLARA_CONFIG_OPTIONAL_TYPE<T>& target ) -> ParserResult {
  7391. T temp;
  7392. auto result = convertInto( source, temp );
  7393. if( result )
  7394. target = std::move(temp);
  7395. return result;
  7396. }
  7397. #endif // CLARA_CONFIG_OPTIONAL_TYPE
  7398. struct NonCopyable {
  7399. NonCopyable() = default;
  7400. NonCopyable( NonCopyable const & ) = delete;
  7401. NonCopyable( NonCopyable && ) = delete;
  7402. NonCopyable &operator=( NonCopyable const & ) = delete;
  7403. NonCopyable &operator=( NonCopyable && ) = delete;
  7404. };
  7405. struct BoundRef : NonCopyable {
  7406. virtual ~BoundRef() = default;
  7407. virtual auto isContainer() const -> bool { return false; }
  7408. virtual auto isFlag() const -> bool { return false; }
  7409. };
  7410. struct BoundValueRefBase : BoundRef {
  7411. virtual auto setValue( std::string const &arg ) -> ParserResult = 0;
  7412. };
  7413. struct BoundFlagRefBase : BoundRef {
  7414. virtual auto setFlag( bool flag ) -> ParserResult = 0;
  7415. virtual auto isFlag() const -> bool { return true; }
  7416. };
  7417. template<typename T>
  7418. struct BoundValueRef : BoundValueRefBase {
  7419. T &m_ref;
  7420. explicit BoundValueRef( T &ref ) : m_ref( ref ) {}
  7421. auto setValue( std::string const &arg ) -> ParserResult override {
  7422. return convertInto( arg, m_ref );
  7423. }
  7424. };
  7425. template<typename T>
  7426. struct BoundValueRef<std::vector<T>> : BoundValueRefBase {
  7427. std::vector<T> &m_ref;
  7428. explicit BoundValueRef( std::vector<T> &ref ) : m_ref( ref ) {}
  7429. auto isContainer() const -> bool override { return true; }
  7430. auto setValue( std::string const &arg ) -> ParserResult override {
  7431. T temp;
  7432. auto result = convertInto( arg, temp );
  7433. if( result )
  7434. m_ref.push_back( temp );
  7435. return result;
  7436. }
  7437. };
  7438. struct BoundFlagRef : BoundFlagRefBase {
  7439. bool &m_ref;
  7440. explicit BoundFlagRef( bool &ref ) : m_ref( ref ) {}
  7441. auto setFlag( bool flag ) -> ParserResult override {
  7442. m_ref = flag;
  7443. return ParserResult::ok( ParseResultType::Matched );
  7444. }
  7445. };
  7446. template<typename ReturnType>
  7447. struct LambdaInvoker {
  7448. static_assert( std::is_same<ReturnType, ParserResult>::value, "Lambda must return void or clara::ParserResult" );
  7449. template<typename L, typename ArgType>
  7450. static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
  7451. return lambda( arg );
  7452. }
  7453. };
  7454. template<>
  7455. struct LambdaInvoker<void> {
  7456. template<typename L, typename ArgType>
  7457. static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
  7458. lambda( arg );
  7459. return ParserResult::ok( ParseResultType::Matched );
  7460. }
  7461. };
  7462. template<typename ArgType, typename L>
  7463. inline auto invokeLambda( L const &lambda, std::string const &arg ) -> ParserResult {
  7464. ArgType temp{};
  7465. auto result = convertInto( arg, temp );
  7466. return !result
  7467. ? result
  7468. : LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( lambda, temp );
  7469. }
  7470. template<typename L>
  7471. struct BoundLambda : BoundValueRefBase {
  7472. L m_lambda;
  7473. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  7474. explicit BoundLambda( L const &lambda ) : m_lambda( lambda ) {}
  7475. auto setValue( std::string const &arg ) -> ParserResult override {
  7476. return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>( m_lambda, arg );
  7477. }
  7478. };
  7479. template<typename L>
  7480. struct BoundFlagLambda : BoundFlagRefBase {
  7481. L m_lambda;
  7482. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  7483. static_assert( std::is_same<typename UnaryLambdaTraits<L>::ArgType, bool>::value, "flags must be boolean" );
  7484. explicit BoundFlagLambda( L const &lambda ) : m_lambda( lambda ) {}
  7485. auto setFlag( bool flag ) -> ParserResult override {
  7486. return LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( m_lambda, flag );
  7487. }
  7488. };
  7489. enum class Optionality { Optional, Required };
  7490. struct Parser;
  7491. class ParserBase {
  7492. public:
  7493. virtual ~ParserBase() = default;
  7494. virtual auto validate() const -> Result { return Result::ok(); }
  7495. virtual auto parse( std::string const& exeName, TokenStream const &tokens) const -> InternalParseResult = 0;
  7496. virtual auto cardinality() const -> size_t { return 1; }
  7497. auto parse( Args const &args ) const -> InternalParseResult {
  7498. return parse( args.exeName(), TokenStream( args ) );
  7499. }
  7500. };
  7501. template<typename DerivedT>
  7502. class ComposableParserImpl : public ParserBase {
  7503. public:
  7504. template<typename T>
  7505. auto operator|( T const &other ) const -> Parser;
  7506. template<typename T>
  7507. auto operator+( T const &other ) const -> Parser;
  7508. };
  7509. // Common code and state for Args and Opts
  7510. template<typename DerivedT>
  7511. class ParserRefImpl : public ComposableParserImpl<DerivedT> {
  7512. protected:
  7513. Optionality m_optionality = Optionality::Optional;
  7514. std::shared_ptr<BoundRef> m_ref;
  7515. std::string m_hint;
  7516. std::string m_description;
  7517. explicit ParserRefImpl( std::shared_ptr<BoundRef> const &ref ) : m_ref( ref ) {}
  7518. public:
  7519. template<typename T>
  7520. ParserRefImpl( T &ref, std::string const &hint )
  7521. : m_ref( std::make_shared<BoundValueRef<T>>( ref ) ),
  7522. m_hint( hint )
  7523. {}
  7524. template<typename LambdaT>
  7525. ParserRefImpl( LambdaT const &ref, std::string const &hint )
  7526. : m_ref( std::make_shared<BoundLambda<LambdaT>>( ref ) ),
  7527. m_hint(hint)
  7528. {}
  7529. auto operator()( std::string const &description ) -> DerivedT & {
  7530. m_description = description;
  7531. return static_cast<DerivedT &>( *this );
  7532. }
  7533. auto optional() -> DerivedT & {
  7534. m_optionality = Optionality::Optional;
  7535. return static_cast<DerivedT &>( *this );
  7536. };
  7537. auto required() -> DerivedT & {
  7538. m_optionality = Optionality::Required;
  7539. return static_cast<DerivedT &>( *this );
  7540. };
  7541. auto isOptional() const -> bool {
  7542. return m_optionality == Optionality::Optional;
  7543. }
  7544. auto cardinality() const -> size_t override {
  7545. if( m_ref->isContainer() )
  7546. return 0;
  7547. else
  7548. return 1;
  7549. }
  7550. auto hint() const -> std::string { return m_hint; }
  7551. };
  7552. class ExeName : public ComposableParserImpl<ExeName> {
  7553. std::shared_ptr<std::string> m_name;
  7554. std::shared_ptr<BoundValueRefBase> m_ref;
  7555. template<typename LambdaT>
  7556. static auto makeRef(LambdaT const &lambda) -> std::shared_ptr<BoundValueRefBase> {
  7557. return std::make_shared<BoundLambda<LambdaT>>( lambda) ;
  7558. }
  7559. public:
  7560. ExeName() : m_name( std::make_shared<std::string>( "<executable>" ) ) {}
  7561. explicit ExeName( std::string &ref ) : ExeName() {
  7562. m_ref = std::make_shared<BoundValueRef<std::string>>( ref );
  7563. }
  7564. template<typename LambdaT>
  7565. explicit ExeName( LambdaT const& lambda ) : ExeName() {
  7566. m_ref = std::make_shared<BoundLambda<LambdaT>>( lambda );
  7567. }
  7568. // The exe name is not parsed out of the normal tokens, but is handled specially
  7569. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  7570. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
  7571. }
  7572. auto name() const -> std::string { return *m_name; }
  7573. auto set( std::string const& newName ) -> ParserResult {
  7574. auto lastSlash = newName.find_last_of( "\\/" );
  7575. auto filename = ( lastSlash == std::string::npos )
  7576. ? newName
  7577. : newName.substr( lastSlash+1 );
  7578. *m_name = filename;
  7579. if( m_ref )
  7580. return m_ref->setValue( filename );
  7581. else
  7582. return ParserResult::ok( ParseResultType::Matched );
  7583. }
  7584. };
  7585. class Arg : public ParserRefImpl<Arg> {
  7586. public:
  7587. using ParserRefImpl::ParserRefImpl;
  7588. auto parse( std::string const &, TokenStream const &tokens ) const -> InternalParseResult override {
  7589. auto validationResult = validate();
  7590. if( !validationResult )
  7591. return InternalParseResult( validationResult );
  7592. auto remainingTokens = tokens;
  7593. auto const &token = *remainingTokens;
  7594. if( token.type != TokenType::Argument )
  7595. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
  7596. assert( !m_ref->isFlag() );
  7597. auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
  7598. auto result = valueRef->setValue( remainingTokens->token );
  7599. if( !result )
  7600. return InternalParseResult( result );
  7601. else
  7602. return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
  7603. }
  7604. };
  7605. inline auto normaliseOpt( std::string const &optName ) -> std::string {
  7606. #ifdef CATCH_PLATFORM_WINDOWS
  7607. if( optName[0] == '/' )
  7608. return "-" + optName.substr( 1 );
  7609. else
  7610. #endif
  7611. return optName;
  7612. }
  7613. class Opt : public ParserRefImpl<Opt> {
  7614. protected:
  7615. std::vector<std::string> m_optNames;
  7616. public:
  7617. template<typename LambdaT>
  7618. explicit Opt( LambdaT const &ref ) : ParserRefImpl( std::make_shared<BoundFlagLambda<LambdaT>>( ref ) ) {}
  7619. explicit Opt( bool &ref ) : ParserRefImpl( std::make_shared<BoundFlagRef>( ref ) ) {}
  7620. template<typename LambdaT>
  7621. Opt( LambdaT const &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  7622. template<typename T>
  7623. Opt( T &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  7624. auto operator[]( std::string const &optName ) -> Opt & {
  7625. m_optNames.push_back( optName );
  7626. return *this;
  7627. }
  7628. auto getHelpColumns() const -> std::vector<HelpColumns> {
  7629. std::ostringstream oss;
  7630. bool first = true;
  7631. for( auto const &opt : m_optNames ) {
  7632. if (first)
  7633. first = false;
  7634. else
  7635. oss << ", ";
  7636. oss << opt;
  7637. }
  7638. if( !m_hint.empty() )
  7639. oss << " <" << m_hint << ">";
  7640. return { { oss.str(), m_description } };
  7641. }
  7642. auto isMatch( std::string const &optToken ) const -> bool {
  7643. auto normalisedToken = normaliseOpt( optToken );
  7644. for( auto const &name : m_optNames ) {
  7645. if( normaliseOpt( name ) == normalisedToken )
  7646. return true;
  7647. }
  7648. return false;
  7649. }
  7650. using ParserBase::parse;
  7651. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  7652. auto validationResult = validate();
  7653. if( !validationResult )
  7654. return InternalParseResult( validationResult );
  7655. auto remainingTokens = tokens;
  7656. if( remainingTokens && remainingTokens->type == TokenType::Option ) {
  7657. auto const &token = *remainingTokens;
  7658. if( isMatch(token.token ) ) {
  7659. if( m_ref->isFlag() ) {
  7660. auto flagRef = static_cast<detail::BoundFlagRefBase*>( m_ref.get() );
  7661. auto result = flagRef->setFlag( true );
  7662. if( !result )
  7663. return InternalParseResult( result );
  7664. if( result.value() == ParseResultType::ShortCircuitAll )
  7665. return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
  7666. } else {
  7667. auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
  7668. ++remainingTokens;
  7669. if( !remainingTokens )
  7670. return InternalParseResult::runtimeError( "Expected argument following " + token.token );
  7671. auto const &argToken = *remainingTokens;
  7672. if( argToken.type != TokenType::Argument )
  7673. return InternalParseResult::runtimeError( "Expected argument following " + token.token );
  7674. auto result = valueRef->setValue( argToken.token );
  7675. if( !result )
  7676. return InternalParseResult( result );
  7677. if( result.value() == ParseResultType::ShortCircuitAll )
  7678. return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
  7679. }
  7680. return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
  7681. }
  7682. }
  7683. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
  7684. }
  7685. auto validate() const -> Result override {
  7686. if( m_optNames.empty() )
  7687. return Result::logicError( "No options supplied to Opt" );
  7688. for( auto const &name : m_optNames ) {
  7689. if( name.empty() )
  7690. return Result::logicError( "Option name cannot be empty" );
  7691. #ifdef CATCH_PLATFORM_WINDOWS
  7692. if( name[0] != '-' && name[0] != '/' )
  7693. return Result::logicError( "Option name must begin with '-' or '/'" );
  7694. #else
  7695. if( name[0] != '-' )
  7696. return Result::logicError( "Option name must begin with '-'" );
  7697. #endif
  7698. }
  7699. return ParserRefImpl::validate();
  7700. }
  7701. };
  7702. struct Help : Opt {
  7703. Help( bool &showHelpFlag )
  7704. : Opt([&]( bool flag ) {
  7705. showHelpFlag = flag;
  7706. return ParserResult::ok( ParseResultType::ShortCircuitAll );
  7707. })
  7708. {
  7709. static_cast<Opt &>( *this )
  7710. ("display usage information")
  7711. ["-?"]["-h"]["--help"]
  7712. .optional();
  7713. }
  7714. };
  7715. struct Parser : ParserBase {
  7716. mutable ExeName m_exeName;
  7717. std::vector<Opt> m_options;
  7718. std::vector<Arg> m_args;
  7719. auto operator|=( ExeName const &exeName ) -> Parser & {
  7720. m_exeName = exeName;
  7721. return *this;
  7722. }
  7723. auto operator|=( Arg const &arg ) -> Parser & {
  7724. m_args.push_back(arg);
  7725. return *this;
  7726. }
  7727. auto operator|=( Opt const &opt ) -> Parser & {
  7728. m_options.push_back(opt);
  7729. return *this;
  7730. }
  7731. auto operator|=( Parser const &other ) -> Parser & {
  7732. m_options.insert(m_options.end(), other.m_options.begin(), other.m_options.end());
  7733. m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end());
  7734. return *this;
  7735. }
  7736. template<typename T>
  7737. auto operator|( T const &other ) const -> Parser {
  7738. return Parser( *this ) |= other;
  7739. }
  7740. // Forward deprecated interface with '+' instead of '|'
  7741. template<typename T>
  7742. auto operator+=( T const &other ) -> Parser & { return operator|=( other ); }
  7743. template<typename T>
  7744. auto operator+( T const &other ) const -> Parser { return operator|( other ); }
  7745. auto getHelpColumns() const -> std::vector<HelpColumns> {
  7746. std::vector<HelpColumns> cols;
  7747. for (auto const &o : m_options) {
  7748. auto childCols = o.getHelpColumns();
  7749. cols.insert( cols.end(), childCols.begin(), childCols.end() );
  7750. }
  7751. return cols;
  7752. }
  7753. void writeToStream( std::ostream &os ) const {
  7754. if (!m_exeName.name().empty()) {
  7755. os << "usage:\n" << " " << m_exeName.name() << " ";
  7756. bool required = true, first = true;
  7757. for( auto const &arg : m_args ) {
  7758. if (first)
  7759. first = false;
  7760. else
  7761. os << " ";
  7762. if( arg.isOptional() && required ) {
  7763. os << "[";
  7764. required = false;
  7765. }
  7766. os << "<" << arg.hint() << ">";
  7767. if( arg.cardinality() == 0 )
  7768. os << " ... ";
  7769. }
  7770. if( !required )
  7771. os << "]";
  7772. if( !m_options.empty() )
  7773. os << " options";
  7774. os << "\n\nwhere options are:" << std::endl;
  7775. }
  7776. auto rows = getHelpColumns();
  7777. size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH;
  7778. size_t optWidth = 0;
  7779. for( auto const &cols : rows )
  7780. optWidth = (std::max)(optWidth, cols.left.size() + 2);
  7781. optWidth = (std::min)(optWidth, consoleWidth/2);
  7782. for( auto const &cols : rows ) {
  7783. auto row =
  7784. TextFlow::Column( cols.left ).width( optWidth ).indent( 2 ) +
  7785. TextFlow::Spacer(4) +
  7786. TextFlow::Column( cols.right ).width( consoleWidth - 7 - optWidth );
  7787. os << row << std::endl;
  7788. }
  7789. }
  7790. friend auto operator<<( std::ostream &os, Parser const &parser ) -> std::ostream& {
  7791. parser.writeToStream( os );
  7792. return os;
  7793. }
  7794. auto validate() const -> Result override {
  7795. for( auto const &opt : m_options ) {
  7796. auto result = opt.validate();
  7797. if( !result )
  7798. return result;
  7799. }
  7800. for( auto const &arg : m_args ) {
  7801. auto result = arg.validate();
  7802. if( !result )
  7803. return result;
  7804. }
  7805. return Result::ok();
  7806. }
  7807. using ParserBase::parse;
  7808. auto parse( std::string const& exeName, TokenStream const &tokens ) const -> InternalParseResult override {
  7809. struct ParserInfo {
  7810. ParserBase const* parser = nullptr;
  7811. size_t count = 0;
  7812. };
  7813. const size_t totalParsers = m_options.size() + m_args.size();
  7814. assert( totalParsers < 512 );
  7815. // ParserInfo parseInfos[totalParsers]; // <-- this is what we really want to do
  7816. ParserInfo parseInfos[512];
  7817. {
  7818. size_t i = 0;
  7819. for (auto const &opt : m_options) parseInfos[i++].parser = &opt;
  7820. for (auto const &arg : m_args) parseInfos[i++].parser = &arg;
  7821. }
  7822. m_exeName.set( exeName );
  7823. auto result = InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
  7824. while( result.value().remainingTokens() ) {
  7825. bool tokenParsed = false;
  7826. for( size_t i = 0; i < totalParsers; ++i ) {
  7827. auto& parseInfo = parseInfos[i];
  7828. if( parseInfo.parser->cardinality() == 0 || parseInfo.count < parseInfo.parser->cardinality() ) {
  7829. result = parseInfo.parser->parse(exeName, result.value().remainingTokens());
  7830. if (!result)
  7831. return result;
  7832. if (result.value().type() != ParseResultType::NoMatch) {
  7833. tokenParsed = true;
  7834. ++parseInfo.count;
  7835. break;
  7836. }
  7837. }
  7838. }
  7839. if( result.value().type() == ParseResultType::ShortCircuitAll )
  7840. return result;
  7841. if( !tokenParsed )
  7842. return InternalParseResult::runtimeError( "Unrecognised token: " + result.value().remainingTokens()->token );
  7843. }
  7844. // !TBD Check missing required options
  7845. return result;
  7846. }
  7847. };
  7848. template<typename DerivedT>
  7849. template<typename T>
  7850. auto ComposableParserImpl<DerivedT>::operator|( T const &other ) const -> Parser {
  7851. return Parser() | static_cast<DerivedT const &>( *this ) | other;
  7852. }
  7853. } // namespace detail
  7854. // A Combined parser
  7855. using detail::Parser;
  7856. // A parser for options
  7857. using detail::Opt;
  7858. // A parser for arguments
  7859. using detail::Arg;
  7860. // Wrapper for argc, argv from main()
  7861. using detail::Args;
  7862. // Specifies the name of the executable
  7863. using detail::ExeName;
  7864. // Convenience wrapper for option parser that specifies the help option
  7865. using detail::Help;
  7866. // enum of result types from a parse
  7867. using detail::ParseResultType;
  7868. // Result type for parser operation
  7869. using detail::ParserResult;
  7870. }} // namespace Catch::clara
  7871. // end clara.hpp
  7872. #ifdef __clang__
  7873. #pragma clang diagnostic pop
  7874. #endif
  7875. // Restore Clara's value for console width, if present
  7876. #ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  7877. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  7878. #undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  7879. #endif
  7880. // end catch_clara.h
  7881. namespace Catch {
  7882. clara::Parser makeCommandLineParser( ConfigData& config );
  7883. } // end namespace Catch
  7884. // end catch_commandline.h
  7885. #include <fstream>
  7886. #include <ctime>
  7887. namespace Catch {
  7888. clara::Parser makeCommandLineParser( ConfigData& config ) {
  7889. using namespace clara;
  7890. auto const setWarning = [&]( std::string const& warning ) {
  7891. auto warningSet = [&]() {
  7892. if( warning == "NoAssertions" )
  7893. return WarnAbout::NoAssertions;
  7894. if ( warning == "NoTests" )
  7895. return WarnAbout::NoTests;
  7896. return WarnAbout::Nothing;
  7897. }();
  7898. if (warningSet == WarnAbout::Nothing)
  7899. return ParserResult::runtimeError( "Unrecognised warning: '" + warning + "'" );
  7900. config.warnings = static_cast<WarnAbout::What>( config.warnings | warningSet );
  7901. return ParserResult::ok( ParseResultType::Matched );
  7902. };
  7903. auto const loadTestNamesFromFile = [&]( std::string const& filename ) {
  7904. std::ifstream f( filename.c_str() );
  7905. if( !f.is_open() )
  7906. return ParserResult::runtimeError( "Unable to load input file: '" + filename + "'" );
  7907. std::string line;
  7908. while( std::getline( f, line ) ) {
  7909. line = trim(line);
  7910. if( !line.empty() && !startsWith( line, '#' ) ) {
  7911. if( !startsWith( line, '"' ) )
  7912. line = '"' + line + '"';
  7913. config.testsOrTags.push_back( line );
  7914. config.testsOrTags.emplace_back( "," );
  7915. }
  7916. }
  7917. //Remove comma in the end
  7918. if(!config.testsOrTags.empty())
  7919. config.testsOrTags.erase( config.testsOrTags.end()-1 );
  7920. return ParserResult::ok( ParseResultType::Matched );
  7921. };
  7922. auto const setTestOrder = [&]( std::string const& order ) {
  7923. if( startsWith( "declared", order ) )
  7924. config.runOrder = RunTests::InDeclarationOrder;
  7925. else if( startsWith( "lexical", order ) )
  7926. config.runOrder = RunTests::InLexicographicalOrder;
  7927. else if( startsWith( "random", order ) )
  7928. config.runOrder = RunTests::InRandomOrder;
  7929. else
  7930. return clara::ParserResult::runtimeError( "Unrecognised ordering: '" + order + "'" );
  7931. return ParserResult::ok( ParseResultType::Matched );
  7932. };
  7933. auto const setRngSeed = [&]( std::string const& seed ) {
  7934. if( seed != "time" )
  7935. return clara::detail::convertInto( seed, config.rngSeed );
  7936. config.rngSeed = static_cast<unsigned int>( std::time(nullptr) );
  7937. return ParserResult::ok( ParseResultType::Matched );
  7938. };
  7939. auto const setColourUsage = [&]( std::string const& useColour ) {
  7940. auto mode = toLower( useColour );
  7941. if( mode == "yes" )
  7942. config.useColour = UseColour::Yes;
  7943. else if( mode == "no" )
  7944. config.useColour = UseColour::No;
  7945. else if( mode == "auto" )
  7946. config.useColour = UseColour::Auto;
  7947. else
  7948. return ParserResult::runtimeError( "colour mode must be one of: auto, yes or no. '" + useColour + "' not recognised" );
  7949. return ParserResult::ok( ParseResultType::Matched );
  7950. };
  7951. auto const setWaitForKeypress = [&]( std::string const& keypress ) {
  7952. auto keypressLc = toLower( keypress );
  7953. if (keypressLc == "never")
  7954. config.waitForKeypress = WaitForKeypress::Never;
  7955. else if( keypressLc == "start" )
  7956. config.waitForKeypress = WaitForKeypress::BeforeStart;
  7957. else if( keypressLc == "exit" )
  7958. config.waitForKeypress = WaitForKeypress::BeforeExit;
  7959. else if( keypressLc == "both" )
  7960. config.waitForKeypress = WaitForKeypress::BeforeStartAndExit;
  7961. else
  7962. return ParserResult::runtimeError( "keypress argument must be one of: never, start, exit or both. '" + keypress + "' not recognised" );
  7963. return ParserResult::ok( ParseResultType::Matched );
  7964. };
  7965. auto const setVerbosity = [&]( std::string const& verbosity ) {
  7966. auto lcVerbosity = toLower( verbosity );
  7967. if( lcVerbosity == "quiet" )
  7968. config.verbosity = Verbosity::Quiet;
  7969. else if( lcVerbosity == "normal" )
  7970. config.verbosity = Verbosity::Normal;
  7971. else if( lcVerbosity == "high" )
  7972. config.verbosity = Verbosity::High;
  7973. else
  7974. return ParserResult::runtimeError( "Unrecognised verbosity, '" + verbosity + "'" );
  7975. return ParserResult::ok( ParseResultType::Matched );
  7976. };
  7977. auto const setReporter = [&]( std::string const& reporter ) {
  7978. IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
  7979. auto lcReporter = toLower( reporter );
  7980. auto result = factories.find( lcReporter );
  7981. if( factories.end() != result )
  7982. config.reporterName = lcReporter;
  7983. else
  7984. return ParserResult::runtimeError( "Unrecognized reporter, '" + reporter + "'. Check available with --list-reporters" );
  7985. return ParserResult::ok( ParseResultType::Matched );
  7986. };
  7987. auto cli
  7988. = ExeName( config.processName )
  7989. | Help( config.showHelp )
  7990. | Opt( config.listTests )
  7991. ["-l"]["--list-tests"]
  7992. ( "list all/matching test cases" )
  7993. | Opt( config.listTags )
  7994. ["-t"]["--list-tags"]
  7995. ( "list all/matching tags" )
  7996. | Opt( config.showSuccessfulTests )
  7997. ["-s"]["--success"]
  7998. ( "include successful tests in output" )
  7999. | Opt( config.shouldDebugBreak )
  8000. ["-b"]["--break"]
  8001. ( "break into debugger on failure" )
  8002. | Opt( config.noThrow )
  8003. ["-e"]["--nothrow"]
  8004. ( "skip exception tests" )
  8005. | Opt( config.showInvisibles )
  8006. ["-i"]["--invisibles"]
  8007. ( "show invisibles (tabs, newlines)" )
  8008. | Opt( config.outputFilename, "filename" )
  8009. ["-o"]["--out"]
  8010. ( "output filename" )
  8011. | Opt( setReporter, "name" )
  8012. ["-r"]["--reporter"]
  8013. ( "reporter to use (defaults to console)" )
  8014. | Opt( config.name, "name" )
  8015. ["-n"]["--name"]
  8016. ( "suite name" )
  8017. | Opt( [&]( bool ){ config.abortAfter = 1; } )
  8018. ["-a"]["--abort"]
  8019. ( "abort at first failure" )
  8020. | Opt( [&]( int x ){ config.abortAfter = x; }, "no. failures" )
  8021. ["-x"]["--abortx"]
  8022. ( "abort after x failures" )
  8023. | Opt( setWarning, "warning name" )
  8024. ["-w"]["--warn"]
  8025. ( "enable warnings" )
  8026. | Opt( [&]( bool flag ) { config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never; }, "yes|no" )
  8027. ["-d"]["--durations"]
  8028. ( "show test durations" )
  8029. | Opt( config.minDuration, "seconds" )
  8030. ["-D"]["--min-duration"]
  8031. ( "show test durations for tests taking at least the given number of seconds" )
  8032. | Opt( loadTestNamesFromFile, "filename" )
  8033. ["-f"]["--input-file"]
  8034. ( "load test names to run from a file" )
  8035. | Opt( config.filenamesAsTags )
  8036. ["-#"]["--filenames-as-tags"]
  8037. ( "adds a tag for the filename" )
  8038. | Opt( config.sectionsToRun, "section name" )
  8039. ["-c"]["--section"]
  8040. ( "specify section to run" )
  8041. | Opt( setVerbosity, "quiet|normal|high" )
  8042. ["-v"]["--verbosity"]
  8043. ( "set output verbosity" )
  8044. | Opt( config.listTestNamesOnly )
  8045. ["--list-test-names-only"]
  8046. ( "list all/matching test cases names only" )
  8047. | Opt( config.listReporters )
  8048. ["--list-reporters"]
  8049. ( "list all reporters" )
  8050. | Opt( setTestOrder, "decl|lex|rand" )
  8051. ["--order"]
  8052. ( "test case order (defaults to decl)" )
  8053. | Opt( setRngSeed, "'time'|number" )
  8054. ["--rng-seed"]
  8055. ( "set a specific seed for random numbers" )
  8056. | Opt( setColourUsage, "yes|no" )
  8057. ["--use-colour"]
  8058. ( "should output be colourised" )
  8059. | Opt( config.libIdentify )
  8060. ["--libidentify"]
  8061. ( "report name and version according to libidentify standard" )
  8062. | Opt( setWaitForKeypress, "never|start|exit|both" )
  8063. ["--wait-for-keypress"]
  8064. ( "waits for a keypress before exiting" )
  8065. | Opt( config.benchmarkSamples, "samples" )
  8066. ["--benchmark-samples"]
  8067. ( "number of samples to collect (default: 100)" )
  8068. | Opt( config.benchmarkResamples, "resamples" )
  8069. ["--benchmark-resamples"]
  8070. ( "number of resamples for the bootstrap (default: 100000)" )
  8071. | Opt( config.benchmarkConfidenceInterval, "confidence interval" )
  8072. ["--benchmark-confidence-interval"]
  8073. ( "confidence interval for the bootstrap (between 0 and 1, default: 0.95)" )
  8074. | Opt( config.benchmarkNoAnalysis )
  8075. ["--benchmark-no-analysis"]
  8076. ( "perform only measurements; do not perform any analysis" )
  8077. | Opt( config.benchmarkWarmupTime, "benchmarkWarmupTime" )
  8078. ["--benchmark-warmup-time"]
  8079. ( "amount of time in milliseconds spent on warming up each test (default: 100)" )
  8080. | Arg( config.testsOrTags, "test name|pattern|tags" )
  8081. ( "which test or tests to use" );
  8082. return cli;
  8083. }
  8084. } // end namespace Catch
  8085. // end catch_commandline.cpp
  8086. // start catch_common.cpp
  8087. #include <cstring>
  8088. #include <ostream>
  8089. namespace Catch {
  8090. bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const noexcept {
  8091. return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0);
  8092. }
  8093. bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const noexcept {
  8094. // We can assume that the same file will usually have the same pointer.
  8095. // Thus, if the pointers are the same, there is no point in calling the strcmp
  8096. return line < other.line || ( line == other.line && file != other.file && (std::strcmp(file, other.file) < 0));
  8097. }
  8098. std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) {
  8099. #ifndef __GNUG__
  8100. os << info.file << '(' << info.line << ')';
  8101. #else
  8102. os << info.file << ':' << info.line;
  8103. #endif
  8104. return os;
  8105. }
  8106. std::string StreamEndStop::operator+() const {
  8107. return std::string();
  8108. }
  8109. NonCopyable::NonCopyable() = default;
  8110. NonCopyable::~NonCopyable() = default;
  8111. }
  8112. // end catch_common.cpp
  8113. // start catch_config.cpp
  8114. namespace Catch {
  8115. Config::Config( ConfigData const& data )
  8116. : m_data( data ),
  8117. m_stream( openStream() )
  8118. {
  8119. // We need to trim filter specs to avoid trouble with superfluous
  8120. // whitespace (esp. important for bdd macros, as those are manually
  8121. // aligned with whitespace).
  8122. for (auto& elem : m_data.testsOrTags) {
  8123. elem = trim(elem);
  8124. }
  8125. for (auto& elem : m_data.sectionsToRun) {
  8126. elem = trim(elem);
  8127. }
  8128. TestSpecParser parser(ITagAliasRegistry::get());
  8129. if (!m_data.testsOrTags.empty()) {
  8130. m_hasTestFilters = true;
  8131. for (auto const& testOrTags : m_data.testsOrTags) {
  8132. parser.parse(testOrTags);
  8133. }
  8134. }
  8135. m_testSpec = parser.testSpec();
  8136. }
  8137. std::string const& Config::getFilename() const {
  8138. return m_data.outputFilename ;
  8139. }
  8140. bool Config::listTests() const { return m_data.listTests; }
  8141. bool Config::listTestNamesOnly() const { return m_data.listTestNamesOnly; }
  8142. bool Config::listTags() const { return m_data.listTags; }
  8143. bool Config::listReporters() const { return m_data.listReporters; }
  8144. std::string Config::getProcessName() const { return m_data.processName; }
  8145. std::string const& Config::getReporterName() const { return m_data.reporterName; }
  8146. std::vector<std::string> const& Config::getTestsOrTags() const { return m_data.testsOrTags; }
  8147. std::vector<std::string> const& Config::getSectionsToRun() const { return m_data.sectionsToRun; }
  8148. TestSpec const& Config::testSpec() const { return m_testSpec; }
  8149. bool Config::hasTestFilters() const { return m_hasTestFilters; }
  8150. bool Config::showHelp() const { return m_data.showHelp; }
  8151. // IConfig interface
  8152. bool Config::allowThrows() const { return !m_data.noThrow; }
  8153. std::ostream& Config::stream() const { return m_stream->stream(); }
  8154. std::string Config::name() const { return m_data.name.empty() ? m_data.processName : m_data.name; }
  8155. bool Config::includeSuccessfulResults() const { return m_data.showSuccessfulTests; }
  8156. bool Config::warnAboutMissingAssertions() const { return !!(m_data.warnings & WarnAbout::NoAssertions); }
  8157. bool Config::warnAboutNoTests() const { return !!(m_data.warnings & WarnAbout::NoTests); }
  8158. ShowDurations::OrNot Config::showDurations() const { return m_data.showDurations; }
  8159. double Config::minDuration() const { return m_data.minDuration; }
  8160. RunTests::InWhatOrder Config::runOrder() const { return m_data.runOrder; }
  8161. unsigned int Config::rngSeed() const { return m_data.rngSeed; }
  8162. UseColour::YesOrNo Config::useColour() const { return m_data.useColour; }
  8163. bool Config::shouldDebugBreak() const { return m_data.shouldDebugBreak; }
  8164. int Config::abortAfter() const { return m_data.abortAfter; }
  8165. bool Config::showInvisibles() const { return m_data.showInvisibles; }
  8166. Verbosity Config::verbosity() const { return m_data.verbosity; }
  8167. bool Config::benchmarkNoAnalysis() const { return m_data.benchmarkNoAnalysis; }
  8168. int Config::benchmarkSamples() const { return m_data.benchmarkSamples; }
  8169. double Config::benchmarkConfidenceInterval() const { return m_data.benchmarkConfidenceInterval; }
  8170. unsigned int Config::benchmarkResamples() const { return m_data.benchmarkResamples; }
  8171. std::chrono::milliseconds Config::benchmarkWarmupTime() const { return std::chrono::milliseconds(m_data.benchmarkWarmupTime); }
  8172. IStream const* Config::openStream() {
  8173. return Catch::makeStream(m_data.outputFilename);
  8174. }
  8175. } // end namespace Catch
  8176. // end catch_config.cpp
  8177. // start catch_console_colour.cpp
  8178. #if defined(__clang__)
  8179. # pragma clang diagnostic push
  8180. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  8181. #endif
  8182. // start catch_errno_guard.h
  8183. namespace Catch {
  8184. class ErrnoGuard {
  8185. public:
  8186. ErrnoGuard();
  8187. ~ErrnoGuard();
  8188. private:
  8189. int m_oldErrno;
  8190. };
  8191. }
  8192. // end catch_errno_guard.h
  8193. // start catch_windows_h_proxy.h
  8194. #if defined(CATCH_PLATFORM_WINDOWS)
  8195. #if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX)
  8196. # define CATCH_DEFINED_NOMINMAX
  8197. # define NOMINMAX
  8198. #endif
  8199. #if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN)
  8200. # define CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  8201. # define WIN32_LEAN_AND_MEAN
  8202. #endif
  8203. #ifdef __AFXDLL
  8204. #include <AfxWin.h>
  8205. #else
  8206. #include <windows.h>
  8207. #endif
  8208. #ifdef CATCH_DEFINED_NOMINMAX
  8209. # undef NOMINMAX
  8210. #endif
  8211. #ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  8212. # undef WIN32_LEAN_AND_MEAN
  8213. #endif
  8214. #endif // defined(CATCH_PLATFORM_WINDOWS)
  8215. // end catch_windows_h_proxy.h
  8216. #include <sstream>
  8217. namespace Catch {
  8218. namespace {
  8219. struct IColourImpl {
  8220. virtual ~IColourImpl() = default;
  8221. virtual void use( Colour::Code _colourCode ) = 0;
  8222. };
  8223. struct NoColourImpl : IColourImpl {
  8224. void use( Colour::Code ) override {}
  8225. static IColourImpl* instance() {
  8226. static NoColourImpl s_instance;
  8227. return &s_instance;
  8228. }
  8229. };
  8230. } // anon namespace
  8231. } // namespace Catch
  8232. #if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI )
  8233. # ifdef CATCH_PLATFORM_WINDOWS
  8234. # define CATCH_CONFIG_COLOUR_WINDOWS
  8235. # else
  8236. # define CATCH_CONFIG_COLOUR_ANSI
  8237. # endif
  8238. #endif
  8239. #if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) /////////////////////////////////////////
  8240. namespace Catch {
  8241. namespace {
  8242. class Win32ColourImpl : public IColourImpl {
  8243. public:
  8244. Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) )
  8245. {
  8246. CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
  8247. GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo );
  8248. originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY );
  8249. originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY );
  8250. }
  8251. void use( Colour::Code _colourCode ) override {
  8252. switch( _colourCode ) {
  8253. case Colour::None: return setTextAttribute( originalForegroundAttributes );
  8254. case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  8255. case Colour::Red: return setTextAttribute( FOREGROUND_RED );
  8256. case Colour::Green: return setTextAttribute( FOREGROUND_GREEN );
  8257. case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE );
  8258. case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN );
  8259. case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN );
  8260. case Colour::Grey: return setTextAttribute( 0 );
  8261. case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY );
  8262. case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED );
  8263. case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN );
  8264. case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  8265. case Colour::BrightYellow: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN );
  8266. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  8267. default:
  8268. CATCH_ERROR( "Unknown colour requested" );
  8269. }
  8270. }
  8271. private:
  8272. void setTextAttribute( WORD _textAttribute ) {
  8273. SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes );
  8274. }
  8275. HANDLE stdoutHandle;
  8276. WORD originalForegroundAttributes;
  8277. WORD originalBackgroundAttributes;
  8278. };
  8279. IColourImpl* platformColourInstance() {
  8280. static Win32ColourImpl s_instance;
  8281. IConfigPtr config = getCurrentContext().getConfig();
  8282. UseColour::YesOrNo colourMode = config
  8283. ? config->useColour()
  8284. : UseColour::Auto;
  8285. if( colourMode == UseColour::Auto )
  8286. colourMode = UseColour::Yes;
  8287. return colourMode == UseColour::Yes
  8288. ? &s_instance
  8289. : NoColourImpl::instance();
  8290. }
  8291. } // end anon namespace
  8292. } // end namespace Catch
  8293. #elif defined( CATCH_CONFIG_COLOUR_ANSI ) //////////////////////////////////////
  8294. #include <unistd.h>
  8295. namespace Catch {
  8296. namespace {
  8297. // use POSIX/ ANSI console terminal codes
  8298. // Thanks to Adam Strzelecki for original contribution
  8299. // (http://github.com/nanoant)
  8300. // https://github.com/philsquared/Catch/pull/131
  8301. class PosixColourImpl : public IColourImpl {
  8302. public:
  8303. void use( Colour::Code _colourCode ) override {
  8304. switch( _colourCode ) {
  8305. case Colour::None:
  8306. case Colour::White: return setColour( "[0m" );
  8307. case Colour::Red: return setColour( "[0;31m" );
  8308. case Colour::Green: return setColour( "[0;32m" );
  8309. case Colour::Blue: return setColour( "[0;34m" );
  8310. case Colour::Cyan: return setColour( "[0;36m" );
  8311. case Colour::Yellow: return setColour( "[0;33m" );
  8312. case Colour::Grey: return setColour( "[1;30m" );
  8313. case Colour::LightGrey: return setColour( "[0;37m" );
  8314. case Colour::BrightRed: return setColour( "[1;31m" );
  8315. case Colour::BrightGreen: return setColour( "[1;32m" );
  8316. case Colour::BrightWhite: return setColour( "[1;37m" );
  8317. case Colour::BrightYellow: return setColour( "[1;33m" );
  8318. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  8319. default: CATCH_INTERNAL_ERROR( "Unknown colour requested" );
  8320. }
  8321. }
  8322. static IColourImpl* instance() {
  8323. static PosixColourImpl s_instance;
  8324. return &s_instance;
  8325. }
  8326. private:
  8327. void setColour( const char* _escapeCode ) {
  8328. getCurrentContext().getConfig()->stream()
  8329. << '\033' << _escapeCode;
  8330. }
  8331. };
  8332. bool useColourOnPlatform() {
  8333. return
  8334. #if defined(CATCH_PLATFORM_MAC) || defined(CATCH_PLATFORM_IPHONE)
  8335. !isDebuggerActive() &&
  8336. #endif
  8337. #if !(defined(__DJGPP__) && defined(__STRICT_ANSI__))
  8338. isatty(STDOUT_FILENO)
  8339. #else
  8340. false
  8341. #endif
  8342. ;
  8343. }
  8344. IColourImpl* platformColourInstance() {
  8345. ErrnoGuard guard;
  8346. IConfigPtr config = getCurrentContext().getConfig();
  8347. UseColour::YesOrNo colourMode = config
  8348. ? config->useColour()
  8349. : UseColour::Auto;
  8350. if( colourMode == UseColour::Auto )
  8351. colourMode = useColourOnPlatform()
  8352. ? UseColour::Yes
  8353. : UseColour::No;
  8354. return colourMode == UseColour::Yes
  8355. ? PosixColourImpl::instance()
  8356. : NoColourImpl::instance();
  8357. }
  8358. } // end anon namespace
  8359. } // end namespace Catch
  8360. #else // not Windows or ANSI ///////////////////////////////////////////////
  8361. namespace Catch {
  8362. static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); }
  8363. } // end namespace Catch
  8364. #endif // Windows/ ANSI/ None
  8365. namespace Catch {
  8366. Colour::Colour( Code _colourCode ) { use( _colourCode ); }
  8367. Colour::Colour( Colour&& other ) noexcept {
  8368. m_moved = other.m_moved;
  8369. other.m_moved = true;
  8370. }
  8371. Colour& Colour::operator=( Colour&& other ) noexcept {
  8372. m_moved = other.m_moved;
  8373. other.m_moved = true;
  8374. return *this;
  8375. }
  8376. Colour::~Colour(){ if( !m_moved ) use( None ); }
  8377. void Colour::use( Code _colourCode ) {
  8378. static IColourImpl* impl = platformColourInstance();
  8379. // Strictly speaking, this cannot possibly happen.
  8380. // However, under some conditions it does happen (see #1626),
  8381. // and this change is small enough that we can let practicality
  8382. // triumph over purity in this case.
  8383. if (impl != nullptr) {
  8384. impl->use( _colourCode );
  8385. }
  8386. }
  8387. std::ostream& operator << ( std::ostream& os, Colour const& ) {
  8388. return os;
  8389. }
  8390. } // end namespace Catch
  8391. #if defined(__clang__)
  8392. # pragma clang diagnostic pop
  8393. #endif
  8394. // end catch_console_colour.cpp
  8395. // start catch_context.cpp
  8396. namespace Catch {
  8397. class Context : public IMutableContext, NonCopyable {
  8398. public: // IContext
  8399. IResultCapture* getResultCapture() override {
  8400. return m_resultCapture;
  8401. }
  8402. IRunner* getRunner() override {
  8403. return m_runner;
  8404. }
  8405. IConfigPtr const& getConfig() const override {
  8406. return m_config;
  8407. }
  8408. ~Context() override;
  8409. public: // IMutableContext
  8410. void setResultCapture( IResultCapture* resultCapture ) override {
  8411. m_resultCapture = resultCapture;
  8412. }
  8413. void setRunner( IRunner* runner ) override {
  8414. m_runner = runner;
  8415. }
  8416. void setConfig( IConfigPtr const& config ) override {
  8417. m_config = config;
  8418. }
  8419. friend IMutableContext& getCurrentMutableContext();
  8420. private:
  8421. IConfigPtr m_config;
  8422. IRunner* m_runner = nullptr;
  8423. IResultCapture* m_resultCapture = nullptr;
  8424. };
  8425. IMutableContext *IMutableContext::currentContext = nullptr;
  8426. void IMutableContext::createContext()
  8427. {
  8428. currentContext = new Context();
  8429. }
  8430. void cleanUpContext() {
  8431. delete IMutableContext::currentContext;
  8432. IMutableContext::currentContext = nullptr;
  8433. }
  8434. IContext::~IContext() = default;
  8435. IMutableContext::~IMutableContext() = default;
  8436. Context::~Context() = default;
  8437. SimplePcg32& rng() {
  8438. static SimplePcg32 s_rng;
  8439. return s_rng;
  8440. }
  8441. }
  8442. // end catch_context.cpp
  8443. // start catch_debug_console.cpp
  8444. // start catch_debug_console.h
  8445. #include <string>
  8446. namespace Catch {
  8447. void writeToDebugConsole( std::string const& text );
  8448. }
  8449. // end catch_debug_console.h
  8450. #if defined(CATCH_CONFIG_ANDROID_LOGWRITE)
  8451. #include <android/log.h>
  8452. namespace Catch {
  8453. void writeToDebugConsole( std::string const& text ) {
  8454. __android_log_write( ANDROID_LOG_DEBUG, "Catch", text.c_str() );
  8455. }
  8456. }
  8457. #elif defined(CATCH_PLATFORM_WINDOWS)
  8458. namespace Catch {
  8459. void writeToDebugConsole( std::string const& text ) {
  8460. ::OutputDebugStringA( text.c_str() );
  8461. }
  8462. }
  8463. #else
  8464. namespace Catch {
  8465. void writeToDebugConsole( std::string const& text ) {
  8466. // !TBD: Need a version for Mac/ XCode and other IDEs
  8467. Catch::cout() << text;
  8468. }
  8469. }
  8470. #endif // Platform
  8471. // end catch_debug_console.cpp
  8472. // start catch_debugger.cpp
  8473. #if defined(CATCH_PLATFORM_MAC) || defined(CATCH_PLATFORM_IPHONE)
  8474. # include <cassert>
  8475. # include <sys/types.h>
  8476. # include <unistd.h>
  8477. # include <cstddef>
  8478. # include <ostream>
  8479. #ifdef __apple_build_version__
  8480. // These headers will only compile with AppleClang (XCode)
  8481. // For other compilers (Clang, GCC, ... ) we need to exclude them
  8482. # include <sys/sysctl.h>
  8483. #endif
  8484. namespace Catch {
  8485. #ifdef __apple_build_version__
  8486. // The following function is taken directly from the following technical note:
  8487. // https://developer.apple.com/library/archive/qa/qa1361/_index.html
  8488. // Returns true if the current process is being debugged (either
  8489. // running under the debugger or has a debugger attached post facto).
  8490. bool isDebuggerActive(){
  8491. int mib[4];
  8492. struct kinfo_proc info;
  8493. std::size_t size;
  8494. // Initialize the flags so that, if sysctl fails for some bizarre
  8495. // reason, we get a predictable result.
  8496. info.kp_proc.p_flag = 0;
  8497. // Initialize mib, which tells sysctl the info we want, in this case
  8498. // we're looking for information about a specific process ID.
  8499. mib[0] = CTL_KERN;
  8500. mib[1] = KERN_PROC;
  8501. mib[2] = KERN_PROC_PID;
  8502. mib[3] = getpid();
  8503. // Call sysctl.
  8504. size = sizeof(info);
  8505. if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0) != 0 ) {
  8506. Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl;
  8507. return false;
  8508. }
  8509. // We're being debugged if the P_TRACED flag is set.
  8510. return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
  8511. }
  8512. #else
  8513. bool isDebuggerActive() {
  8514. // We need to find another way to determine this for non-appleclang compilers on macOS
  8515. return false;
  8516. }
  8517. #endif
  8518. } // namespace Catch
  8519. #elif defined(CATCH_PLATFORM_LINUX)
  8520. #include <fstream>
  8521. #include <string>
  8522. namespace Catch{
  8523. // The standard POSIX way of detecting a debugger is to attempt to
  8524. // ptrace() the process, but this needs to be done from a child and not
  8525. // this process itself to still allow attaching to this process later
  8526. // if wanted, so is rather heavy. Under Linux we have the PID of the
  8527. // "debugger" (which doesn't need to be gdb, of course, it could also
  8528. // be strace, for example) in /proc/$PID/status, so just get it from
  8529. // there instead.
  8530. bool isDebuggerActive(){
  8531. // Libstdc++ has a bug, where std::ifstream sets errno to 0
  8532. // This way our users can properly assert over errno values
  8533. ErrnoGuard guard;
  8534. std::ifstream in("/proc/self/status");
  8535. for( std::string line; std::getline(in, line); ) {
  8536. static const int PREFIX_LEN = 11;
  8537. if( line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0 ) {
  8538. // We're traced if the PID is not 0 and no other PID starts
  8539. // with 0 digit, so it's enough to check for just a single
  8540. // character.
  8541. return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0';
  8542. }
  8543. }
  8544. return false;
  8545. }
  8546. } // namespace Catch
  8547. #elif defined(_MSC_VER)
  8548. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  8549. namespace Catch {
  8550. bool isDebuggerActive() {
  8551. return IsDebuggerPresent() != 0;
  8552. }
  8553. }
  8554. #elif defined(__MINGW32__)
  8555. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  8556. namespace Catch {
  8557. bool isDebuggerActive() {
  8558. return IsDebuggerPresent() != 0;
  8559. }
  8560. }
  8561. #else
  8562. namespace Catch {
  8563. bool isDebuggerActive() { return false; }
  8564. }
  8565. #endif // Platform
  8566. // end catch_debugger.cpp
  8567. // start catch_decomposer.cpp
  8568. namespace Catch {
  8569. ITransientExpression::~ITransientExpression() = default;
  8570. void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs ) {
  8571. if( lhs.size() + rhs.size() < 40 &&
  8572. lhs.find('\n') == std::string::npos &&
  8573. rhs.find('\n') == std::string::npos )
  8574. os << lhs << " " << op << " " << rhs;
  8575. else
  8576. os << lhs << "\n" << op << "\n" << rhs;
  8577. }
  8578. }
  8579. // end catch_decomposer.cpp
  8580. // start catch_enforce.cpp
  8581. #include <stdexcept>
  8582. namespace Catch {
  8583. #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS_CUSTOM_HANDLER)
  8584. [[noreturn]]
  8585. void throw_exception(std::exception const& e) {
  8586. Catch::cerr() << "Catch will terminate because it needed to throw an exception.\n"
  8587. << "The message was: " << e.what() << '\n';
  8588. std::terminate();
  8589. }
  8590. #endif
  8591. [[noreturn]]
  8592. void throw_logic_error(std::string const& msg) {
  8593. throw_exception(std::logic_error(msg));
  8594. }
  8595. [[noreturn]]
  8596. void throw_domain_error(std::string const& msg) {
  8597. throw_exception(std::domain_error(msg));
  8598. }
  8599. [[noreturn]]
  8600. void throw_runtime_error(std::string const& msg) {
  8601. throw_exception(std::runtime_error(msg));
  8602. }
  8603. } // namespace Catch;
  8604. // end catch_enforce.cpp
  8605. // start catch_enum_values_registry.cpp
  8606. // start catch_enum_values_registry.h
  8607. #include <vector>
  8608. #include <memory>
  8609. namespace Catch {
  8610. namespace Detail {
  8611. std::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int> const& values );
  8612. class EnumValuesRegistry : public IMutableEnumValuesRegistry {
  8613. std::vector<std::unique_ptr<EnumInfo>> m_enumInfos;
  8614. EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::vector<int> const& values) override;
  8615. };
  8616. std::vector<StringRef> parseEnums( StringRef enums );
  8617. } // Detail
  8618. } // Catch
  8619. // end catch_enum_values_registry.h
  8620. #include <map>
  8621. #include <cassert>
  8622. namespace Catch {
  8623. IMutableEnumValuesRegistry::~IMutableEnumValuesRegistry() {}
  8624. namespace Detail {
  8625. namespace {
  8626. // Extracts the actual name part of an enum instance
  8627. // In other words, it returns the Blue part of Bikeshed::Colour::Blue
  8628. StringRef extractInstanceName(StringRef enumInstance) {
  8629. // Find last occurrence of ":"
  8630. size_t name_start = enumInstance.size();
  8631. while (name_start > 0 && enumInstance[name_start - 1] != ':') {
  8632. --name_start;
  8633. }
  8634. return enumInstance.substr(name_start, enumInstance.size() - name_start);
  8635. }
  8636. }
  8637. std::vector<StringRef> parseEnums( StringRef enums ) {
  8638. auto enumValues = splitStringRef( enums, ',' );
  8639. std::vector<StringRef> parsed;
  8640. parsed.reserve( enumValues.size() );
  8641. for( auto const& enumValue : enumValues ) {
  8642. parsed.push_back(trim(extractInstanceName(enumValue)));
  8643. }
  8644. return parsed;
  8645. }
  8646. EnumInfo::~EnumInfo() {}
  8647. StringRef EnumInfo::lookup( int value ) const {
  8648. for( auto const& valueToName : m_values ) {
  8649. if( valueToName.first == value )
  8650. return valueToName.second;
  8651. }
  8652. return "{** unexpected enum value **}"_sr;
  8653. }
  8654. std::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ) {
  8655. std::unique_ptr<EnumInfo> enumInfo( new EnumInfo );
  8656. enumInfo->m_name = enumName;
  8657. enumInfo->m_values.reserve( values.size() );
  8658. const auto valueNames = Catch::Detail::parseEnums( allValueNames );
  8659. assert( valueNames.size() == values.size() );
  8660. std::size_t i = 0;
  8661. for( auto value : values )
  8662. enumInfo->m_values.emplace_back(value, valueNames[i++]);
  8663. return enumInfo;
  8664. }
  8665. EnumInfo const& EnumValuesRegistry::registerEnum( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ) {
  8666. m_enumInfos.push_back(makeEnumInfo(enumName, allValueNames, values));
  8667. return *m_enumInfos.back();
  8668. }
  8669. } // Detail
  8670. } // Catch
  8671. // end catch_enum_values_registry.cpp
  8672. // start catch_errno_guard.cpp
  8673. #include <cerrno>
  8674. namespace Catch {
  8675. ErrnoGuard::ErrnoGuard():m_oldErrno(errno){}
  8676. ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; }
  8677. }
  8678. // end catch_errno_guard.cpp
  8679. // start catch_exception_translator_registry.cpp
  8680. // start catch_exception_translator_registry.h
  8681. #include <vector>
  8682. #include <string>
  8683. #include <memory>
  8684. namespace Catch {
  8685. class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry {
  8686. public:
  8687. ~ExceptionTranslatorRegistry();
  8688. virtual void registerTranslator( const IExceptionTranslator* translator );
  8689. std::string translateActiveException() const override;
  8690. std::string tryTranslators() const;
  8691. private:
  8692. std::vector<std::unique_ptr<IExceptionTranslator const>> m_translators;
  8693. };
  8694. }
  8695. // end catch_exception_translator_registry.h
  8696. #ifdef __OBJC__
  8697. #import "Foundation/Foundation.h"
  8698. #endif
  8699. namespace Catch {
  8700. ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {
  8701. }
  8702. void ExceptionTranslatorRegistry::registerTranslator( const IExceptionTranslator* translator ) {
  8703. m_translators.push_back( std::unique_ptr<const IExceptionTranslator>( translator ) );
  8704. }
  8705. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  8706. std::string ExceptionTranslatorRegistry::translateActiveException() const {
  8707. try {
  8708. #ifdef __OBJC__
  8709. // In Objective-C try objective-c exceptions first
  8710. @try {
  8711. return tryTranslators();
  8712. }
  8713. @catch (NSException *exception) {
  8714. return Catch::Detail::stringify( [exception description] );
  8715. }
  8716. #else
  8717. // Compiling a mixed mode project with MSVC means that CLR
  8718. // exceptions will be caught in (...) as well. However, these
  8719. // do not fill-in std::current_exception and thus lead to crash
  8720. // when attempting rethrow.
  8721. // /EHa switch also causes structured exceptions to be caught
  8722. // here, but they fill-in current_exception properly, so
  8723. // at worst the output should be a little weird, instead of
  8724. // causing a crash.
  8725. if (std::current_exception() == nullptr) {
  8726. return "Non C++ exception. Possibly a CLR exception.";
  8727. }
  8728. return tryTranslators();
  8729. #endif
  8730. }
  8731. catch( TestFailureException& ) {
  8732. std::rethrow_exception(std::current_exception());
  8733. }
  8734. catch( std::exception& ex ) {
  8735. return ex.what();
  8736. }
  8737. catch( std::string& msg ) {
  8738. return msg;
  8739. }
  8740. catch( const char* msg ) {
  8741. return msg;
  8742. }
  8743. catch(...) {
  8744. return "Unknown exception";
  8745. }
  8746. }
  8747. std::string ExceptionTranslatorRegistry::tryTranslators() const {
  8748. if (m_translators.empty()) {
  8749. std::rethrow_exception(std::current_exception());
  8750. } else {
  8751. return m_translators[0]->translate(m_translators.begin() + 1, m_translators.end());
  8752. }
  8753. }
  8754. #else // ^^ Exceptions are enabled // Exceptions are disabled vv
  8755. std::string ExceptionTranslatorRegistry::translateActiveException() const {
  8756. CATCH_INTERNAL_ERROR("Attempted to translate active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
  8757. }
  8758. std::string ExceptionTranslatorRegistry::tryTranslators() const {
  8759. CATCH_INTERNAL_ERROR("Attempted to use exception translators under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
  8760. }
  8761. #endif
  8762. }
  8763. // end catch_exception_translator_registry.cpp
  8764. // start catch_fatal_condition.cpp
  8765. #include <algorithm>
  8766. #if !defined( CATCH_CONFIG_WINDOWS_SEH ) && !defined( CATCH_CONFIG_POSIX_SIGNALS )
  8767. namespace Catch {
  8768. // If neither SEH nor signal handling is required, the handler impls
  8769. // do not have to do anything, and can be empty.
  8770. void FatalConditionHandler::engage_platform() {}
  8771. void FatalConditionHandler::disengage_platform() {}
  8772. FatalConditionHandler::FatalConditionHandler() = default;
  8773. FatalConditionHandler::~FatalConditionHandler() = default;
  8774. } // end namespace Catch
  8775. #endif // !CATCH_CONFIG_WINDOWS_SEH && !CATCH_CONFIG_POSIX_SIGNALS
  8776. #if defined( CATCH_CONFIG_WINDOWS_SEH ) && defined( CATCH_CONFIG_POSIX_SIGNALS )
  8777. #error "Inconsistent configuration: Windows' SEH handling and POSIX signals cannot be enabled at the same time"
  8778. #endif // CATCH_CONFIG_WINDOWS_SEH && CATCH_CONFIG_POSIX_SIGNALS
  8779. #if defined( CATCH_CONFIG_WINDOWS_SEH ) || defined( CATCH_CONFIG_POSIX_SIGNALS )
  8780. namespace {
  8781. //! Signals fatal error message to the run context
  8782. void reportFatal( char const * const message ) {
  8783. Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition( message );
  8784. }
  8785. //! Minimal size Catch2 needs for its own fatal error handling.
  8786. //! Picked anecdotally, so it might not be sufficient on all
  8787. //! platforms, and for all configurations.
  8788. constexpr std::size_t minStackSizeForErrors = 32 * 1024;
  8789. } // end unnamed namespace
  8790. #endif // CATCH_CONFIG_WINDOWS_SEH || CATCH_CONFIG_POSIX_SIGNALS
  8791. #if defined( CATCH_CONFIG_WINDOWS_SEH )
  8792. namespace Catch {
  8793. struct SignalDefs { DWORD id; const char* name; };
  8794. // There is no 1-1 mapping between signals and windows exceptions.
  8795. // Windows can easily distinguish between SO and SigSegV,
  8796. // but SigInt, SigTerm, etc are handled differently.
  8797. static SignalDefs signalDefs[] = {
  8798. { static_cast<DWORD>(EXCEPTION_ILLEGAL_INSTRUCTION), "SIGILL - Illegal instruction signal" },
  8799. { static_cast<DWORD>(EXCEPTION_STACK_OVERFLOW), "SIGSEGV - Stack overflow" },
  8800. { static_cast<DWORD>(EXCEPTION_ACCESS_VIOLATION), "SIGSEGV - Segmentation violation signal" },
  8801. { static_cast<DWORD>(EXCEPTION_INT_DIVIDE_BY_ZERO), "Divide by zero error" },
  8802. };
  8803. static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {
  8804. for (auto const& def : signalDefs) {
  8805. if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) {
  8806. reportFatal(def.name);
  8807. }
  8808. }
  8809. // If its not an exception we care about, pass it along.
  8810. // This stops us from eating debugger breaks etc.
  8811. return EXCEPTION_CONTINUE_SEARCH;
  8812. }
  8813. // Since we do not support multiple instantiations, we put these
  8814. // into global variables and rely on cleaning them up in outlined
  8815. // constructors/destructors
  8816. static PVOID exceptionHandlerHandle = nullptr;
  8817. // For MSVC, we reserve part of the stack memory for handling
  8818. // memory overflow structured exception.
  8819. FatalConditionHandler::FatalConditionHandler() {
  8820. ULONG guaranteeSize = static_cast<ULONG>(minStackSizeForErrors);
  8821. if (!SetThreadStackGuarantee(&guaranteeSize)) {
  8822. // We do not want to fully error out, because needing
  8823. // the stack reserve should be rare enough anyway.
  8824. Catch::cerr()
  8825. << "Failed to reserve piece of stack."
  8826. << " Stack overflows will not be reported successfully.";
  8827. }
  8828. }
  8829. // We do not attempt to unset the stack guarantee, because
  8830. // Windows does not support lowering the stack size guarantee.
  8831. FatalConditionHandler::~FatalConditionHandler() = default;
  8832. void FatalConditionHandler::engage_platform() {
  8833. // Register as first handler in current chain
  8834. exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);
  8835. if (!exceptionHandlerHandle) {
  8836. CATCH_RUNTIME_ERROR("Could not register vectored exception handler");
  8837. }
  8838. }
  8839. void FatalConditionHandler::disengage_platform() {
  8840. if (!RemoveVectoredExceptionHandler(exceptionHandlerHandle)) {
  8841. CATCH_RUNTIME_ERROR("Could not unregister vectored exception handler");
  8842. }
  8843. exceptionHandlerHandle = nullptr;
  8844. }
  8845. } // end namespace Catch
  8846. #endif // CATCH_CONFIG_WINDOWS_SEH
  8847. #if defined( CATCH_CONFIG_POSIX_SIGNALS )
  8848. #include <signal.h>
  8849. namespace Catch {
  8850. struct SignalDefs {
  8851. int id;
  8852. const char* name;
  8853. };
  8854. static SignalDefs signalDefs[] = {
  8855. { SIGINT, "SIGINT - Terminal interrupt signal" },
  8856. { SIGILL, "SIGILL - Illegal instruction signal" },
  8857. { SIGFPE, "SIGFPE - Floating point error signal" },
  8858. { SIGSEGV, "SIGSEGV - Segmentation violation signal" },
  8859. { SIGTERM, "SIGTERM - Termination request signal" },
  8860. { SIGABRT, "SIGABRT - Abort (abnormal termination) signal" }
  8861. };
  8862. // Older GCCs trigger -Wmissing-field-initializers for T foo = {}
  8863. // which is zero initialization, but not explicit. We want to avoid
  8864. // that.
  8865. #if defined(__GNUC__)
  8866. # pragma GCC diagnostic push
  8867. # pragma GCC diagnostic ignored "-Wmissing-field-initializers"
  8868. #endif
  8869. static char* altStackMem = nullptr;
  8870. static std::size_t altStackSize = 0;
  8871. static stack_t oldSigStack{};
  8872. static struct sigaction oldSigActions[sizeof(signalDefs) / sizeof(SignalDefs)]{};
  8873. static void restorePreviousSignalHandlers() {
  8874. // We set signal handlers back to the previous ones. Hopefully
  8875. // nobody overwrote them in the meantime, and doesn't expect
  8876. // their signal handlers to live past ours given that they
  8877. // installed them after ours..
  8878. for (std::size_t i = 0; i < sizeof(signalDefs) / sizeof(SignalDefs); ++i) {
  8879. sigaction(signalDefs[i].id, &oldSigActions[i], nullptr);
  8880. }
  8881. // Return the old stack
  8882. sigaltstack(&oldSigStack, nullptr);
  8883. }
  8884. static void handleSignal( int sig ) {
  8885. char const * name = "<unknown signal>";
  8886. for (auto const& def : signalDefs) {
  8887. if (sig == def.id) {
  8888. name = def.name;
  8889. break;
  8890. }
  8891. }
  8892. // We need to restore previous signal handlers and let them do
  8893. // their thing, so that the users can have the debugger break
  8894. // when a signal is raised, and so on.
  8895. restorePreviousSignalHandlers();
  8896. reportFatal( name );
  8897. raise( sig );
  8898. }
  8899. FatalConditionHandler::FatalConditionHandler() {
  8900. assert(!altStackMem && "Cannot initialize POSIX signal handler when one already exists");
  8901. if (altStackSize == 0) {
  8902. altStackSize = std::max(static_cast<size_t>(SIGSTKSZ), minStackSizeForErrors);
  8903. }
  8904. altStackMem = new char[altStackSize]();
  8905. }
  8906. FatalConditionHandler::~FatalConditionHandler() {
  8907. delete[] altStackMem;
  8908. // We signal that another instance can be constructed by zeroing
  8909. // out the pointer.
  8910. altStackMem = nullptr;
  8911. }
  8912. void FatalConditionHandler::engage_platform() {
  8913. stack_t sigStack;
  8914. sigStack.ss_sp = altStackMem;
  8915. sigStack.ss_size = altStackSize;
  8916. sigStack.ss_flags = 0;
  8917. sigaltstack(&sigStack, &oldSigStack);
  8918. struct sigaction sa = { };
  8919. sa.sa_handler = handleSignal;
  8920. sa.sa_flags = SA_ONSTACK;
  8921. for (std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i) {
  8922. sigaction(signalDefs[i].id, &sa, &oldSigActions[i]);
  8923. }
  8924. }
  8925. #if defined(__GNUC__)
  8926. # pragma GCC diagnostic pop
  8927. #endif
  8928. void FatalConditionHandler::disengage_platform() {
  8929. restorePreviousSignalHandlers();
  8930. }
  8931. } // end namespace Catch
  8932. #endif // CATCH_CONFIG_POSIX_SIGNALS
  8933. // end catch_fatal_condition.cpp
  8934. // start catch_generators.cpp
  8935. #include <limits>
  8936. #include <set>
  8937. namespace Catch {
  8938. IGeneratorTracker::~IGeneratorTracker() {}
  8939. const char* GeneratorException::what() const noexcept {
  8940. return m_msg;
  8941. }
  8942. namespace Generators {
  8943. GeneratorUntypedBase::~GeneratorUntypedBase() {}
  8944. auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
  8945. return getResultCapture().acquireGeneratorTracker( generatorName, lineInfo );
  8946. }
  8947. } // namespace Generators
  8948. } // namespace Catch
  8949. // end catch_generators.cpp
  8950. // start catch_interfaces_capture.cpp
  8951. namespace Catch {
  8952. IResultCapture::~IResultCapture() = default;
  8953. }
  8954. // end catch_interfaces_capture.cpp
  8955. // start catch_interfaces_config.cpp
  8956. namespace Catch {
  8957. IConfig::~IConfig() = default;
  8958. }
  8959. // end catch_interfaces_config.cpp
  8960. // start catch_interfaces_exception.cpp
  8961. namespace Catch {
  8962. IExceptionTranslator::~IExceptionTranslator() = default;
  8963. IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() = default;
  8964. }
  8965. // end catch_interfaces_exception.cpp
  8966. // start catch_interfaces_registry_hub.cpp
  8967. namespace Catch {
  8968. IRegistryHub::~IRegistryHub() = default;
  8969. IMutableRegistryHub::~IMutableRegistryHub() = default;
  8970. }
  8971. // end catch_interfaces_registry_hub.cpp
  8972. // start catch_interfaces_reporter.cpp
  8973. // start catch_reporter_listening.h
  8974. namespace Catch {
  8975. class ListeningReporter : public IStreamingReporter {
  8976. using Reporters = std::vector<IStreamingReporterPtr>;
  8977. Reporters m_listeners;
  8978. IStreamingReporterPtr m_reporter = nullptr;
  8979. ReporterPreferences m_preferences;
  8980. public:
  8981. ListeningReporter();
  8982. void addListener( IStreamingReporterPtr&& listener );
  8983. void addReporter( IStreamingReporterPtr&& reporter );
  8984. public: // IStreamingReporter
  8985. ReporterPreferences getPreferences() const override;
  8986. void noMatchingTestCases( std::string const& spec ) override;
  8987. void reportInvalidArguments(std::string const&arg) override;
  8988. static std::set<Verbosity> getSupportedVerbosities();
  8989. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  8990. void benchmarkPreparing(std::string const& name) override;
  8991. void benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) override;
  8992. void benchmarkEnded( BenchmarkStats<> const& benchmarkStats ) override;
  8993. void benchmarkFailed(std::string const&) override;
  8994. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  8995. void testRunStarting( TestRunInfo const& testRunInfo ) override;
  8996. void testGroupStarting( GroupInfo const& groupInfo ) override;
  8997. void testCaseStarting( TestCaseInfo const& testInfo ) override;
  8998. void sectionStarting( SectionInfo const& sectionInfo ) override;
  8999. void assertionStarting( AssertionInfo const& assertionInfo ) override;
  9000. // The return value indicates if the messages buffer should be cleared:
  9001. bool assertionEnded( AssertionStats const& assertionStats ) override;
  9002. void sectionEnded( SectionStats const& sectionStats ) override;
  9003. void testCaseEnded( TestCaseStats const& testCaseStats ) override;
  9004. void testGroupEnded( TestGroupStats const& testGroupStats ) override;
  9005. void testRunEnded( TestRunStats const& testRunStats ) override;
  9006. void skipTest( TestCaseInfo const& testInfo ) override;
  9007. bool isMulti() const override;
  9008. };
  9009. } // end namespace Catch
  9010. // end catch_reporter_listening.h
  9011. namespace Catch {
  9012. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig )
  9013. : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {}
  9014. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream )
  9015. : m_stream( &_stream ), m_fullConfig( _fullConfig ) {}
  9016. std::ostream& ReporterConfig::stream() const { return *m_stream; }
  9017. IConfigPtr ReporterConfig::fullConfig() const { return m_fullConfig; }
  9018. TestRunInfo::TestRunInfo( std::string const& _name ) : name( _name ) {}
  9019. GroupInfo::GroupInfo( std::string const& _name,
  9020. std::size_t _groupIndex,
  9021. std::size_t _groupsCount )
  9022. : name( _name ),
  9023. groupIndex( _groupIndex ),
  9024. groupsCounts( _groupsCount )
  9025. {}
  9026. AssertionStats::AssertionStats( AssertionResult const& _assertionResult,
  9027. std::vector<MessageInfo> const& _infoMessages,
  9028. Totals const& _totals )
  9029. : assertionResult( _assertionResult ),
  9030. infoMessages( _infoMessages ),
  9031. totals( _totals )
  9032. {
  9033. assertionResult.m_resultData.lazyExpression.m_transientExpression = _assertionResult.m_resultData.lazyExpression.m_transientExpression;
  9034. if( assertionResult.hasMessage() ) {
  9035. // Copy message into messages list.
  9036. // !TBD This should have been done earlier, somewhere
  9037. MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() );
  9038. builder << assertionResult.getMessage();
  9039. builder.m_info.message = builder.m_stream.str();
  9040. infoMessages.push_back( builder.m_info );
  9041. }
  9042. }
  9043. AssertionStats::~AssertionStats() = default;
  9044. SectionStats::SectionStats( SectionInfo const& _sectionInfo,
  9045. Counts const& _assertions,
  9046. double _durationInSeconds,
  9047. bool _missingAssertions )
  9048. : sectionInfo( _sectionInfo ),
  9049. assertions( _assertions ),
  9050. durationInSeconds( _durationInSeconds ),
  9051. missingAssertions( _missingAssertions )
  9052. {}
  9053. SectionStats::~SectionStats() = default;
  9054. TestCaseStats::TestCaseStats( TestCaseInfo const& _testInfo,
  9055. Totals const& _totals,
  9056. std::string const& _stdOut,
  9057. std::string const& _stdErr,
  9058. bool _aborting )
  9059. : testInfo( _testInfo ),
  9060. totals( _totals ),
  9061. stdOut( _stdOut ),
  9062. stdErr( _stdErr ),
  9063. aborting( _aborting )
  9064. {}
  9065. TestCaseStats::~TestCaseStats() = default;
  9066. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo,
  9067. Totals const& _totals,
  9068. bool _aborting )
  9069. : groupInfo( _groupInfo ),
  9070. totals( _totals ),
  9071. aborting( _aborting )
  9072. {}
  9073. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo )
  9074. : groupInfo( _groupInfo ),
  9075. aborting( false )
  9076. {}
  9077. TestGroupStats::~TestGroupStats() = default;
  9078. TestRunStats::TestRunStats( TestRunInfo const& _runInfo,
  9079. Totals const& _totals,
  9080. bool _aborting )
  9081. : runInfo( _runInfo ),
  9082. totals( _totals ),
  9083. aborting( _aborting )
  9084. {}
  9085. TestRunStats::~TestRunStats() = default;
  9086. void IStreamingReporter::fatalErrorEncountered( StringRef ) {}
  9087. bool IStreamingReporter::isMulti() const { return false; }
  9088. IReporterFactory::~IReporterFactory() = default;
  9089. IReporterRegistry::~IReporterRegistry() = default;
  9090. } // end namespace Catch
  9091. // end catch_interfaces_reporter.cpp
  9092. // start catch_interfaces_runner.cpp
  9093. namespace Catch {
  9094. IRunner::~IRunner() = default;
  9095. }
  9096. // end catch_interfaces_runner.cpp
  9097. // start catch_interfaces_testcase.cpp
  9098. namespace Catch {
  9099. ITestInvoker::~ITestInvoker() = default;
  9100. ITestCaseRegistry::~ITestCaseRegistry() = default;
  9101. }
  9102. // end catch_interfaces_testcase.cpp
  9103. // start catch_leak_detector.cpp
  9104. #ifdef CATCH_CONFIG_WINDOWS_CRTDBG
  9105. #include <crtdbg.h>
  9106. namespace Catch {
  9107. LeakDetector::LeakDetector() {
  9108. int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
  9109. flag |= _CRTDBG_LEAK_CHECK_DF;
  9110. flag |= _CRTDBG_ALLOC_MEM_DF;
  9111. _CrtSetDbgFlag(flag);
  9112. _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
  9113. _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
  9114. // Change this to leaking allocation's number to break there
  9115. _CrtSetBreakAlloc(-1);
  9116. }
  9117. }
  9118. #else
  9119. Catch::LeakDetector::LeakDetector() {}
  9120. #endif
  9121. Catch::LeakDetector::~LeakDetector() {
  9122. Catch::cleanUp();
  9123. }
  9124. // end catch_leak_detector.cpp
  9125. // start catch_list.cpp
  9126. // start catch_list.h
  9127. #include <set>
  9128. namespace Catch {
  9129. std::size_t listTests( Config const& config );
  9130. std::size_t listTestsNamesOnly( Config const& config );
  9131. struct TagInfo {
  9132. void add( std::string const& spelling );
  9133. std::string all() const;
  9134. std::set<std::string> spellings;
  9135. std::size_t count = 0;
  9136. };
  9137. std::size_t listTags( Config const& config );
  9138. std::size_t listReporters();
  9139. Option<std::size_t> list( std::shared_ptr<Config> const& config );
  9140. } // end namespace Catch
  9141. // end catch_list.h
  9142. // start catch_text.h
  9143. namespace Catch {
  9144. using namespace clara::TextFlow;
  9145. }
  9146. // end catch_text.h
  9147. #include <limits>
  9148. #include <algorithm>
  9149. #include <iomanip>
  9150. namespace Catch {
  9151. std::size_t listTests( Config const& config ) {
  9152. TestSpec const& testSpec = config.testSpec();
  9153. if( config.hasTestFilters() )
  9154. Catch::cout() << "Matching test cases:\n";
  9155. else {
  9156. Catch::cout() << "All available test cases:\n";
  9157. }
  9158. auto matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  9159. for( auto const& testCaseInfo : matchedTestCases ) {
  9160. Colour::Code colour = testCaseInfo.isHidden()
  9161. ? Colour::SecondaryText
  9162. : Colour::None;
  9163. Colour colourGuard( colour );
  9164. Catch::cout() << Column( testCaseInfo.name ).initialIndent( 2 ).indent( 4 ) << "\n";
  9165. if( config.verbosity() >= Verbosity::High ) {
  9166. Catch::cout() << Column( Catch::Detail::stringify( testCaseInfo.lineInfo ) ).indent(4) << std::endl;
  9167. std::string description = testCaseInfo.description;
  9168. if( description.empty() )
  9169. description = "(NO DESCRIPTION)";
  9170. Catch::cout() << Column( description ).indent(4) << std::endl;
  9171. }
  9172. if( !testCaseInfo.tags.empty() )
  9173. Catch::cout() << Column( testCaseInfo.tagsAsString() ).indent( 6 ) << "\n";
  9174. }
  9175. if( !config.hasTestFilters() )
  9176. Catch::cout() << pluralise( matchedTestCases.size(), "test case" ) << '\n' << std::endl;
  9177. else
  9178. Catch::cout() << pluralise( matchedTestCases.size(), "matching test case" ) << '\n' << std::endl;
  9179. return matchedTestCases.size();
  9180. }
  9181. std::size_t listTestsNamesOnly( Config const& config ) {
  9182. TestSpec const& testSpec = config.testSpec();
  9183. std::size_t matchedTests = 0;
  9184. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  9185. for( auto const& testCaseInfo : matchedTestCases ) {
  9186. matchedTests++;
  9187. if( startsWith( testCaseInfo.name, '#' ) )
  9188. Catch::cout() << '"' << testCaseInfo.name << '"';
  9189. else
  9190. Catch::cout() << testCaseInfo.name;
  9191. if ( config.verbosity() >= Verbosity::High )
  9192. Catch::cout() << "\t@" << testCaseInfo.lineInfo;
  9193. Catch::cout() << std::endl;
  9194. }
  9195. return matchedTests;
  9196. }
  9197. void TagInfo::add( std::string const& spelling ) {
  9198. ++count;
  9199. spellings.insert( spelling );
  9200. }
  9201. std::string TagInfo::all() const {
  9202. size_t size = 0;
  9203. for (auto const& spelling : spellings) {
  9204. // Add 2 for the brackes
  9205. size += spelling.size() + 2;
  9206. }
  9207. std::string out; out.reserve(size);
  9208. for (auto const& spelling : spellings) {
  9209. out += '[';
  9210. out += spelling;
  9211. out += ']';
  9212. }
  9213. return out;
  9214. }
  9215. std::size_t listTags( Config const& config ) {
  9216. TestSpec const& testSpec = config.testSpec();
  9217. if( config.hasTestFilters() )
  9218. Catch::cout() << "Tags for matching test cases:\n";
  9219. else {
  9220. Catch::cout() << "All available tags:\n";
  9221. }
  9222. std::map<std::string, TagInfo> tagCounts;
  9223. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  9224. for( auto const& testCase : matchedTestCases ) {
  9225. for( auto const& tagName : testCase.getTestCaseInfo().tags ) {
  9226. std::string lcaseTagName = toLower( tagName );
  9227. auto countIt = tagCounts.find( lcaseTagName );
  9228. if( countIt == tagCounts.end() )
  9229. countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first;
  9230. countIt->second.add( tagName );
  9231. }
  9232. }
  9233. for( auto const& tagCount : tagCounts ) {
  9234. ReusableStringStream rss;
  9235. rss << " " << std::setw(2) << tagCount.second.count << " ";
  9236. auto str = rss.str();
  9237. auto wrapper = Column( tagCount.second.all() )
  9238. .initialIndent( 0 )
  9239. .indent( str.size() )
  9240. .width( CATCH_CONFIG_CONSOLE_WIDTH-10 );
  9241. Catch::cout() << str << wrapper << '\n';
  9242. }
  9243. Catch::cout() << pluralise( tagCounts.size(), "tag" ) << '\n' << std::endl;
  9244. return tagCounts.size();
  9245. }
  9246. std::size_t listReporters() {
  9247. Catch::cout() << "Available reporters:\n";
  9248. IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
  9249. std::size_t maxNameLen = 0;
  9250. for( auto const& factoryKvp : factories )
  9251. maxNameLen = (std::max)( maxNameLen, factoryKvp.first.size() );
  9252. for( auto const& factoryKvp : factories ) {
  9253. Catch::cout()
  9254. << Column( factoryKvp.first + ":" )
  9255. .indent(2)
  9256. .width( 5+maxNameLen )
  9257. + Column( factoryKvp.second->getDescription() )
  9258. .initialIndent(0)
  9259. .indent(2)
  9260. .width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 )
  9261. << "\n";
  9262. }
  9263. Catch::cout() << std::endl;
  9264. return factories.size();
  9265. }
  9266. Option<std::size_t> list( std::shared_ptr<Config> const& config ) {
  9267. Option<std::size_t> listedCount;
  9268. getCurrentMutableContext().setConfig( config );
  9269. if( config->listTests() )
  9270. listedCount = listedCount.valueOr(0) + listTests( *config );
  9271. if( config->listTestNamesOnly() )
  9272. listedCount = listedCount.valueOr(0) + listTestsNamesOnly( *config );
  9273. if( config->listTags() )
  9274. listedCount = listedCount.valueOr(0) + listTags( *config );
  9275. if( config->listReporters() )
  9276. listedCount = listedCount.valueOr(0) + listReporters();
  9277. return listedCount;
  9278. }
  9279. } // end namespace Catch
  9280. // end catch_list.cpp
  9281. // start catch_matchers.cpp
  9282. namespace Catch {
  9283. namespace Matchers {
  9284. namespace Impl {
  9285. std::string MatcherUntypedBase::toString() const {
  9286. if( m_cachedToString.empty() )
  9287. m_cachedToString = describe();
  9288. return m_cachedToString;
  9289. }
  9290. MatcherUntypedBase::~MatcherUntypedBase() = default;
  9291. } // namespace Impl
  9292. } // namespace Matchers
  9293. using namespace Matchers;
  9294. using Matchers::Impl::MatcherBase;
  9295. } // namespace Catch
  9296. // end catch_matchers.cpp
  9297. // start catch_matchers_exception.cpp
  9298. namespace Catch {
  9299. namespace Matchers {
  9300. namespace Exception {
  9301. bool ExceptionMessageMatcher::match(std::exception const& ex) const {
  9302. return ex.what() == m_message;
  9303. }
  9304. std::string ExceptionMessageMatcher::describe() const {
  9305. return "exception message matches \"" + m_message + "\"";
  9306. }
  9307. }
  9308. Exception::ExceptionMessageMatcher Message(std::string const& message) {
  9309. return Exception::ExceptionMessageMatcher(message);
  9310. }
  9311. // namespace Exception
  9312. } // namespace Matchers
  9313. } // namespace Catch
  9314. // end catch_matchers_exception.cpp
  9315. // start catch_matchers_floating.cpp
  9316. // start catch_polyfills.hpp
  9317. namespace Catch {
  9318. bool isnan(float f);
  9319. bool isnan(double d);
  9320. }
  9321. // end catch_polyfills.hpp
  9322. // start catch_to_string.hpp
  9323. #include <string>
  9324. namespace Catch {
  9325. template <typename T>
  9326. std::string to_string(T const& t) {
  9327. #if defined(CATCH_CONFIG_CPP11_TO_STRING)
  9328. return std::to_string(t);
  9329. #else
  9330. ReusableStringStream rss;
  9331. rss << t;
  9332. return rss.str();
  9333. #endif
  9334. }
  9335. } // end namespace Catch
  9336. // end catch_to_string.hpp
  9337. #include <algorithm>
  9338. #include <cmath>
  9339. #include <cstdlib>
  9340. #include <cstdint>
  9341. #include <cstring>
  9342. #include <sstream>
  9343. #include <type_traits>
  9344. #include <iomanip>
  9345. #include <limits>
  9346. namespace Catch {
  9347. namespace {
  9348. int32_t convert(float f) {
  9349. static_assert(sizeof(float) == sizeof(int32_t), "Important ULP matcher assumption violated");
  9350. int32_t i;
  9351. std::memcpy(&i, &f, sizeof(f));
  9352. return i;
  9353. }
  9354. int64_t convert(double d) {
  9355. static_assert(sizeof(double) == sizeof(int64_t), "Important ULP matcher assumption violated");
  9356. int64_t i;
  9357. std::memcpy(&i, &d, sizeof(d));
  9358. return i;
  9359. }
  9360. template <typename FP>
  9361. bool almostEqualUlps(FP lhs, FP rhs, uint64_t maxUlpDiff) {
  9362. // Comparison with NaN should always be false.
  9363. // This way we can rule it out before getting into the ugly details
  9364. if (Catch::isnan(lhs) || Catch::isnan(rhs)) {
  9365. return false;
  9366. }
  9367. auto lc = convert(lhs);
  9368. auto rc = convert(rhs);
  9369. if ((lc < 0) != (rc < 0)) {
  9370. // Potentially we can have +0 and -0
  9371. return lhs == rhs;
  9372. }
  9373. // static cast as a workaround for IBM XLC
  9374. auto ulpDiff = std::abs(static_cast<FP>(lc - rc));
  9375. return static_cast<uint64_t>(ulpDiff) <= maxUlpDiff;
  9376. }
  9377. #if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
  9378. float nextafter(float x, float y) {
  9379. return ::nextafterf(x, y);
  9380. }
  9381. double nextafter(double x, double y) {
  9382. return ::nextafter(x, y);
  9383. }
  9384. #endif // ^^^ CATCH_CONFIG_GLOBAL_NEXTAFTER ^^^
  9385. template <typename FP>
  9386. FP step(FP start, FP direction, uint64_t steps) {
  9387. for (uint64_t i = 0; i < steps; ++i) {
  9388. #if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
  9389. start = Catch::nextafter(start, direction);
  9390. #else
  9391. start = std::nextafter(start, direction);
  9392. #endif
  9393. }
  9394. return start;
  9395. }
  9396. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  9397. // But without the subtraction to allow for INFINITY in comparison
  9398. bool marginComparison(double lhs, double rhs, double margin) {
  9399. return (lhs + margin >= rhs) && (rhs + margin >= lhs);
  9400. }
  9401. template <typename FloatingPoint>
  9402. void write(std::ostream& out, FloatingPoint num) {
  9403. out << std::scientific
  9404. << std::setprecision(std::numeric_limits<FloatingPoint>::max_digits10 - 1)
  9405. << num;
  9406. }
  9407. } // end anonymous namespace
  9408. namespace Matchers {
  9409. namespace Floating {
  9410. enum class FloatingPointKind : uint8_t {
  9411. Float,
  9412. Double
  9413. };
  9414. WithinAbsMatcher::WithinAbsMatcher(double target, double margin)
  9415. :m_target{ target }, m_margin{ margin } {
  9416. CATCH_ENFORCE(margin >= 0, "Invalid margin: " << margin << '.'
  9417. << " Margin has to be non-negative.");
  9418. }
  9419. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  9420. // But without the subtraction to allow for INFINITY in comparison
  9421. bool WithinAbsMatcher::match(double const& matchee) const {
  9422. return (matchee + m_margin >= m_target) && (m_target + m_margin >= matchee);
  9423. }
  9424. std::string WithinAbsMatcher::describe() const {
  9425. return "is within " + ::Catch::Detail::stringify(m_margin) + " of " + ::Catch::Detail::stringify(m_target);
  9426. }
  9427. WithinUlpsMatcher::WithinUlpsMatcher(double target, uint64_t ulps, FloatingPointKind baseType)
  9428. :m_target{ target }, m_ulps{ ulps }, m_type{ baseType } {
  9429. CATCH_ENFORCE(m_type == FloatingPointKind::Double
  9430. || m_ulps < (std::numeric_limits<uint32_t>::max)(),
  9431. "Provided ULP is impossibly large for a float comparison.");
  9432. }
  9433. #if defined(__clang__)
  9434. #pragma clang diagnostic push
  9435. // Clang <3.5 reports on the default branch in the switch below
  9436. #pragma clang diagnostic ignored "-Wunreachable-code"
  9437. #endif
  9438. bool WithinUlpsMatcher::match(double const& matchee) const {
  9439. switch (m_type) {
  9440. case FloatingPointKind::Float:
  9441. return almostEqualUlps<float>(static_cast<float>(matchee), static_cast<float>(m_target), m_ulps);
  9442. case FloatingPointKind::Double:
  9443. return almostEqualUlps<double>(matchee, m_target, m_ulps);
  9444. default:
  9445. CATCH_INTERNAL_ERROR( "Unknown FloatingPointKind value" );
  9446. }
  9447. }
  9448. #if defined(__clang__)
  9449. #pragma clang diagnostic pop
  9450. #endif
  9451. std::string WithinUlpsMatcher::describe() const {
  9452. std::stringstream ret;
  9453. ret << "is within " << m_ulps << " ULPs of ";
  9454. if (m_type == FloatingPointKind::Float) {
  9455. write(ret, static_cast<float>(m_target));
  9456. ret << 'f';
  9457. } else {
  9458. write(ret, m_target);
  9459. }
  9460. ret << " ([";
  9461. if (m_type == FloatingPointKind::Double) {
  9462. write(ret, step(m_target, static_cast<double>(-INFINITY), m_ulps));
  9463. ret << ", ";
  9464. write(ret, step(m_target, static_cast<double>( INFINITY), m_ulps));
  9465. } else {
  9466. // We have to cast INFINITY to float because of MinGW, see #1782
  9467. write(ret, step(static_cast<float>(m_target), static_cast<float>(-INFINITY), m_ulps));
  9468. ret << ", ";
  9469. write(ret, step(static_cast<float>(m_target), static_cast<float>( INFINITY), m_ulps));
  9470. }
  9471. ret << "])";
  9472. return ret.str();
  9473. }
  9474. WithinRelMatcher::WithinRelMatcher(double target, double epsilon):
  9475. m_target(target),
  9476. m_epsilon(epsilon){
  9477. CATCH_ENFORCE(m_epsilon >= 0., "Relative comparison with epsilon < 0 does not make sense.");
  9478. CATCH_ENFORCE(m_epsilon < 1., "Relative comparison with epsilon >= 1 does not make sense.");
  9479. }
  9480. bool WithinRelMatcher::match(double const& matchee) const {
  9481. const auto relMargin = m_epsilon * (std::max)(std::fabs(matchee), std::fabs(m_target));
  9482. return marginComparison(matchee, m_target,
  9483. std::isinf(relMargin)? 0 : relMargin);
  9484. }
  9485. std::string WithinRelMatcher::describe() const {
  9486. Catch::ReusableStringStream sstr;
  9487. sstr << "and " << m_target << " are within " << m_epsilon * 100. << "% of each other";
  9488. return sstr.str();
  9489. }
  9490. }// namespace Floating
  9491. Floating::WithinUlpsMatcher WithinULP(double target, uint64_t maxUlpDiff) {
  9492. return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Double);
  9493. }
  9494. Floating::WithinUlpsMatcher WithinULP(float target, uint64_t maxUlpDiff) {
  9495. return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Float);
  9496. }
  9497. Floating::WithinAbsMatcher WithinAbs(double target, double margin) {
  9498. return Floating::WithinAbsMatcher(target, margin);
  9499. }
  9500. Floating::WithinRelMatcher WithinRel(double target, double eps) {
  9501. return Floating::WithinRelMatcher(target, eps);
  9502. }
  9503. Floating::WithinRelMatcher WithinRel(double target) {
  9504. return Floating::WithinRelMatcher(target, std::numeric_limits<double>::epsilon() * 100);
  9505. }
  9506. Floating::WithinRelMatcher WithinRel(float target, float eps) {
  9507. return Floating::WithinRelMatcher(target, eps);
  9508. }
  9509. Floating::WithinRelMatcher WithinRel(float target) {
  9510. return Floating::WithinRelMatcher(target, std::numeric_limits<float>::epsilon() * 100);
  9511. }
  9512. } // namespace Matchers
  9513. } // namespace Catch
  9514. // end catch_matchers_floating.cpp
  9515. // start catch_matchers_generic.cpp
  9516. std::string Catch::Matchers::Generic::Detail::finalizeDescription(const std::string& desc) {
  9517. if (desc.empty()) {
  9518. return "matches undescribed predicate";
  9519. } else {
  9520. return "matches predicate: \"" + desc + '"';
  9521. }
  9522. }
  9523. // end catch_matchers_generic.cpp
  9524. // start catch_matchers_string.cpp
  9525. #include <regex>
  9526. namespace Catch {
  9527. namespace Matchers {
  9528. namespace StdString {
  9529. CasedString::CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity )
  9530. : m_caseSensitivity( caseSensitivity ),
  9531. m_str( adjustString( str ) )
  9532. {}
  9533. std::string CasedString::adjustString( std::string const& str ) const {
  9534. return m_caseSensitivity == CaseSensitive::No
  9535. ? toLower( str )
  9536. : str;
  9537. }
  9538. std::string CasedString::caseSensitivitySuffix() const {
  9539. return m_caseSensitivity == CaseSensitive::No
  9540. ? " (case insensitive)"
  9541. : std::string();
  9542. }
  9543. StringMatcherBase::StringMatcherBase( std::string const& operation, CasedString const& comparator )
  9544. : m_comparator( comparator ),
  9545. m_operation( operation ) {
  9546. }
  9547. std::string StringMatcherBase::describe() const {
  9548. std::string description;
  9549. description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
  9550. m_comparator.caseSensitivitySuffix().size());
  9551. description += m_operation;
  9552. description += ": \"";
  9553. description += m_comparator.m_str;
  9554. description += "\"";
  9555. description += m_comparator.caseSensitivitySuffix();
  9556. return description;
  9557. }
  9558. EqualsMatcher::EqualsMatcher( CasedString const& comparator ) : StringMatcherBase( "equals", comparator ) {}
  9559. bool EqualsMatcher::match( std::string const& source ) const {
  9560. return m_comparator.adjustString( source ) == m_comparator.m_str;
  9561. }
  9562. ContainsMatcher::ContainsMatcher( CasedString const& comparator ) : StringMatcherBase( "contains", comparator ) {}
  9563. bool ContainsMatcher::match( std::string const& source ) const {
  9564. return contains( m_comparator.adjustString( source ), m_comparator.m_str );
  9565. }
  9566. StartsWithMatcher::StartsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "starts with", comparator ) {}
  9567. bool StartsWithMatcher::match( std::string const& source ) const {
  9568. return startsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  9569. }
  9570. EndsWithMatcher::EndsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "ends with", comparator ) {}
  9571. bool EndsWithMatcher::match( std::string const& source ) const {
  9572. return endsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  9573. }
  9574. RegexMatcher::RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity): m_regex(std::move(regex)), m_caseSensitivity(caseSensitivity) {}
  9575. bool RegexMatcher::match(std::string const& matchee) const {
  9576. auto flags = std::regex::ECMAScript; // ECMAScript is the default syntax option anyway
  9577. if (m_caseSensitivity == CaseSensitive::Choice::No) {
  9578. flags |= std::regex::icase;
  9579. }
  9580. auto reg = std::regex(m_regex, flags);
  9581. return std::regex_match(matchee, reg);
  9582. }
  9583. std::string RegexMatcher::describe() const {
  9584. return "matches " + ::Catch::Detail::stringify(m_regex) + ((m_caseSensitivity == CaseSensitive::Choice::Yes)? " case sensitively" : " case insensitively");
  9585. }
  9586. } // namespace StdString
  9587. StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  9588. return StdString::EqualsMatcher( StdString::CasedString( str, caseSensitivity) );
  9589. }
  9590. StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  9591. return StdString::ContainsMatcher( StdString::CasedString( str, caseSensitivity) );
  9592. }
  9593. StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  9594. return StdString::EndsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  9595. }
  9596. StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  9597. return StdString::StartsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  9598. }
  9599. StdString::RegexMatcher Matches(std::string const& regex, CaseSensitive::Choice caseSensitivity) {
  9600. return StdString::RegexMatcher(regex, caseSensitivity);
  9601. }
  9602. } // namespace Matchers
  9603. } // namespace Catch
  9604. // end catch_matchers_string.cpp
  9605. // start catch_message.cpp
  9606. // start catch_uncaught_exceptions.h
  9607. namespace Catch {
  9608. bool uncaught_exceptions();
  9609. } // end namespace Catch
  9610. // end catch_uncaught_exceptions.h
  9611. #include <cassert>
  9612. #include <stack>
  9613. namespace Catch {
  9614. MessageInfo::MessageInfo( StringRef const& _macroName,
  9615. SourceLineInfo const& _lineInfo,
  9616. ResultWas::OfType _type )
  9617. : macroName( _macroName ),
  9618. lineInfo( _lineInfo ),
  9619. type( _type ),
  9620. sequence( ++globalCount )
  9621. {}
  9622. bool MessageInfo::operator==( MessageInfo const& other ) const {
  9623. return sequence == other.sequence;
  9624. }
  9625. bool MessageInfo::operator<( MessageInfo const& other ) const {
  9626. return sequence < other.sequence;
  9627. }
  9628. // This may need protecting if threading support is added
  9629. unsigned int MessageInfo::globalCount = 0;
  9630. ////////////////////////////////////////////////////////////////////////////
  9631. Catch::MessageBuilder::MessageBuilder( StringRef const& macroName,
  9632. SourceLineInfo const& lineInfo,
  9633. ResultWas::OfType type )
  9634. :m_info(macroName, lineInfo, type) {}
  9635. ////////////////////////////////////////////////////////////////////////////
  9636. ScopedMessage::ScopedMessage( MessageBuilder const& builder )
  9637. : m_info( builder.m_info ), m_moved()
  9638. {
  9639. m_info.message = builder.m_stream.str();
  9640. getResultCapture().pushScopedMessage( m_info );
  9641. }
  9642. ScopedMessage::ScopedMessage( ScopedMessage&& old )
  9643. : m_info( old.m_info ), m_moved()
  9644. {
  9645. old.m_moved = true;
  9646. }
  9647. ScopedMessage::~ScopedMessage() {
  9648. if ( !uncaught_exceptions() && !m_moved ){
  9649. getResultCapture().popScopedMessage(m_info);
  9650. }
  9651. }
  9652. Capturer::Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names ) {
  9653. auto trimmed = [&] (size_t start, size_t end) {
  9654. while (names[start] == ',' || isspace(static_cast<unsigned char>(names[start]))) {
  9655. ++start;
  9656. }
  9657. while (names[end] == ',' || isspace(static_cast<unsigned char>(names[end]))) {
  9658. --end;
  9659. }
  9660. return names.substr(start, end - start + 1);
  9661. };
  9662. auto skipq = [&] (size_t start, char quote) {
  9663. for (auto i = start + 1; i < names.size() ; ++i) {
  9664. if (names[i] == quote)
  9665. return i;
  9666. if (names[i] == '\\')
  9667. ++i;
  9668. }
  9669. CATCH_INTERNAL_ERROR("CAPTURE parsing encountered unmatched quote");
  9670. };
  9671. size_t start = 0;
  9672. std::stack<char> openings;
  9673. for (size_t pos = 0; pos < names.size(); ++pos) {
  9674. char c = names[pos];
  9675. switch (c) {
  9676. case '[':
  9677. case '{':
  9678. case '(':
  9679. // It is basically impossible to disambiguate between
  9680. // comparison and start of template args in this context
  9681. // case '<':
  9682. openings.push(c);
  9683. break;
  9684. case ']':
  9685. case '}':
  9686. case ')':
  9687. // case '>':
  9688. openings.pop();
  9689. break;
  9690. case '"':
  9691. case '\'':
  9692. pos = skipq(pos, c);
  9693. break;
  9694. case ',':
  9695. if (start != pos && openings.empty()) {
  9696. m_messages.emplace_back(macroName, lineInfo, resultType);
  9697. m_messages.back().message = static_cast<std::string>(trimmed(start, pos));
  9698. m_messages.back().message += " := ";
  9699. start = pos;
  9700. }
  9701. }
  9702. }
  9703. assert(openings.empty() && "Mismatched openings");
  9704. m_messages.emplace_back(macroName, lineInfo, resultType);
  9705. m_messages.back().message = static_cast<std::string>(trimmed(start, names.size() - 1));
  9706. m_messages.back().message += " := ";
  9707. }
  9708. Capturer::~Capturer() {
  9709. if ( !uncaught_exceptions() ){
  9710. assert( m_captured == m_messages.size() );
  9711. for( size_t i = 0; i < m_captured; ++i )
  9712. m_resultCapture.popScopedMessage( m_messages[i] );
  9713. }
  9714. }
  9715. void Capturer::captureValue( size_t index, std::string const& value ) {
  9716. assert( index < m_messages.size() );
  9717. m_messages[index].message += value;
  9718. m_resultCapture.pushScopedMessage( m_messages[index] );
  9719. m_captured++;
  9720. }
  9721. } // end namespace Catch
  9722. // end catch_message.cpp
  9723. // start catch_output_redirect.cpp
  9724. // start catch_output_redirect.h
  9725. #ifndef TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  9726. #define TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  9727. #include <cstdio>
  9728. #include <iosfwd>
  9729. #include <string>
  9730. namespace Catch {
  9731. class RedirectedStream {
  9732. std::ostream& m_originalStream;
  9733. std::ostream& m_redirectionStream;
  9734. std::streambuf* m_prevBuf;
  9735. public:
  9736. RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream );
  9737. ~RedirectedStream();
  9738. };
  9739. class RedirectedStdOut {
  9740. ReusableStringStream m_rss;
  9741. RedirectedStream m_cout;
  9742. public:
  9743. RedirectedStdOut();
  9744. auto str() const -> std::string;
  9745. };
  9746. // StdErr has two constituent streams in C++, std::cerr and std::clog
  9747. // This means that we need to redirect 2 streams into 1 to keep proper
  9748. // order of writes
  9749. class RedirectedStdErr {
  9750. ReusableStringStream m_rss;
  9751. RedirectedStream m_cerr;
  9752. RedirectedStream m_clog;
  9753. public:
  9754. RedirectedStdErr();
  9755. auto str() const -> std::string;
  9756. };
  9757. class RedirectedStreams {
  9758. public:
  9759. RedirectedStreams(RedirectedStreams const&) = delete;
  9760. RedirectedStreams& operator=(RedirectedStreams const&) = delete;
  9761. RedirectedStreams(RedirectedStreams&&) = delete;
  9762. RedirectedStreams& operator=(RedirectedStreams&&) = delete;
  9763. RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr);
  9764. ~RedirectedStreams();
  9765. private:
  9766. std::string& m_redirectedCout;
  9767. std::string& m_redirectedCerr;
  9768. RedirectedStdOut m_redirectedStdOut;
  9769. RedirectedStdErr m_redirectedStdErr;
  9770. };
  9771. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  9772. // Windows's implementation of std::tmpfile is terrible (it tries
  9773. // to create a file inside system folder, thus requiring elevated
  9774. // privileges for the binary), so we have to use tmpnam(_s) and
  9775. // create the file ourselves there.
  9776. class TempFile {
  9777. public:
  9778. TempFile(TempFile const&) = delete;
  9779. TempFile& operator=(TempFile const&) = delete;
  9780. TempFile(TempFile&&) = delete;
  9781. TempFile& operator=(TempFile&&) = delete;
  9782. TempFile();
  9783. ~TempFile();
  9784. std::FILE* getFile();
  9785. std::string getContents();
  9786. private:
  9787. std::FILE* m_file = nullptr;
  9788. #if defined(_MSC_VER)
  9789. char m_buffer[L_tmpnam] = { 0 };
  9790. #endif
  9791. };
  9792. class OutputRedirect {
  9793. public:
  9794. OutputRedirect(OutputRedirect const&) = delete;
  9795. OutputRedirect& operator=(OutputRedirect const&) = delete;
  9796. OutputRedirect(OutputRedirect&&) = delete;
  9797. OutputRedirect& operator=(OutputRedirect&&) = delete;
  9798. OutputRedirect(std::string& stdout_dest, std::string& stderr_dest);
  9799. ~OutputRedirect();
  9800. private:
  9801. int m_originalStdout = -1;
  9802. int m_originalStderr = -1;
  9803. TempFile m_stdoutFile;
  9804. TempFile m_stderrFile;
  9805. std::string& m_stdoutDest;
  9806. std::string& m_stderrDest;
  9807. };
  9808. #endif
  9809. } // end namespace Catch
  9810. #endif // TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  9811. // end catch_output_redirect.h
  9812. #include <cstdio>
  9813. #include <cstring>
  9814. #include <fstream>
  9815. #include <sstream>
  9816. #include <stdexcept>
  9817. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  9818. #if defined(_MSC_VER)
  9819. #include <io.h> //_dup and _dup2
  9820. #define dup _dup
  9821. #define dup2 _dup2
  9822. #define fileno _fileno
  9823. #else
  9824. #include <unistd.h> // dup and dup2
  9825. #endif
  9826. #endif
  9827. namespace Catch {
  9828. RedirectedStream::RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream )
  9829. : m_originalStream( originalStream ),
  9830. m_redirectionStream( redirectionStream ),
  9831. m_prevBuf( m_originalStream.rdbuf() )
  9832. {
  9833. m_originalStream.rdbuf( m_redirectionStream.rdbuf() );
  9834. }
  9835. RedirectedStream::~RedirectedStream() {
  9836. m_originalStream.rdbuf( m_prevBuf );
  9837. }
  9838. RedirectedStdOut::RedirectedStdOut() : m_cout( Catch::cout(), m_rss.get() ) {}
  9839. auto RedirectedStdOut::str() const -> std::string { return m_rss.str(); }
  9840. RedirectedStdErr::RedirectedStdErr()
  9841. : m_cerr( Catch::cerr(), m_rss.get() ),
  9842. m_clog( Catch::clog(), m_rss.get() )
  9843. {}
  9844. auto RedirectedStdErr::str() const -> std::string { return m_rss.str(); }
  9845. RedirectedStreams::RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr)
  9846. : m_redirectedCout(redirectedCout),
  9847. m_redirectedCerr(redirectedCerr)
  9848. {}
  9849. RedirectedStreams::~RedirectedStreams() {
  9850. m_redirectedCout += m_redirectedStdOut.str();
  9851. m_redirectedCerr += m_redirectedStdErr.str();
  9852. }
  9853. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  9854. #if defined(_MSC_VER)
  9855. TempFile::TempFile() {
  9856. if (tmpnam_s(m_buffer)) {
  9857. CATCH_RUNTIME_ERROR("Could not get a temp filename");
  9858. }
  9859. if (fopen_s(&m_file, m_buffer, "w+")) {
  9860. char buffer[100];
  9861. if (strerror_s(buffer, errno)) {
  9862. CATCH_RUNTIME_ERROR("Could not translate errno to a string");
  9863. }
  9864. CATCH_RUNTIME_ERROR("Could not open the temp file: '" << m_buffer << "' because: " << buffer);
  9865. }
  9866. }
  9867. #else
  9868. TempFile::TempFile() {
  9869. m_file = std::tmpfile();
  9870. if (!m_file) {
  9871. CATCH_RUNTIME_ERROR("Could not create a temp file.");
  9872. }
  9873. }
  9874. #endif
  9875. TempFile::~TempFile() {
  9876. // TBD: What to do about errors here?
  9877. std::fclose(m_file);
  9878. // We manually create the file on Windows only, on Linux
  9879. // it will be autodeleted
  9880. #if defined(_MSC_VER)
  9881. std::remove(m_buffer);
  9882. #endif
  9883. }
  9884. FILE* TempFile::getFile() {
  9885. return m_file;
  9886. }
  9887. std::string TempFile::getContents() {
  9888. std::stringstream sstr;
  9889. char buffer[100] = {};
  9890. std::rewind(m_file);
  9891. while (std::fgets(buffer, sizeof(buffer), m_file)) {
  9892. sstr << buffer;
  9893. }
  9894. return sstr.str();
  9895. }
  9896. OutputRedirect::OutputRedirect(std::string& stdout_dest, std::string& stderr_dest) :
  9897. m_originalStdout(dup(1)),
  9898. m_originalStderr(dup(2)),
  9899. m_stdoutDest(stdout_dest),
  9900. m_stderrDest(stderr_dest) {
  9901. dup2(fileno(m_stdoutFile.getFile()), 1);
  9902. dup2(fileno(m_stderrFile.getFile()), 2);
  9903. }
  9904. OutputRedirect::~OutputRedirect() {
  9905. Catch::cout() << std::flush;
  9906. fflush(stdout);
  9907. // Since we support overriding these streams, we flush cerr
  9908. // even though std::cerr is unbuffered
  9909. Catch::cerr() << std::flush;
  9910. Catch::clog() << std::flush;
  9911. fflush(stderr);
  9912. dup2(m_originalStdout, 1);
  9913. dup2(m_originalStderr, 2);
  9914. m_stdoutDest += m_stdoutFile.getContents();
  9915. m_stderrDest += m_stderrFile.getContents();
  9916. }
  9917. #endif // CATCH_CONFIG_NEW_CAPTURE
  9918. } // namespace Catch
  9919. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  9920. #if defined(_MSC_VER)
  9921. #undef dup
  9922. #undef dup2
  9923. #undef fileno
  9924. #endif
  9925. #endif
  9926. // end catch_output_redirect.cpp
  9927. // start catch_polyfills.cpp
  9928. #include <cmath>
  9929. namespace Catch {
  9930. #if !defined(CATCH_CONFIG_POLYFILL_ISNAN)
  9931. bool isnan(float f) {
  9932. return std::isnan(f);
  9933. }
  9934. bool isnan(double d) {
  9935. return std::isnan(d);
  9936. }
  9937. #else
  9938. // For now we only use this for embarcadero
  9939. bool isnan(float f) {
  9940. return std::_isnan(f);
  9941. }
  9942. bool isnan(double d) {
  9943. return std::_isnan(d);
  9944. }
  9945. #endif
  9946. } // end namespace Catch
  9947. // end catch_polyfills.cpp
  9948. // start catch_random_number_generator.cpp
  9949. namespace Catch {
  9950. namespace {
  9951. #if defined(_MSC_VER)
  9952. #pragma warning(push)
  9953. #pragma warning(disable:4146) // we negate uint32 during the rotate
  9954. #endif
  9955. // Safe rotr implementation thanks to John Regehr
  9956. uint32_t rotate_right(uint32_t val, uint32_t count) {
  9957. const uint32_t mask = 31;
  9958. count &= mask;
  9959. return (val >> count) | (val << (-count & mask));
  9960. }
  9961. #if defined(_MSC_VER)
  9962. #pragma warning(pop)
  9963. #endif
  9964. }
  9965. SimplePcg32::SimplePcg32(result_type seed_) {
  9966. seed(seed_);
  9967. }
  9968. void SimplePcg32::seed(result_type seed_) {
  9969. m_state = 0;
  9970. (*this)();
  9971. m_state += seed_;
  9972. (*this)();
  9973. }
  9974. void SimplePcg32::discard(uint64_t skip) {
  9975. // We could implement this to run in O(log n) steps, but this
  9976. // should suffice for our use case.
  9977. for (uint64_t s = 0; s < skip; ++s) {
  9978. static_cast<void>((*this)());
  9979. }
  9980. }
  9981. SimplePcg32::result_type SimplePcg32::operator()() {
  9982. // prepare the output value
  9983. const uint32_t xorshifted = static_cast<uint32_t>(((m_state >> 18u) ^ m_state) >> 27u);
  9984. const auto output = rotate_right(xorshifted, m_state >> 59u);
  9985. // advance state
  9986. m_state = m_state * 6364136223846793005ULL + s_inc;
  9987. return output;
  9988. }
  9989. bool operator==(SimplePcg32 const& lhs, SimplePcg32 const& rhs) {
  9990. return lhs.m_state == rhs.m_state;
  9991. }
  9992. bool operator!=(SimplePcg32 const& lhs, SimplePcg32 const& rhs) {
  9993. return lhs.m_state != rhs.m_state;
  9994. }
  9995. }
  9996. // end catch_random_number_generator.cpp
  9997. // start catch_registry_hub.cpp
  9998. // start catch_test_case_registry_impl.h
  9999. #include <vector>
  10000. #include <set>
  10001. #include <algorithm>
  10002. #include <ios>
  10003. namespace Catch {
  10004. class TestCase;
  10005. struct IConfig;
  10006. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases );
  10007. bool isThrowSafe( TestCase const& testCase, IConfig const& config );
  10008. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
  10009. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions );
  10010. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
  10011. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
  10012. class TestRegistry : public ITestCaseRegistry {
  10013. public:
  10014. virtual ~TestRegistry() = default;
  10015. virtual void registerTest( TestCase const& testCase );
  10016. std::vector<TestCase> const& getAllTests() const override;
  10017. std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const override;
  10018. private:
  10019. std::vector<TestCase> m_functions;
  10020. mutable RunTests::InWhatOrder m_currentSortOrder = RunTests::InDeclarationOrder;
  10021. mutable std::vector<TestCase> m_sortedFunctions;
  10022. std::size_t m_unnamedCount = 0;
  10023. std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised
  10024. };
  10025. ///////////////////////////////////////////////////////////////////////////
  10026. class TestInvokerAsFunction : public ITestInvoker {
  10027. void(*m_testAsFunction)();
  10028. public:
  10029. TestInvokerAsFunction( void(*testAsFunction)() ) noexcept;
  10030. void invoke() const override;
  10031. };
  10032. std::string extractClassName( StringRef const& classOrQualifiedMethodName );
  10033. ///////////////////////////////////////////////////////////////////////////
  10034. } // end namespace Catch
  10035. // end catch_test_case_registry_impl.h
  10036. // start catch_reporter_registry.h
  10037. #include <map>
  10038. namespace Catch {
  10039. class ReporterRegistry : public IReporterRegistry {
  10040. public:
  10041. ~ReporterRegistry() override;
  10042. IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const override;
  10043. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory );
  10044. void registerListener( IReporterFactoryPtr const& factory );
  10045. FactoryMap const& getFactories() const override;
  10046. Listeners const& getListeners() const override;
  10047. private:
  10048. FactoryMap m_factories;
  10049. Listeners m_listeners;
  10050. };
  10051. }
  10052. // end catch_reporter_registry.h
  10053. // start catch_tag_alias_registry.h
  10054. // start catch_tag_alias.h
  10055. #include <string>
  10056. namespace Catch {
  10057. struct TagAlias {
  10058. TagAlias(std::string const& _tag, SourceLineInfo _lineInfo);
  10059. std::string tag;
  10060. SourceLineInfo lineInfo;
  10061. };
  10062. } // end namespace Catch
  10063. // end catch_tag_alias.h
  10064. #include <map>
  10065. namespace Catch {
  10066. class TagAliasRegistry : public ITagAliasRegistry {
  10067. public:
  10068. ~TagAliasRegistry() override;
  10069. TagAlias const* find( std::string const& alias ) const override;
  10070. std::string expandAliases( std::string const& unexpandedTestSpec ) const override;
  10071. void add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo );
  10072. private:
  10073. std::map<std::string, TagAlias> m_registry;
  10074. };
  10075. } // end namespace Catch
  10076. // end catch_tag_alias_registry.h
  10077. // start catch_startup_exception_registry.h
  10078. #include <vector>
  10079. #include <exception>
  10080. namespace Catch {
  10081. class StartupExceptionRegistry {
  10082. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  10083. public:
  10084. void add(std::exception_ptr const& exception) noexcept;
  10085. std::vector<std::exception_ptr> const& getExceptions() const noexcept;
  10086. private:
  10087. std::vector<std::exception_ptr> m_exceptions;
  10088. #endif
  10089. };
  10090. } // end namespace Catch
  10091. // end catch_startup_exception_registry.h
  10092. // start catch_singletons.hpp
  10093. namespace Catch {
  10094. struct ISingleton {
  10095. virtual ~ISingleton();
  10096. };
  10097. void addSingleton( ISingleton* singleton );
  10098. void cleanupSingletons();
  10099. template<typename SingletonImplT, typename InterfaceT = SingletonImplT, typename MutableInterfaceT = InterfaceT>
  10100. class Singleton : SingletonImplT, public ISingleton {
  10101. static auto getInternal() -> Singleton* {
  10102. static Singleton* s_instance = nullptr;
  10103. if( !s_instance ) {
  10104. s_instance = new Singleton;
  10105. addSingleton( s_instance );
  10106. }
  10107. return s_instance;
  10108. }
  10109. public:
  10110. static auto get() -> InterfaceT const& {
  10111. return *getInternal();
  10112. }
  10113. static auto getMutable() -> MutableInterfaceT& {
  10114. return *getInternal();
  10115. }
  10116. };
  10117. } // namespace Catch
  10118. // end catch_singletons.hpp
  10119. namespace Catch {
  10120. namespace {
  10121. class RegistryHub : public IRegistryHub, public IMutableRegistryHub,
  10122. private NonCopyable {
  10123. public: // IRegistryHub
  10124. RegistryHub() = default;
  10125. IReporterRegistry const& getReporterRegistry() const override {
  10126. return m_reporterRegistry;
  10127. }
  10128. ITestCaseRegistry const& getTestCaseRegistry() const override {
  10129. return m_testCaseRegistry;
  10130. }
  10131. IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const override {
  10132. return m_exceptionTranslatorRegistry;
  10133. }
  10134. ITagAliasRegistry const& getTagAliasRegistry() const override {
  10135. return m_tagAliasRegistry;
  10136. }
  10137. StartupExceptionRegistry const& getStartupExceptionRegistry() const override {
  10138. return m_exceptionRegistry;
  10139. }
  10140. public: // IMutableRegistryHub
  10141. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) override {
  10142. m_reporterRegistry.registerReporter( name, factory );
  10143. }
  10144. void registerListener( IReporterFactoryPtr const& factory ) override {
  10145. m_reporterRegistry.registerListener( factory );
  10146. }
  10147. void registerTest( TestCase const& testInfo ) override {
  10148. m_testCaseRegistry.registerTest( testInfo );
  10149. }
  10150. void registerTranslator( const IExceptionTranslator* translator ) override {
  10151. m_exceptionTranslatorRegistry.registerTranslator( translator );
  10152. }
  10153. void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) override {
  10154. m_tagAliasRegistry.add( alias, tag, lineInfo );
  10155. }
  10156. void registerStartupException() noexcept override {
  10157. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  10158. m_exceptionRegistry.add(std::current_exception());
  10159. #else
  10160. CATCH_INTERNAL_ERROR("Attempted to register active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
  10161. #endif
  10162. }
  10163. IMutableEnumValuesRegistry& getMutableEnumValuesRegistry() override {
  10164. return m_enumValuesRegistry;
  10165. }
  10166. private:
  10167. TestRegistry m_testCaseRegistry;
  10168. ReporterRegistry m_reporterRegistry;
  10169. ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
  10170. TagAliasRegistry m_tagAliasRegistry;
  10171. StartupExceptionRegistry m_exceptionRegistry;
  10172. Detail::EnumValuesRegistry m_enumValuesRegistry;
  10173. };
  10174. }
  10175. using RegistryHubSingleton = Singleton<RegistryHub, IRegistryHub, IMutableRegistryHub>;
  10176. IRegistryHub const& getRegistryHub() {
  10177. return RegistryHubSingleton::get();
  10178. }
  10179. IMutableRegistryHub& getMutableRegistryHub() {
  10180. return RegistryHubSingleton::getMutable();
  10181. }
  10182. void cleanUp() {
  10183. cleanupSingletons();
  10184. cleanUpContext();
  10185. }
  10186. std::string translateActiveException() {
  10187. return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException();
  10188. }
  10189. } // end namespace Catch
  10190. // end catch_registry_hub.cpp
  10191. // start catch_reporter_registry.cpp
  10192. namespace Catch {
  10193. ReporterRegistry::~ReporterRegistry() = default;
  10194. IStreamingReporterPtr ReporterRegistry::create( std::string const& name, IConfigPtr const& config ) const {
  10195. auto it = m_factories.find( name );
  10196. if( it == m_factories.end() )
  10197. return nullptr;
  10198. return it->second->create( ReporterConfig( config ) );
  10199. }
  10200. void ReporterRegistry::registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) {
  10201. m_factories.emplace(name, factory);
  10202. }
  10203. void ReporterRegistry::registerListener( IReporterFactoryPtr const& factory ) {
  10204. m_listeners.push_back( factory );
  10205. }
  10206. IReporterRegistry::FactoryMap const& ReporterRegistry::getFactories() const {
  10207. return m_factories;
  10208. }
  10209. IReporterRegistry::Listeners const& ReporterRegistry::getListeners() const {
  10210. return m_listeners;
  10211. }
  10212. }
  10213. // end catch_reporter_registry.cpp
  10214. // start catch_result_type.cpp
  10215. namespace Catch {
  10216. bool isOk( ResultWas::OfType resultType ) {
  10217. return ( resultType & ResultWas::FailureBit ) == 0;
  10218. }
  10219. bool isJustInfo( int flags ) {
  10220. return flags == ResultWas::Info;
  10221. }
  10222. ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) {
  10223. return static_cast<ResultDisposition::Flags>( static_cast<int>( lhs ) | static_cast<int>( rhs ) );
  10224. }
  10225. bool shouldContinueOnFailure( int flags ) { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; }
  10226. bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; }
  10227. } // end namespace Catch
  10228. // end catch_result_type.cpp
  10229. // start catch_run_context.cpp
  10230. #include <cassert>
  10231. #include <algorithm>
  10232. #include <sstream>
  10233. namespace Catch {
  10234. namespace Generators {
  10235. struct GeneratorTracker : TestCaseTracking::TrackerBase, IGeneratorTracker {
  10236. GeneratorBasePtr m_generator;
  10237. GeneratorTracker( TestCaseTracking::NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  10238. : TrackerBase( nameAndLocation, ctx, parent )
  10239. {}
  10240. ~GeneratorTracker();
  10241. static GeneratorTracker& acquire( TrackerContext& ctx, TestCaseTracking::NameAndLocation const& nameAndLocation ) {
  10242. std::shared_ptr<GeneratorTracker> tracker;
  10243. ITracker& currentTracker = ctx.currentTracker();
  10244. // Under specific circumstances, the generator we want
  10245. // to acquire is also the current tracker. If this is
  10246. // the case, we have to avoid looking through current
  10247. // tracker's children, and instead return the current
  10248. // tracker.
  10249. // A case where this check is important is e.g.
  10250. // for (int i = 0; i < 5; ++i) {
  10251. // int n = GENERATE(1, 2);
  10252. // }
  10253. //
  10254. // without it, the code above creates 5 nested generators.
  10255. if (currentTracker.nameAndLocation() == nameAndLocation) {
  10256. auto thisTracker = currentTracker.parent().findChild(nameAndLocation);
  10257. assert(thisTracker);
  10258. assert(thisTracker->isGeneratorTracker());
  10259. tracker = std::static_pointer_cast<GeneratorTracker>(thisTracker);
  10260. } else if ( TestCaseTracking::ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  10261. assert( childTracker );
  10262. assert( childTracker->isGeneratorTracker() );
  10263. tracker = std::static_pointer_cast<GeneratorTracker>( childTracker );
  10264. } else {
  10265. tracker = std::make_shared<GeneratorTracker>( nameAndLocation, ctx, &currentTracker );
  10266. currentTracker.addChild( tracker );
  10267. }
  10268. if( !tracker->isComplete() ) {
  10269. tracker->open();
  10270. }
  10271. return *tracker;
  10272. }
  10273. // TrackerBase interface
  10274. bool isGeneratorTracker() const override { return true; }
  10275. auto hasGenerator() const -> bool override {
  10276. return !!m_generator;
  10277. }
  10278. void close() override {
  10279. TrackerBase::close();
  10280. // If a generator has a child (it is followed by a section)
  10281. // and none of its children have started, then we must wait
  10282. // until later to start consuming its values.
  10283. // This catches cases where `GENERATE` is placed between two
  10284. // `SECTION`s.
  10285. // **The check for m_children.empty cannot be removed**.
  10286. // doing so would break `GENERATE` _not_ followed by `SECTION`s.
  10287. const bool should_wait_for_child = [&]() {
  10288. // No children -> nobody to wait for
  10289. if ( m_children.empty() ) {
  10290. return false;
  10291. }
  10292. // If at least one child started executing, don't wait
  10293. if ( std::find_if(
  10294. m_children.begin(),
  10295. m_children.end(),
  10296. []( TestCaseTracking::ITrackerPtr tracker ) {
  10297. return tracker->hasStarted();
  10298. } ) != m_children.end() ) {
  10299. return false;
  10300. }
  10301. // No children have started. We need to check if they _can_
  10302. // start, and thus we should wait for them, or they cannot
  10303. // start (due to filters), and we shouldn't wait for them
  10304. auto* parent = m_parent;
  10305. // This is safe: there is always at least one section
  10306. // tracker in a test case tracking tree
  10307. while ( !parent->isSectionTracker() ) {
  10308. parent = &( parent->parent() );
  10309. }
  10310. assert( parent &&
  10311. "Missing root (test case) level section" );
  10312. auto const& parentSection =
  10313. static_cast<SectionTracker&>( *parent );
  10314. auto const& filters = parentSection.getFilters();
  10315. // No filters -> no restrictions on running sections
  10316. if ( filters.empty() ) {
  10317. return true;
  10318. }
  10319. for ( auto const& child : m_children ) {
  10320. if ( child->isSectionTracker() &&
  10321. std::find( filters.begin(),
  10322. filters.end(),
  10323. static_cast<SectionTracker&>( *child )
  10324. .trimmedName() ) !=
  10325. filters.end() ) {
  10326. return true;
  10327. }
  10328. }
  10329. return false;
  10330. }();
  10331. // This check is a bit tricky, because m_generator->next()
  10332. // has a side-effect, where it consumes generator's current
  10333. // value, but we do not want to invoke the side-effect if
  10334. // this generator is still waiting for any child to start.
  10335. if ( should_wait_for_child ||
  10336. ( m_runState == CompletedSuccessfully &&
  10337. m_generator->next() ) ) {
  10338. m_children.clear();
  10339. m_runState = Executing;
  10340. }
  10341. }
  10342. // IGeneratorTracker interface
  10343. auto getGenerator() const -> GeneratorBasePtr const& override {
  10344. return m_generator;
  10345. }
  10346. void setGenerator( GeneratorBasePtr&& generator ) override {
  10347. m_generator = std::move( generator );
  10348. }
  10349. };
  10350. GeneratorTracker::~GeneratorTracker() {}
  10351. }
  10352. RunContext::RunContext(IConfigPtr const& _config, IStreamingReporterPtr&& reporter)
  10353. : m_runInfo(_config->name()),
  10354. m_context(getCurrentMutableContext()),
  10355. m_config(_config),
  10356. m_reporter(std::move(reporter)),
  10357. m_lastAssertionInfo{ StringRef(), SourceLineInfo("",0), StringRef(), ResultDisposition::Normal },
  10358. m_includeSuccessfulResults( m_config->includeSuccessfulResults() || m_reporter->getPreferences().shouldReportAllAssertions )
  10359. {
  10360. m_context.setRunner(this);
  10361. m_context.setConfig(m_config);
  10362. m_context.setResultCapture(this);
  10363. m_reporter->testRunStarting(m_runInfo);
  10364. }
  10365. RunContext::~RunContext() {
  10366. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting()));
  10367. }
  10368. void RunContext::testGroupStarting(std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount) {
  10369. m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount));
  10370. }
  10371. void RunContext::testGroupEnded(std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount) {
  10372. m_reporter->testGroupEnded(TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting()));
  10373. }
  10374. Totals RunContext::runTest(TestCase const& testCase) {
  10375. Totals prevTotals = m_totals;
  10376. std::string redirectedCout;
  10377. std::string redirectedCerr;
  10378. auto const& testInfo = testCase.getTestCaseInfo();
  10379. m_reporter->testCaseStarting(testInfo);
  10380. m_activeTestCase = &testCase;
  10381. ITracker& rootTracker = m_trackerContext.startRun();
  10382. assert(rootTracker.isSectionTracker());
  10383. static_cast<SectionTracker&>(rootTracker).addInitialFilters(m_config->getSectionsToRun());
  10384. do {
  10385. m_trackerContext.startCycle();
  10386. m_testCaseTracker = &SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo));
  10387. runCurrentTest(redirectedCout, redirectedCerr);
  10388. } while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting());
  10389. Totals deltaTotals = m_totals.delta(prevTotals);
  10390. if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) {
  10391. deltaTotals.assertions.failed++;
  10392. deltaTotals.testCases.passed--;
  10393. deltaTotals.testCases.failed++;
  10394. }
  10395. m_totals.testCases += deltaTotals.testCases;
  10396. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  10397. deltaTotals,
  10398. redirectedCout,
  10399. redirectedCerr,
  10400. aborting()));
  10401. m_activeTestCase = nullptr;
  10402. m_testCaseTracker = nullptr;
  10403. return deltaTotals;
  10404. }
  10405. IConfigPtr RunContext::config() const {
  10406. return m_config;
  10407. }
  10408. IStreamingReporter& RunContext::reporter() const {
  10409. return *m_reporter;
  10410. }
  10411. void RunContext::assertionEnded(AssertionResult const & result) {
  10412. if (result.getResultType() == ResultWas::Ok) {
  10413. m_totals.assertions.passed++;
  10414. m_lastAssertionPassed = true;
  10415. } else if (!result.isOk()) {
  10416. m_lastAssertionPassed = false;
  10417. if( m_activeTestCase->getTestCaseInfo().okToFail() )
  10418. m_totals.assertions.failedButOk++;
  10419. else
  10420. m_totals.assertions.failed++;
  10421. }
  10422. else {
  10423. m_lastAssertionPassed = true;
  10424. }
  10425. // We have no use for the return value (whether messages should be cleared), because messages were made scoped
  10426. // and should be let to clear themselves out.
  10427. static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals)));
  10428. if (result.getResultType() != ResultWas::Warning)
  10429. m_messageScopes.clear();
  10430. // Reset working state
  10431. resetAssertionInfo();
  10432. m_lastResult = result;
  10433. }
  10434. void RunContext::resetAssertionInfo() {
  10435. m_lastAssertionInfo.macroName = StringRef();
  10436. m_lastAssertionInfo.capturedExpression = "{Unknown expression after the reported line}"_sr;
  10437. }
  10438. bool RunContext::sectionStarted(SectionInfo const & sectionInfo, Counts & assertions) {
  10439. ITracker& sectionTracker = SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(sectionInfo.name, sectionInfo.lineInfo));
  10440. if (!sectionTracker.isOpen())
  10441. return false;
  10442. m_activeSections.push_back(&sectionTracker);
  10443. m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;
  10444. m_reporter->sectionStarting(sectionInfo);
  10445. assertions = m_totals.assertions;
  10446. return true;
  10447. }
  10448. auto RunContext::acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
  10449. using namespace Generators;
  10450. GeneratorTracker& tracker = GeneratorTracker::acquire(m_trackerContext,
  10451. TestCaseTracking::NameAndLocation( static_cast<std::string>(generatorName), lineInfo ) );
  10452. m_lastAssertionInfo.lineInfo = lineInfo;
  10453. return tracker;
  10454. }
  10455. bool RunContext::testForMissingAssertions(Counts& assertions) {
  10456. if (assertions.total() != 0)
  10457. return false;
  10458. if (!m_config->warnAboutMissingAssertions())
  10459. return false;
  10460. if (m_trackerContext.currentTracker().hasChildren())
  10461. return false;
  10462. m_totals.assertions.failed++;
  10463. assertions.failed++;
  10464. return true;
  10465. }
  10466. void RunContext::sectionEnded(SectionEndInfo const & endInfo) {
  10467. Counts assertions = m_totals.assertions - endInfo.prevAssertions;
  10468. bool missingAssertions = testForMissingAssertions(assertions);
  10469. if (!m_activeSections.empty()) {
  10470. m_activeSections.back()->close();
  10471. m_activeSections.pop_back();
  10472. }
  10473. m_reporter->sectionEnded(SectionStats(endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions));
  10474. m_messages.clear();
  10475. m_messageScopes.clear();
  10476. }
  10477. void RunContext::sectionEndedEarly(SectionEndInfo const & endInfo) {
  10478. if (m_unfinishedSections.empty())
  10479. m_activeSections.back()->fail();
  10480. else
  10481. m_activeSections.back()->close();
  10482. m_activeSections.pop_back();
  10483. m_unfinishedSections.push_back(endInfo);
  10484. }
  10485. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  10486. void RunContext::benchmarkPreparing(std::string const& name) {
  10487. m_reporter->benchmarkPreparing(name);
  10488. }
  10489. void RunContext::benchmarkStarting( BenchmarkInfo const& info ) {
  10490. m_reporter->benchmarkStarting( info );
  10491. }
  10492. void RunContext::benchmarkEnded( BenchmarkStats<> const& stats ) {
  10493. m_reporter->benchmarkEnded( stats );
  10494. }
  10495. void RunContext::benchmarkFailed(std::string const & error) {
  10496. m_reporter->benchmarkFailed(error);
  10497. }
  10498. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  10499. void RunContext::pushScopedMessage(MessageInfo const & message) {
  10500. m_messages.push_back(message);
  10501. }
  10502. void RunContext::popScopedMessage(MessageInfo const & message) {
  10503. m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end());
  10504. }
  10505. void RunContext::emplaceUnscopedMessage( MessageBuilder const& builder ) {
  10506. m_messageScopes.emplace_back( builder );
  10507. }
  10508. std::string RunContext::getCurrentTestName() const {
  10509. return m_activeTestCase
  10510. ? m_activeTestCase->getTestCaseInfo().name
  10511. : std::string();
  10512. }
  10513. const AssertionResult * RunContext::getLastResult() const {
  10514. return &(*m_lastResult);
  10515. }
  10516. void RunContext::exceptionEarlyReported() {
  10517. m_shouldReportUnexpected = false;
  10518. }
  10519. void RunContext::handleFatalErrorCondition( StringRef message ) {
  10520. // First notify reporter that bad things happened
  10521. m_reporter->fatalErrorEncountered(message);
  10522. // Don't rebuild the result -- the stringification itself can cause more fatal errors
  10523. // Instead, fake a result data.
  10524. AssertionResultData tempResult( ResultWas::FatalErrorCondition, { false } );
  10525. tempResult.message = static_cast<std::string>(message);
  10526. AssertionResult result(m_lastAssertionInfo, tempResult);
  10527. assertionEnded(result);
  10528. handleUnfinishedSections();
  10529. // Recreate section for test case (as we will lose the one that was in scope)
  10530. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  10531. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
  10532. Counts assertions;
  10533. assertions.failed = 1;
  10534. SectionStats testCaseSectionStats(testCaseSection, assertions, 0, false);
  10535. m_reporter->sectionEnded(testCaseSectionStats);
  10536. auto const& testInfo = m_activeTestCase->getTestCaseInfo();
  10537. Totals deltaTotals;
  10538. deltaTotals.testCases.failed = 1;
  10539. deltaTotals.assertions.failed = 1;
  10540. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  10541. deltaTotals,
  10542. std::string(),
  10543. std::string(),
  10544. false));
  10545. m_totals.testCases.failed++;
  10546. testGroupEnded(std::string(), m_totals, 1, 1);
  10547. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, false));
  10548. }
  10549. bool RunContext::lastAssertionPassed() {
  10550. return m_lastAssertionPassed;
  10551. }
  10552. void RunContext::assertionPassed() {
  10553. m_lastAssertionPassed = true;
  10554. ++m_totals.assertions.passed;
  10555. resetAssertionInfo();
  10556. m_messageScopes.clear();
  10557. }
  10558. bool RunContext::aborting() const {
  10559. return m_totals.assertions.failed >= static_cast<std::size_t>(m_config->abortAfter());
  10560. }
  10561. void RunContext::runCurrentTest(std::string & redirectedCout, std::string & redirectedCerr) {
  10562. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  10563. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
  10564. m_reporter->sectionStarting(testCaseSection);
  10565. Counts prevAssertions = m_totals.assertions;
  10566. double duration = 0;
  10567. m_shouldReportUnexpected = true;
  10568. m_lastAssertionInfo = { "TEST_CASE"_sr, testCaseInfo.lineInfo, StringRef(), ResultDisposition::Normal };
  10569. seedRng(*m_config);
  10570. Timer timer;
  10571. CATCH_TRY {
  10572. if (m_reporter->getPreferences().shouldRedirectStdOut) {
  10573. #if !defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
  10574. RedirectedStreams redirectedStreams(redirectedCout, redirectedCerr);
  10575. timer.start();
  10576. invokeActiveTestCase();
  10577. #else
  10578. OutputRedirect r(redirectedCout, redirectedCerr);
  10579. timer.start();
  10580. invokeActiveTestCase();
  10581. #endif
  10582. } else {
  10583. timer.start();
  10584. invokeActiveTestCase();
  10585. }
  10586. duration = timer.getElapsedSeconds();
  10587. } CATCH_CATCH_ANON (TestFailureException&) {
  10588. // This just means the test was aborted due to failure
  10589. } CATCH_CATCH_ALL {
  10590. // Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under REQUIRE assertions
  10591. // are reported without translation at the point of origin.
  10592. if( m_shouldReportUnexpected ) {
  10593. AssertionReaction dummyReaction;
  10594. handleUnexpectedInflightException( m_lastAssertionInfo, translateActiveException(), dummyReaction );
  10595. }
  10596. }
  10597. Counts assertions = m_totals.assertions - prevAssertions;
  10598. bool missingAssertions = testForMissingAssertions(assertions);
  10599. m_testCaseTracker->close();
  10600. handleUnfinishedSections();
  10601. m_messages.clear();
  10602. m_messageScopes.clear();
  10603. SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions);
  10604. m_reporter->sectionEnded(testCaseSectionStats);
  10605. }
  10606. void RunContext::invokeActiveTestCase() {
  10607. FatalConditionHandlerGuard _(&m_fatalConditionhandler);
  10608. m_activeTestCase->invoke();
  10609. }
  10610. void RunContext::handleUnfinishedSections() {
  10611. // If sections ended prematurely due to an exception we stored their
  10612. // infos here so we can tear them down outside the unwind process.
  10613. for (auto it = m_unfinishedSections.rbegin(),
  10614. itEnd = m_unfinishedSections.rend();
  10615. it != itEnd;
  10616. ++it)
  10617. sectionEnded(*it);
  10618. m_unfinishedSections.clear();
  10619. }
  10620. void RunContext::handleExpr(
  10621. AssertionInfo const& info,
  10622. ITransientExpression const& expr,
  10623. AssertionReaction& reaction
  10624. ) {
  10625. m_reporter->assertionStarting( info );
  10626. bool negated = isFalseTest( info.resultDisposition );
  10627. bool result = expr.getResult() != negated;
  10628. if( result ) {
  10629. if (!m_includeSuccessfulResults) {
  10630. assertionPassed();
  10631. }
  10632. else {
  10633. reportExpr(info, ResultWas::Ok, &expr, negated);
  10634. }
  10635. }
  10636. else {
  10637. reportExpr(info, ResultWas::ExpressionFailed, &expr, negated );
  10638. populateReaction( reaction );
  10639. }
  10640. }
  10641. void RunContext::reportExpr(
  10642. AssertionInfo const &info,
  10643. ResultWas::OfType resultType,
  10644. ITransientExpression const *expr,
  10645. bool negated ) {
  10646. m_lastAssertionInfo = info;
  10647. AssertionResultData data( resultType, LazyExpression( negated ) );
  10648. AssertionResult assertionResult{ info, data };
  10649. assertionResult.m_resultData.lazyExpression.m_transientExpression = expr;
  10650. assertionEnded( assertionResult );
  10651. }
  10652. void RunContext::handleMessage(
  10653. AssertionInfo const& info,
  10654. ResultWas::OfType resultType,
  10655. StringRef const& message,
  10656. AssertionReaction& reaction
  10657. ) {
  10658. m_reporter->assertionStarting( info );
  10659. m_lastAssertionInfo = info;
  10660. AssertionResultData data( resultType, LazyExpression( false ) );
  10661. data.message = static_cast<std::string>(message);
  10662. AssertionResult assertionResult{ m_lastAssertionInfo, data };
  10663. assertionEnded( assertionResult );
  10664. if( !assertionResult.isOk() )
  10665. populateReaction( reaction );
  10666. }
  10667. void RunContext::handleUnexpectedExceptionNotThrown(
  10668. AssertionInfo const& info,
  10669. AssertionReaction& reaction
  10670. ) {
  10671. handleNonExpr(info, Catch::ResultWas::DidntThrowException, reaction);
  10672. }
  10673. void RunContext::handleUnexpectedInflightException(
  10674. AssertionInfo const& info,
  10675. std::string const& message,
  10676. AssertionReaction& reaction
  10677. ) {
  10678. m_lastAssertionInfo = info;
  10679. AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
  10680. data.message = message;
  10681. AssertionResult assertionResult{ info, data };
  10682. assertionEnded( assertionResult );
  10683. populateReaction( reaction );
  10684. }
  10685. void RunContext::populateReaction( AssertionReaction& reaction ) {
  10686. reaction.shouldDebugBreak = m_config->shouldDebugBreak();
  10687. reaction.shouldThrow = aborting() || (m_lastAssertionInfo.resultDisposition & ResultDisposition::Normal);
  10688. }
  10689. void RunContext::handleIncomplete(
  10690. AssertionInfo const& info
  10691. ) {
  10692. m_lastAssertionInfo = info;
  10693. AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
  10694. data.message = "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE";
  10695. AssertionResult assertionResult{ info, data };
  10696. assertionEnded( assertionResult );
  10697. }
  10698. void RunContext::handleNonExpr(
  10699. AssertionInfo const &info,
  10700. ResultWas::OfType resultType,
  10701. AssertionReaction &reaction
  10702. ) {
  10703. m_lastAssertionInfo = info;
  10704. AssertionResultData data( resultType, LazyExpression( false ) );
  10705. AssertionResult assertionResult{ info, data };
  10706. assertionEnded( assertionResult );
  10707. if( !assertionResult.isOk() )
  10708. populateReaction( reaction );
  10709. }
  10710. IResultCapture& getResultCapture() {
  10711. if (auto* capture = getCurrentContext().getResultCapture())
  10712. return *capture;
  10713. else
  10714. CATCH_INTERNAL_ERROR("No result capture instance");
  10715. }
  10716. void seedRng(IConfig const& config) {
  10717. if (config.rngSeed() != 0) {
  10718. std::srand(config.rngSeed());
  10719. rng().seed(config.rngSeed());
  10720. }
  10721. }
  10722. unsigned int rngSeed() {
  10723. return getCurrentContext().getConfig()->rngSeed();
  10724. }
  10725. }
  10726. // end catch_run_context.cpp
  10727. // start catch_section.cpp
  10728. namespace Catch {
  10729. Section::Section( SectionInfo const& info )
  10730. : m_info( info ),
  10731. m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) )
  10732. {
  10733. m_timer.start();
  10734. }
  10735. Section::~Section() {
  10736. if( m_sectionIncluded ) {
  10737. SectionEndInfo endInfo{ m_info, m_assertions, m_timer.getElapsedSeconds() };
  10738. if( uncaught_exceptions() )
  10739. getResultCapture().sectionEndedEarly( endInfo );
  10740. else
  10741. getResultCapture().sectionEnded( endInfo );
  10742. }
  10743. }
  10744. // This indicates whether the section should be executed or not
  10745. Section::operator bool() const {
  10746. return m_sectionIncluded;
  10747. }
  10748. } // end namespace Catch
  10749. // end catch_section.cpp
  10750. // start catch_section_info.cpp
  10751. namespace Catch {
  10752. SectionInfo::SectionInfo
  10753. ( SourceLineInfo const& _lineInfo,
  10754. std::string const& _name )
  10755. : name( _name ),
  10756. lineInfo( _lineInfo )
  10757. {}
  10758. } // end namespace Catch
  10759. // end catch_section_info.cpp
  10760. // start catch_session.cpp
  10761. // start catch_session.h
  10762. #include <memory>
  10763. namespace Catch {
  10764. class Session : NonCopyable {
  10765. public:
  10766. Session();
  10767. ~Session() override;
  10768. void showHelp() const;
  10769. void libIdentify();
  10770. int applyCommandLine( int argc, char const * const * argv );
  10771. #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)
  10772. int applyCommandLine( int argc, wchar_t const * const * argv );
  10773. #endif
  10774. void useConfigData( ConfigData const& configData );
  10775. template<typename CharT>
  10776. int run(int argc, CharT const * const argv[]) {
  10777. if (m_startupExceptions)
  10778. return 1;
  10779. int returnCode = applyCommandLine(argc, argv);
  10780. if (returnCode == 0)
  10781. returnCode = run();
  10782. return returnCode;
  10783. }
  10784. int run();
  10785. clara::Parser const& cli() const;
  10786. void cli( clara::Parser const& newParser );
  10787. ConfigData& configData();
  10788. Config& config();
  10789. private:
  10790. int runInternal();
  10791. clara::Parser m_cli;
  10792. ConfigData m_configData;
  10793. std::shared_ptr<Config> m_config;
  10794. bool m_startupExceptions = false;
  10795. };
  10796. } // end namespace Catch
  10797. // end catch_session.h
  10798. // start catch_version.h
  10799. #include <iosfwd>
  10800. namespace Catch {
  10801. // Versioning information
  10802. struct Version {
  10803. Version( Version const& ) = delete;
  10804. Version& operator=( Version const& ) = delete;
  10805. Version( unsigned int _majorVersion,
  10806. unsigned int _minorVersion,
  10807. unsigned int _patchNumber,
  10808. char const * const _branchName,
  10809. unsigned int _buildNumber );
  10810. unsigned int const majorVersion;
  10811. unsigned int const minorVersion;
  10812. unsigned int const patchNumber;
  10813. // buildNumber is only used if branchName is not null
  10814. char const * const branchName;
  10815. unsigned int const buildNumber;
  10816. friend std::ostream& operator << ( std::ostream& os, Version const& version );
  10817. };
  10818. Version const& libraryVersion();
  10819. }
  10820. // end catch_version.h
  10821. #include <cstdlib>
  10822. #include <iomanip>
  10823. #include <set>
  10824. #include <iterator>
  10825. namespace Catch {
  10826. namespace {
  10827. const int MaxExitCode = 255;
  10828. IStreamingReporterPtr createReporter(std::string const& reporterName, IConfigPtr const& config) {
  10829. auto reporter = Catch::getRegistryHub().getReporterRegistry().create(reporterName, config);
  10830. CATCH_ENFORCE(reporter, "No reporter registered with name: '" << reporterName << "'");
  10831. return reporter;
  10832. }
  10833. IStreamingReporterPtr makeReporter(std::shared_ptr<Config> const& config) {
  10834. if (Catch::getRegistryHub().getReporterRegistry().getListeners().empty()) {
  10835. return createReporter(config->getReporterName(), config);
  10836. }
  10837. // On older platforms, returning std::unique_ptr<ListeningReporter>
  10838. // when the return type is std::unique_ptr<IStreamingReporter>
  10839. // doesn't compile without a std::move call. However, this causes
  10840. // a warning on newer platforms. Thus, we have to work around
  10841. // it a bit and downcast the pointer manually.
  10842. auto ret = std::unique_ptr<IStreamingReporter>(new ListeningReporter);
  10843. auto& multi = static_cast<ListeningReporter&>(*ret);
  10844. auto const& listeners = Catch::getRegistryHub().getReporterRegistry().getListeners();
  10845. for (auto const& listener : listeners) {
  10846. multi.addListener(listener->create(Catch::ReporterConfig(config)));
  10847. }
  10848. multi.addReporter(createReporter(config->getReporterName(), config));
  10849. return ret;
  10850. }
  10851. class TestGroup {
  10852. public:
  10853. explicit TestGroup(std::shared_ptr<Config> const& config)
  10854. : m_config{config}
  10855. , m_context{config, makeReporter(config)}
  10856. {
  10857. auto const& allTestCases = getAllTestCasesSorted(*m_config);
  10858. m_matches = m_config->testSpec().matchesByFilter(allTestCases, *m_config);
  10859. auto const& invalidArgs = m_config->testSpec().getInvalidArgs();
  10860. if (m_matches.empty() && invalidArgs.empty()) {
  10861. for (auto const& test : allTestCases)
  10862. if (!test.isHidden())
  10863. m_tests.emplace(&test);
  10864. } else {
  10865. for (auto const& match : m_matches)
  10866. m_tests.insert(match.tests.begin(), match.tests.end());
  10867. }
  10868. }
  10869. Totals execute() {
  10870. auto const& invalidArgs = m_config->testSpec().getInvalidArgs();
  10871. Totals totals;
  10872. m_context.testGroupStarting(m_config->name(), 1, 1);
  10873. for (auto const& testCase : m_tests) {
  10874. if (!m_context.aborting())
  10875. totals += m_context.runTest(*testCase);
  10876. else
  10877. m_context.reporter().skipTest(*testCase);
  10878. }
  10879. for (auto const& match : m_matches) {
  10880. if (match.tests.empty()) {
  10881. m_context.reporter().noMatchingTestCases(match.name);
  10882. totals.error = -1;
  10883. }
  10884. }
  10885. if (!invalidArgs.empty()) {
  10886. for (auto const& invalidArg: invalidArgs)
  10887. m_context.reporter().reportInvalidArguments(invalidArg);
  10888. }
  10889. m_context.testGroupEnded(m_config->name(), totals, 1, 1);
  10890. return totals;
  10891. }
  10892. private:
  10893. using Tests = std::set<TestCase const*>;
  10894. std::shared_ptr<Config> m_config;
  10895. RunContext m_context;
  10896. Tests m_tests;
  10897. TestSpec::Matches m_matches;
  10898. };
  10899. void applyFilenamesAsTags(Catch::IConfig const& config) {
  10900. auto& tests = const_cast<std::vector<TestCase>&>(getAllTestCasesSorted(config));
  10901. for (auto& testCase : tests) {
  10902. auto tags = testCase.tags;
  10903. std::string filename = testCase.lineInfo.file;
  10904. auto lastSlash = filename.find_last_of("\\/");
  10905. if (lastSlash != std::string::npos) {
  10906. filename.erase(0, lastSlash);
  10907. filename[0] = '#';
  10908. }
  10909. auto lastDot = filename.find_last_of('.');
  10910. if (lastDot != std::string::npos) {
  10911. filename.erase(lastDot);
  10912. }
  10913. tags.push_back(std::move(filename));
  10914. setTags(testCase, tags);
  10915. }
  10916. }
  10917. } // anon namespace
  10918. Session::Session() {
  10919. static bool alreadyInstantiated = false;
  10920. if( alreadyInstantiated ) {
  10921. CATCH_TRY { CATCH_INTERNAL_ERROR( "Only one instance of Catch::Session can ever be used" ); }
  10922. CATCH_CATCH_ALL { getMutableRegistryHub().registerStartupException(); }
  10923. }
  10924. // There cannot be exceptions at startup in no-exception mode.
  10925. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  10926. const auto& exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions();
  10927. if ( !exceptions.empty() ) {
  10928. config();
  10929. getCurrentMutableContext().setConfig(m_config);
  10930. m_startupExceptions = true;
  10931. Colour colourGuard( Colour::Red );
  10932. Catch::cerr() << "Errors occurred during startup!" << '\n';
  10933. // iterate over all exceptions and notify user
  10934. for ( const auto& ex_ptr : exceptions ) {
  10935. try {
  10936. std::rethrow_exception(ex_ptr);
  10937. } catch ( std::exception const& ex ) {
  10938. Catch::cerr() << Column( ex.what() ).indent(2) << '\n';
  10939. }
  10940. }
  10941. }
  10942. #endif
  10943. alreadyInstantiated = true;
  10944. m_cli = makeCommandLineParser( m_configData );
  10945. }
  10946. Session::~Session() {
  10947. Catch::cleanUp();
  10948. }
  10949. void Session::showHelp() const {
  10950. Catch::cout()
  10951. << "\nCatch v" << libraryVersion() << "\n"
  10952. << m_cli << std::endl
  10953. << "For more detailed usage please see the project docs\n" << std::endl;
  10954. }
  10955. void Session::libIdentify() {
  10956. Catch::cout()
  10957. << std::left << std::setw(16) << "description: " << "A Catch2 test executable\n"
  10958. << std::left << std::setw(16) << "category: " << "testframework\n"
  10959. << std::left << std::setw(16) << "framework: " << "Catch Test\n"
  10960. << std::left << std::setw(16) << "version: " << libraryVersion() << std::endl;
  10961. }
  10962. int Session::applyCommandLine( int argc, char const * const * argv ) {
  10963. if( m_startupExceptions )
  10964. return 1;
  10965. auto result = m_cli.parse( clara::Args( argc, argv ) );
  10966. if( !result ) {
  10967. config();
  10968. getCurrentMutableContext().setConfig(m_config);
  10969. Catch::cerr()
  10970. << Colour( Colour::Red )
  10971. << "\nError(s) in input:\n"
  10972. << Column( result.errorMessage() ).indent( 2 )
  10973. << "\n\n";
  10974. Catch::cerr() << "Run with -? for usage\n" << std::endl;
  10975. return MaxExitCode;
  10976. }
  10977. if( m_configData.showHelp )
  10978. showHelp();
  10979. if( m_configData.libIdentify )
  10980. libIdentify();
  10981. m_config.reset();
  10982. return 0;
  10983. }
  10984. #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)
  10985. int Session::applyCommandLine( int argc, wchar_t const * const * argv ) {
  10986. char **utf8Argv = new char *[ argc ];
  10987. for ( int i = 0; i < argc; ++i ) {
  10988. int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, nullptr, 0, nullptr, nullptr );
  10989. utf8Argv[ i ] = new char[ bufSize ];
  10990. WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, nullptr, nullptr );
  10991. }
  10992. int returnCode = applyCommandLine( argc, utf8Argv );
  10993. for ( int i = 0; i < argc; ++i )
  10994. delete [] utf8Argv[ i ];
  10995. delete [] utf8Argv;
  10996. return returnCode;
  10997. }
  10998. #endif
  10999. void Session::useConfigData( ConfigData const& configData ) {
  11000. m_configData = configData;
  11001. m_config.reset();
  11002. }
  11003. int Session::run() {
  11004. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeStart ) != 0 ) {
  11005. Catch::cout() << "...waiting for enter/ return before starting" << std::endl;
  11006. static_cast<void>(std::getchar());
  11007. }
  11008. int exitCode = runInternal();
  11009. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeExit ) != 0 ) {
  11010. Catch::cout() << "...waiting for enter/ return before exiting, with code: " << exitCode << std::endl;
  11011. static_cast<void>(std::getchar());
  11012. }
  11013. return exitCode;
  11014. }
  11015. clara::Parser const& Session::cli() const {
  11016. return m_cli;
  11017. }
  11018. void Session::cli( clara::Parser const& newParser ) {
  11019. m_cli = newParser;
  11020. }
  11021. ConfigData& Session::configData() {
  11022. return m_configData;
  11023. }
  11024. Config& Session::config() {
  11025. if( !m_config )
  11026. m_config = std::make_shared<Config>( m_configData );
  11027. return *m_config;
  11028. }
  11029. int Session::runInternal() {
  11030. if( m_startupExceptions )
  11031. return 1;
  11032. if (m_configData.showHelp || m_configData.libIdentify) {
  11033. return 0;
  11034. }
  11035. CATCH_TRY {
  11036. config(); // Force config to be constructed
  11037. seedRng( *m_config );
  11038. if( m_configData.filenamesAsTags )
  11039. applyFilenamesAsTags( *m_config );
  11040. // Handle list request
  11041. if( Option<std::size_t> listed = list( m_config ) )
  11042. return static_cast<int>( *listed );
  11043. TestGroup tests { m_config };
  11044. auto const totals = tests.execute();
  11045. if( m_config->warnAboutNoTests() && totals.error == -1 )
  11046. return 2;
  11047. // Note that on unices only the lower 8 bits are usually used, clamping
  11048. // the return value to 255 prevents false negative when some multiple
  11049. // of 256 tests has failed
  11050. return (std::min) (MaxExitCode, (std::max) (totals.error, static_cast<int>(totals.assertions.failed)));
  11051. }
  11052. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  11053. catch( std::exception& ex ) {
  11054. Catch::cerr() << ex.what() << std::endl;
  11055. return MaxExitCode;
  11056. }
  11057. #endif
  11058. }
  11059. } // end namespace Catch
  11060. // end catch_session.cpp
  11061. // start catch_singletons.cpp
  11062. #include <vector>
  11063. namespace Catch {
  11064. namespace {
  11065. static auto getSingletons() -> std::vector<ISingleton*>*& {
  11066. static std::vector<ISingleton*>* g_singletons = nullptr;
  11067. if( !g_singletons )
  11068. g_singletons = new std::vector<ISingleton*>();
  11069. return g_singletons;
  11070. }
  11071. }
  11072. ISingleton::~ISingleton() {}
  11073. void addSingleton(ISingleton* singleton ) {
  11074. getSingletons()->push_back( singleton );
  11075. }
  11076. void cleanupSingletons() {
  11077. auto& singletons = getSingletons();
  11078. for( auto singleton : *singletons )
  11079. delete singleton;
  11080. delete singletons;
  11081. singletons = nullptr;
  11082. }
  11083. } // namespace Catch
  11084. // end catch_singletons.cpp
  11085. // start catch_startup_exception_registry.cpp
  11086. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  11087. namespace Catch {
  11088. void StartupExceptionRegistry::add( std::exception_ptr const& exception ) noexcept {
  11089. CATCH_TRY {
  11090. m_exceptions.push_back(exception);
  11091. } CATCH_CATCH_ALL {
  11092. // If we run out of memory during start-up there's really not a lot more we can do about it
  11093. std::terminate();
  11094. }
  11095. }
  11096. std::vector<std::exception_ptr> const& StartupExceptionRegistry::getExceptions() const noexcept {
  11097. return m_exceptions;
  11098. }
  11099. } // end namespace Catch
  11100. #endif
  11101. // end catch_startup_exception_registry.cpp
  11102. // start catch_stream.cpp
  11103. #include <cstdio>
  11104. #include <iostream>
  11105. #include <fstream>
  11106. #include <sstream>
  11107. #include <vector>
  11108. #include <memory>
  11109. namespace Catch {
  11110. Catch::IStream::~IStream() = default;
  11111. namespace Detail { namespace {
  11112. template<typename WriterF, std::size_t bufferSize=256>
  11113. class StreamBufImpl : public std::streambuf {
  11114. char data[bufferSize];
  11115. WriterF m_writer;
  11116. public:
  11117. StreamBufImpl() {
  11118. setp( data, data + sizeof(data) );
  11119. }
  11120. ~StreamBufImpl() noexcept {
  11121. StreamBufImpl::sync();
  11122. }
  11123. private:
  11124. int overflow( int c ) override {
  11125. sync();
  11126. if( c != EOF ) {
  11127. if( pbase() == epptr() )
  11128. m_writer( std::string( 1, static_cast<char>( c ) ) );
  11129. else
  11130. sputc( static_cast<char>( c ) );
  11131. }
  11132. return 0;
  11133. }
  11134. int sync() override {
  11135. if( pbase() != pptr() ) {
  11136. m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) );
  11137. setp( pbase(), epptr() );
  11138. }
  11139. return 0;
  11140. }
  11141. };
  11142. ///////////////////////////////////////////////////////////////////////////
  11143. struct OutputDebugWriter {
  11144. void operator()( std::string const&str ) {
  11145. writeToDebugConsole( str );
  11146. }
  11147. };
  11148. ///////////////////////////////////////////////////////////////////////////
  11149. class FileStream : public IStream {
  11150. mutable std::ofstream m_ofs;
  11151. public:
  11152. FileStream( StringRef filename ) {
  11153. m_ofs.open( filename.c_str() );
  11154. CATCH_ENFORCE( !m_ofs.fail(), "Unable to open file: '" << filename << "'" );
  11155. }
  11156. ~FileStream() override = default;
  11157. public: // IStream
  11158. std::ostream& stream() const override {
  11159. return m_ofs;
  11160. }
  11161. };
  11162. ///////////////////////////////////////////////////////////////////////////
  11163. class CoutStream : public IStream {
  11164. mutable std::ostream m_os;
  11165. public:
  11166. // Store the streambuf from cout up-front because
  11167. // cout may get redirected when running tests
  11168. CoutStream() : m_os( Catch::cout().rdbuf() ) {}
  11169. ~CoutStream() override = default;
  11170. public: // IStream
  11171. std::ostream& stream() const override { return m_os; }
  11172. };
  11173. ///////////////////////////////////////////////////////////////////////////
  11174. class DebugOutStream : public IStream {
  11175. std::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf;
  11176. mutable std::ostream m_os;
  11177. public:
  11178. DebugOutStream()
  11179. : m_streamBuf( new StreamBufImpl<OutputDebugWriter>() ),
  11180. m_os( m_streamBuf.get() )
  11181. {}
  11182. ~DebugOutStream() override = default;
  11183. public: // IStream
  11184. std::ostream& stream() const override { return m_os; }
  11185. };
  11186. }} // namespace anon::detail
  11187. ///////////////////////////////////////////////////////////////////////////
  11188. auto makeStream( StringRef const &filename ) -> IStream const* {
  11189. if( filename.empty() )
  11190. return new Detail::CoutStream();
  11191. else if( filename[0] == '%' ) {
  11192. if( filename == "%debug" )
  11193. return new Detail::DebugOutStream();
  11194. else
  11195. CATCH_ERROR( "Unrecognised stream: '" << filename << "'" );
  11196. }
  11197. else
  11198. return new Detail::FileStream( filename );
  11199. }
  11200. // This class encapsulates the idea of a pool of ostringstreams that can be reused.
  11201. struct StringStreams {
  11202. std::vector<std::unique_ptr<std::ostringstream>> m_streams;
  11203. std::vector<std::size_t> m_unused;
  11204. std::ostringstream m_referenceStream; // Used for copy state/ flags from
  11205. auto add() -> std::size_t {
  11206. if( m_unused.empty() ) {
  11207. m_streams.push_back( std::unique_ptr<std::ostringstream>( new std::ostringstream ) );
  11208. return m_streams.size()-1;
  11209. }
  11210. else {
  11211. auto index = m_unused.back();
  11212. m_unused.pop_back();
  11213. return index;
  11214. }
  11215. }
  11216. void release( std::size_t index ) {
  11217. m_streams[index]->copyfmt( m_referenceStream ); // Restore initial flags and other state
  11218. m_unused.push_back(index);
  11219. }
  11220. };
  11221. ReusableStringStream::ReusableStringStream()
  11222. : m_index( Singleton<StringStreams>::getMutable().add() ),
  11223. m_oss( Singleton<StringStreams>::getMutable().m_streams[m_index].get() )
  11224. {}
  11225. ReusableStringStream::~ReusableStringStream() {
  11226. static_cast<std::ostringstream*>( m_oss )->str("");
  11227. m_oss->clear();
  11228. Singleton<StringStreams>::getMutable().release( m_index );
  11229. }
  11230. auto ReusableStringStream::str() const -> std::string {
  11231. return static_cast<std::ostringstream*>( m_oss )->str();
  11232. }
  11233. ///////////////////////////////////////////////////////////////////////////
  11234. #ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions
  11235. std::ostream& cout() { return std::cout; }
  11236. std::ostream& cerr() { return std::cerr; }
  11237. std::ostream& clog() { return std::clog; }
  11238. #endif
  11239. }
  11240. // end catch_stream.cpp
  11241. // start catch_string_manip.cpp
  11242. #include <algorithm>
  11243. #include <ostream>
  11244. #include <cstring>
  11245. #include <cctype>
  11246. #include <vector>
  11247. namespace Catch {
  11248. namespace {
  11249. char toLowerCh(char c) {
  11250. return static_cast<char>( std::tolower( static_cast<unsigned char>(c) ) );
  11251. }
  11252. }
  11253. bool startsWith( std::string const& s, std::string const& prefix ) {
  11254. return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
  11255. }
  11256. bool startsWith( std::string const& s, char prefix ) {
  11257. return !s.empty() && s[0] == prefix;
  11258. }
  11259. bool endsWith( std::string const& s, std::string const& suffix ) {
  11260. return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
  11261. }
  11262. bool endsWith( std::string const& s, char suffix ) {
  11263. return !s.empty() && s[s.size()-1] == suffix;
  11264. }
  11265. bool contains( std::string const& s, std::string const& infix ) {
  11266. return s.find( infix ) != std::string::npos;
  11267. }
  11268. void toLowerInPlace( std::string& s ) {
  11269. std::transform( s.begin(), s.end(), s.begin(), toLowerCh );
  11270. }
  11271. std::string toLower( std::string const& s ) {
  11272. std::string lc = s;
  11273. toLowerInPlace( lc );
  11274. return lc;
  11275. }
  11276. std::string trim( std::string const& str ) {
  11277. static char const* whitespaceChars = "\n\r\t ";
  11278. std::string::size_type start = str.find_first_not_of( whitespaceChars );
  11279. std::string::size_type end = str.find_last_not_of( whitespaceChars );
  11280. return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string();
  11281. }
  11282. StringRef trim(StringRef ref) {
  11283. const auto is_ws = [](char c) {
  11284. return c == ' ' || c == '\t' || c == '\n' || c == '\r';
  11285. };
  11286. size_t real_begin = 0;
  11287. while (real_begin < ref.size() && is_ws(ref[real_begin])) { ++real_begin; }
  11288. size_t real_end = ref.size();
  11289. while (real_end > real_begin && is_ws(ref[real_end - 1])) { --real_end; }
  11290. return ref.substr(real_begin, real_end - real_begin);
  11291. }
  11292. bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) {
  11293. bool replaced = false;
  11294. std::size_t i = str.find( replaceThis );
  11295. while( i != std::string::npos ) {
  11296. replaced = true;
  11297. str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() );
  11298. if( i < str.size()-withThis.size() )
  11299. i = str.find( replaceThis, i+withThis.size() );
  11300. else
  11301. i = std::string::npos;
  11302. }
  11303. return replaced;
  11304. }
  11305. std::vector<StringRef> splitStringRef( StringRef str, char delimiter ) {
  11306. std::vector<StringRef> subStrings;
  11307. std::size_t start = 0;
  11308. for(std::size_t pos = 0; pos < str.size(); ++pos ) {
  11309. if( str[pos] == delimiter ) {
  11310. if( pos - start > 1 )
  11311. subStrings.push_back( str.substr( start, pos-start ) );
  11312. start = pos+1;
  11313. }
  11314. }
  11315. if( start < str.size() )
  11316. subStrings.push_back( str.substr( start, str.size()-start ) );
  11317. return subStrings;
  11318. }
  11319. pluralise::pluralise( std::size_t count, std::string const& label )
  11320. : m_count( count ),
  11321. m_label( label )
  11322. {}
  11323. std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) {
  11324. os << pluraliser.m_count << ' ' << pluraliser.m_label;
  11325. if( pluraliser.m_count != 1 )
  11326. os << 's';
  11327. return os;
  11328. }
  11329. }
  11330. // end catch_string_manip.cpp
  11331. // start catch_stringref.cpp
  11332. #include <algorithm>
  11333. #include <ostream>
  11334. #include <cstring>
  11335. #include <cstdint>
  11336. namespace Catch {
  11337. StringRef::StringRef( char const* rawChars ) noexcept
  11338. : StringRef( rawChars, static_cast<StringRef::size_type>(std::strlen(rawChars) ) )
  11339. {}
  11340. auto StringRef::c_str() const -> char const* {
  11341. CATCH_ENFORCE(isNullTerminated(), "Called StringRef::c_str() on a non-null-terminated instance");
  11342. return m_start;
  11343. }
  11344. auto StringRef::data() const noexcept -> char const* {
  11345. return m_start;
  11346. }
  11347. auto StringRef::substr( size_type start, size_type size ) const noexcept -> StringRef {
  11348. if (start < m_size) {
  11349. return StringRef(m_start + start, (std::min)(m_size - start, size));
  11350. } else {
  11351. return StringRef();
  11352. }
  11353. }
  11354. auto StringRef::operator == ( StringRef const& other ) const noexcept -> bool {
  11355. return m_size == other.m_size
  11356. && (std::memcmp( m_start, other.m_start, m_size ) == 0);
  11357. }
  11358. auto operator << ( std::ostream& os, StringRef const& str ) -> std::ostream& {
  11359. return os.write(str.data(), str.size());
  11360. }
  11361. auto operator+=( std::string& lhs, StringRef const& rhs ) -> std::string& {
  11362. lhs.append(rhs.data(), rhs.size());
  11363. return lhs;
  11364. }
  11365. } // namespace Catch
  11366. // end catch_stringref.cpp
  11367. // start catch_tag_alias.cpp
  11368. namespace Catch {
  11369. TagAlias::TagAlias(std::string const & _tag, SourceLineInfo _lineInfo): tag(_tag), lineInfo(_lineInfo) {}
  11370. }
  11371. // end catch_tag_alias.cpp
  11372. // start catch_tag_alias_autoregistrar.cpp
  11373. namespace Catch {
  11374. RegistrarForTagAliases::RegistrarForTagAliases(char const* alias, char const* tag, SourceLineInfo const& lineInfo) {
  11375. CATCH_TRY {
  11376. getMutableRegistryHub().registerTagAlias(alias, tag, lineInfo);
  11377. } CATCH_CATCH_ALL {
  11378. // Do not throw when constructing global objects, instead register the exception to be processed later
  11379. getMutableRegistryHub().registerStartupException();
  11380. }
  11381. }
  11382. }
  11383. // end catch_tag_alias_autoregistrar.cpp
  11384. // start catch_tag_alias_registry.cpp
  11385. #include <sstream>
  11386. namespace Catch {
  11387. TagAliasRegistry::~TagAliasRegistry() {}
  11388. TagAlias const* TagAliasRegistry::find( std::string const& alias ) const {
  11389. auto it = m_registry.find( alias );
  11390. if( it != m_registry.end() )
  11391. return &(it->second);
  11392. else
  11393. return nullptr;
  11394. }
  11395. std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const {
  11396. std::string expandedTestSpec = unexpandedTestSpec;
  11397. for( auto const& registryKvp : m_registry ) {
  11398. std::size_t pos = expandedTestSpec.find( registryKvp.first );
  11399. if( pos != std::string::npos ) {
  11400. expandedTestSpec = expandedTestSpec.substr( 0, pos ) +
  11401. registryKvp.second.tag +
  11402. expandedTestSpec.substr( pos + registryKvp.first.size() );
  11403. }
  11404. }
  11405. return expandedTestSpec;
  11406. }
  11407. void TagAliasRegistry::add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) {
  11408. CATCH_ENFORCE( startsWith(alias, "[@") && endsWith(alias, ']'),
  11409. "error: tag alias, '" << alias << "' is not of the form [@alias name].\n" << lineInfo );
  11410. CATCH_ENFORCE( m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second,
  11411. "error: tag alias, '" << alias << "' already registered.\n"
  11412. << "\tFirst seen at: " << find(alias)->lineInfo << "\n"
  11413. << "\tRedefined at: " << lineInfo );
  11414. }
  11415. ITagAliasRegistry::~ITagAliasRegistry() {}
  11416. ITagAliasRegistry const& ITagAliasRegistry::get() {
  11417. return getRegistryHub().getTagAliasRegistry();
  11418. }
  11419. } // end namespace Catch
  11420. // end catch_tag_alias_registry.cpp
  11421. // start catch_test_case_info.cpp
  11422. #include <cctype>
  11423. #include <exception>
  11424. #include <algorithm>
  11425. #include <sstream>
  11426. namespace Catch {
  11427. namespace {
  11428. TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) {
  11429. if( startsWith( tag, '.' ) ||
  11430. tag == "!hide" )
  11431. return TestCaseInfo::IsHidden;
  11432. else if( tag == "!throws" )
  11433. return TestCaseInfo::Throws;
  11434. else if( tag == "!shouldfail" )
  11435. return TestCaseInfo::ShouldFail;
  11436. else if( tag == "!mayfail" )
  11437. return TestCaseInfo::MayFail;
  11438. else if( tag == "!nonportable" )
  11439. return TestCaseInfo::NonPortable;
  11440. else if( tag == "!benchmark" )
  11441. return static_cast<TestCaseInfo::SpecialProperties>( TestCaseInfo::Benchmark | TestCaseInfo::IsHidden );
  11442. else
  11443. return TestCaseInfo::None;
  11444. }
  11445. bool isReservedTag( std::string const& tag ) {
  11446. return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !std::isalnum( static_cast<unsigned char>(tag[0]) );
  11447. }
  11448. void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) {
  11449. CATCH_ENFORCE( !isReservedTag(tag),
  11450. "Tag name: [" << tag << "] is not allowed.\n"
  11451. << "Tag names starting with non alphanumeric characters are reserved\n"
  11452. << _lineInfo );
  11453. }
  11454. }
  11455. TestCase makeTestCase( ITestInvoker* _testCase,
  11456. std::string const& _className,
  11457. NameAndTags const& nameAndTags,
  11458. SourceLineInfo const& _lineInfo )
  11459. {
  11460. bool isHidden = false;
  11461. // Parse out tags
  11462. std::vector<std::string> tags;
  11463. std::string desc, tag;
  11464. bool inTag = false;
  11465. for (char c : nameAndTags.tags) {
  11466. if( !inTag ) {
  11467. if( c == '[' )
  11468. inTag = true;
  11469. else
  11470. desc += c;
  11471. }
  11472. else {
  11473. if( c == ']' ) {
  11474. TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag );
  11475. if( ( prop & TestCaseInfo::IsHidden ) != 0 )
  11476. isHidden = true;
  11477. else if( prop == TestCaseInfo::None )
  11478. enforceNotReservedTag( tag, _lineInfo );
  11479. // Merged hide tags like `[.approvals]` should be added as
  11480. // `[.][approvals]`. The `[.]` is added at later point, so
  11481. // we only strip the prefix
  11482. if (startsWith(tag, '.') && tag.size() > 1) {
  11483. tag.erase(0, 1);
  11484. }
  11485. tags.push_back( tag );
  11486. tag.clear();
  11487. inTag = false;
  11488. }
  11489. else
  11490. tag += c;
  11491. }
  11492. }
  11493. if( isHidden ) {
  11494. // Add all "hidden" tags to make them behave identically
  11495. tags.insert( tags.end(), { ".", "!hide" } );
  11496. }
  11497. TestCaseInfo info( static_cast<std::string>(nameAndTags.name), _className, desc, tags, _lineInfo );
  11498. return TestCase( _testCase, std::move(info) );
  11499. }
  11500. void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags ) {
  11501. std::sort(begin(tags), end(tags));
  11502. tags.erase(std::unique(begin(tags), end(tags)), end(tags));
  11503. testCaseInfo.lcaseTags.clear();
  11504. for( auto const& tag : tags ) {
  11505. std::string lcaseTag = toLower( tag );
  11506. testCaseInfo.properties = static_cast<TestCaseInfo::SpecialProperties>( testCaseInfo.properties | parseSpecialTag( lcaseTag ) );
  11507. testCaseInfo.lcaseTags.push_back( lcaseTag );
  11508. }
  11509. testCaseInfo.tags = std::move(tags);
  11510. }
  11511. TestCaseInfo::TestCaseInfo( std::string const& _name,
  11512. std::string const& _className,
  11513. std::string const& _description,
  11514. std::vector<std::string> const& _tags,
  11515. SourceLineInfo const& _lineInfo )
  11516. : name( _name ),
  11517. className( _className ),
  11518. description( _description ),
  11519. lineInfo( _lineInfo ),
  11520. properties( None )
  11521. {
  11522. setTags( *this, _tags );
  11523. }
  11524. bool TestCaseInfo::isHidden() const {
  11525. return ( properties & IsHidden ) != 0;
  11526. }
  11527. bool TestCaseInfo::throws() const {
  11528. return ( properties & Throws ) != 0;
  11529. }
  11530. bool TestCaseInfo::okToFail() const {
  11531. return ( properties & (ShouldFail | MayFail ) ) != 0;
  11532. }
  11533. bool TestCaseInfo::expectedToFail() const {
  11534. return ( properties & (ShouldFail ) ) != 0;
  11535. }
  11536. std::string TestCaseInfo::tagsAsString() const {
  11537. std::string ret;
  11538. // '[' and ']' per tag
  11539. std::size_t full_size = 2 * tags.size();
  11540. for (const auto& tag : tags) {
  11541. full_size += tag.size();
  11542. }
  11543. ret.reserve(full_size);
  11544. for (const auto& tag : tags) {
  11545. ret.push_back('[');
  11546. ret.append(tag);
  11547. ret.push_back(']');
  11548. }
  11549. return ret;
  11550. }
  11551. TestCase::TestCase( ITestInvoker* testCase, TestCaseInfo&& info ) : TestCaseInfo( std::move(info) ), test( testCase ) {}
  11552. TestCase TestCase::withName( std::string const& _newName ) const {
  11553. TestCase other( *this );
  11554. other.name = _newName;
  11555. return other;
  11556. }
  11557. void TestCase::invoke() const {
  11558. test->invoke();
  11559. }
  11560. bool TestCase::operator == ( TestCase const& other ) const {
  11561. return test.get() == other.test.get() &&
  11562. name == other.name &&
  11563. className == other.className;
  11564. }
  11565. bool TestCase::operator < ( TestCase const& other ) const {
  11566. return name < other.name;
  11567. }
  11568. TestCaseInfo const& TestCase::getTestCaseInfo() const
  11569. {
  11570. return *this;
  11571. }
  11572. } // end namespace Catch
  11573. // end catch_test_case_info.cpp
  11574. // start catch_test_case_registry_impl.cpp
  11575. #include <algorithm>
  11576. #include <sstream>
  11577. namespace Catch {
  11578. namespace {
  11579. struct TestHasher {
  11580. using hash_t = uint64_t;
  11581. explicit TestHasher( hash_t hashSuffix ):
  11582. m_hashSuffix{ hashSuffix } {}
  11583. uint32_t operator()( TestCase const& t ) const {
  11584. // FNV-1a hash with multiplication fold.
  11585. const hash_t prime = 1099511628211u;
  11586. hash_t hash = 14695981039346656037u;
  11587. for ( const char c : t.name ) {
  11588. hash ^= c;
  11589. hash *= prime;
  11590. }
  11591. hash ^= m_hashSuffix;
  11592. hash *= prime;
  11593. const uint32_t low{ static_cast<uint32_t>( hash ) };
  11594. const uint32_t high{ static_cast<uint32_t>( hash >> 32 ) };
  11595. return low * high;
  11596. }
  11597. private:
  11598. hash_t m_hashSuffix;
  11599. };
  11600. } // end unnamed namespace
  11601. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases ) {
  11602. switch( config.runOrder() ) {
  11603. case RunTests::InDeclarationOrder:
  11604. // already in declaration order
  11605. break;
  11606. case RunTests::InLexicographicalOrder: {
  11607. std::vector<TestCase> sorted = unsortedTestCases;
  11608. std::sort( sorted.begin(), sorted.end() );
  11609. return sorted;
  11610. }
  11611. case RunTests::InRandomOrder: {
  11612. seedRng( config );
  11613. TestHasher h{ config.rngSeed() };
  11614. using hashedTest = std::pair<TestHasher::hash_t, TestCase const*>;
  11615. std::vector<hashedTest> indexed_tests;
  11616. indexed_tests.reserve( unsortedTestCases.size() );
  11617. for (auto const& testCase : unsortedTestCases) {
  11618. indexed_tests.emplace_back(h(testCase), &testCase);
  11619. }
  11620. std::sort(indexed_tests.begin(), indexed_tests.end(),
  11621. [](hashedTest const& lhs, hashedTest const& rhs) {
  11622. if (lhs.first == rhs.first) {
  11623. return lhs.second->name < rhs.second->name;
  11624. }
  11625. return lhs.first < rhs.first;
  11626. });
  11627. std::vector<TestCase> sorted;
  11628. sorted.reserve( indexed_tests.size() );
  11629. for (auto const& hashed : indexed_tests) {
  11630. sorted.emplace_back(*hashed.second);
  11631. }
  11632. return sorted;
  11633. }
  11634. }
  11635. return unsortedTestCases;
  11636. }
  11637. bool isThrowSafe( TestCase const& testCase, IConfig const& config ) {
  11638. return !testCase.throws() || config.allowThrows();
  11639. }
  11640. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ) {
  11641. return testSpec.matches( testCase ) && isThrowSafe( testCase, config );
  11642. }
  11643. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions ) {
  11644. std::set<TestCase> seenFunctions;
  11645. for( auto const& function : functions ) {
  11646. auto prev = seenFunctions.insert( function );
  11647. CATCH_ENFORCE( prev.second,
  11648. "error: TEST_CASE( \"" << function.name << "\" ) already defined.\n"
  11649. << "\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo << "\n"
  11650. << "\tRedefined at " << function.getTestCaseInfo().lineInfo );
  11651. }
  11652. }
  11653. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config ) {
  11654. std::vector<TestCase> filtered;
  11655. filtered.reserve( testCases.size() );
  11656. for (auto const& testCase : testCases) {
  11657. if ((!testSpec.hasFilters() && !testCase.isHidden()) ||
  11658. (testSpec.hasFilters() && matchTest(testCase, testSpec, config))) {
  11659. filtered.push_back(testCase);
  11660. }
  11661. }
  11662. return filtered;
  11663. }
  11664. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config ) {
  11665. return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config );
  11666. }
  11667. void TestRegistry::registerTest( TestCase const& testCase ) {
  11668. std::string name = testCase.getTestCaseInfo().name;
  11669. if( name.empty() ) {
  11670. ReusableStringStream rss;
  11671. rss << "Anonymous test case " << ++m_unnamedCount;
  11672. return registerTest( testCase.withName( rss.str() ) );
  11673. }
  11674. m_functions.push_back( testCase );
  11675. }
  11676. std::vector<TestCase> const& TestRegistry::getAllTests() const {
  11677. return m_functions;
  11678. }
  11679. std::vector<TestCase> const& TestRegistry::getAllTestsSorted( IConfig const& config ) const {
  11680. if( m_sortedFunctions.empty() )
  11681. enforceNoDuplicateTestCases( m_functions );
  11682. if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) {
  11683. m_sortedFunctions = sortTests( config, m_functions );
  11684. m_currentSortOrder = config.runOrder();
  11685. }
  11686. return m_sortedFunctions;
  11687. }
  11688. ///////////////////////////////////////////////////////////////////////////
  11689. TestInvokerAsFunction::TestInvokerAsFunction( void(*testAsFunction)() ) noexcept : m_testAsFunction( testAsFunction ) {}
  11690. void TestInvokerAsFunction::invoke() const {
  11691. m_testAsFunction();
  11692. }
  11693. std::string extractClassName( StringRef const& classOrQualifiedMethodName ) {
  11694. std::string className(classOrQualifiedMethodName);
  11695. if( startsWith( className, '&' ) )
  11696. {
  11697. std::size_t lastColons = className.rfind( "::" );
  11698. std::size_t penultimateColons = className.rfind( "::", lastColons-1 );
  11699. if( penultimateColons == std::string::npos )
  11700. penultimateColons = 1;
  11701. className = className.substr( penultimateColons, lastColons-penultimateColons );
  11702. }
  11703. return className;
  11704. }
  11705. } // end namespace Catch
  11706. // end catch_test_case_registry_impl.cpp
  11707. // start catch_test_case_tracker.cpp
  11708. #include <algorithm>
  11709. #include <cassert>
  11710. #include <stdexcept>
  11711. #include <memory>
  11712. #include <sstream>
  11713. #if defined(__clang__)
  11714. # pragma clang diagnostic push
  11715. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  11716. #endif
  11717. namespace Catch {
  11718. namespace TestCaseTracking {
  11719. NameAndLocation::NameAndLocation( std::string const& _name, SourceLineInfo const& _location )
  11720. : name( _name ),
  11721. location( _location )
  11722. {}
  11723. ITracker::~ITracker() = default;
  11724. ITracker& TrackerContext::startRun() {
  11725. m_rootTracker = std::make_shared<SectionTracker>( NameAndLocation( "{root}", CATCH_INTERNAL_LINEINFO ), *this, nullptr );
  11726. m_currentTracker = nullptr;
  11727. m_runState = Executing;
  11728. return *m_rootTracker;
  11729. }
  11730. void TrackerContext::endRun() {
  11731. m_rootTracker.reset();
  11732. m_currentTracker = nullptr;
  11733. m_runState = NotStarted;
  11734. }
  11735. void TrackerContext::startCycle() {
  11736. m_currentTracker = m_rootTracker.get();
  11737. m_runState = Executing;
  11738. }
  11739. void TrackerContext::completeCycle() {
  11740. m_runState = CompletedCycle;
  11741. }
  11742. bool TrackerContext::completedCycle() const {
  11743. return m_runState == CompletedCycle;
  11744. }
  11745. ITracker& TrackerContext::currentTracker() {
  11746. return *m_currentTracker;
  11747. }
  11748. void TrackerContext::setCurrentTracker( ITracker* tracker ) {
  11749. m_currentTracker = tracker;
  11750. }
  11751. TrackerBase::TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent ):
  11752. ITracker(nameAndLocation),
  11753. m_ctx( ctx ),
  11754. m_parent( parent )
  11755. {}
  11756. bool TrackerBase::isComplete() const {
  11757. return m_runState == CompletedSuccessfully || m_runState == Failed;
  11758. }
  11759. bool TrackerBase::isSuccessfullyCompleted() const {
  11760. return m_runState == CompletedSuccessfully;
  11761. }
  11762. bool TrackerBase::isOpen() const {
  11763. return m_runState != NotStarted && !isComplete();
  11764. }
  11765. bool TrackerBase::hasChildren() const {
  11766. return !m_children.empty();
  11767. }
  11768. void TrackerBase::addChild( ITrackerPtr const& child ) {
  11769. m_children.push_back( child );
  11770. }
  11771. ITrackerPtr TrackerBase::findChild( NameAndLocation const& nameAndLocation ) {
  11772. auto it = std::find_if( m_children.begin(), m_children.end(),
  11773. [&nameAndLocation]( ITrackerPtr const& tracker ){
  11774. return
  11775. tracker->nameAndLocation().location == nameAndLocation.location &&
  11776. tracker->nameAndLocation().name == nameAndLocation.name;
  11777. } );
  11778. return( it != m_children.end() )
  11779. ? *it
  11780. : nullptr;
  11781. }
  11782. ITracker& TrackerBase::parent() {
  11783. assert( m_parent ); // Should always be non-null except for root
  11784. return *m_parent;
  11785. }
  11786. void TrackerBase::openChild() {
  11787. if( m_runState != ExecutingChildren ) {
  11788. m_runState = ExecutingChildren;
  11789. if( m_parent )
  11790. m_parent->openChild();
  11791. }
  11792. }
  11793. bool TrackerBase::isSectionTracker() const { return false; }
  11794. bool TrackerBase::isGeneratorTracker() const { return false; }
  11795. void TrackerBase::open() {
  11796. m_runState = Executing;
  11797. moveToThis();
  11798. if( m_parent )
  11799. m_parent->openChild();
  11800. }
  11801. void TrackerBase::close() {
  11802. // Close any still open children (e.g. generators)
  11803. while( &m_ctx.currentTracker() != this )
  11804. m_ctx.currentTracker().close();
  11805. switch( m_runState ) {
  11806. case NeedsAnotherRun:
  11807. break;
  11808. case Executing:
  11809. m_runState = CompletedSuccessfully;
  11810. break;
  11811. case ExecutingChildren:
  11812. if( std::all_of(m_children.begin(), m_children.end(), [](ITrackerPtr const& t){ return t->isComplete(); }) )
  11813. m_runState = CompletedSuccessfully;
  11814. break;
  11815. case NotStarted:
  11816. case CompletedSuccessfully:
  11817. case Failed:
  11818. CATCH_INTERNAL_ERROR( "Illogical state: " << m_runState );
  11819. default:
  11820. CATCH_INTERNAL_ERROR( "Unknown state: " << m_runState );
  11821. }
  11822. moveToParent();
  11823. m_ctx.completeCycle();
  11824. }
  11825. void TrackerBase::fail() {
  11826. m_runState = Failed;
  11827. if( m_parent )
  11828. m_parent->markAsNeedingAnotherRun();
  11829. moveToParent();
  11830. m_ctx.completeCycle();
  11831. }
  11832. void TrackerBase::markAsNeedingAnotherRun() {
  11833. m_runState = NeedsAnotherRun;
  11834. }
  11835. void TrackerBase::moveToParent() {
  11836. assert( m_parent );
  11837. m_ctx.setCurrentTracker( m_parent );
  11838. }
  11839. void TrackerBase::moveToThis() {
  11840. m_ctx.setCurrentTracker( this );
  11841. }
  11842. SectionTracker::SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  11843. : TrackerBase( nameAndLocation, ctx, parent ),
  11844. m_trimmed_name(trim(nameAndLocation.name))
  11845. {
  11846. if( parent ) {
  11847. while( !parent->isSectionTracker() )
  11848. parent = &parent->parent();
  11849. SectionTracker& parentSection = static_cast<SectionTracker&>( *parent );
  11850. addNextFilters( parentSection.m_filters );
  11851. }
  11852. }
  11853. bool SectionTracker::isComplete() const {
  11854. bool complete = true;
  11855. if (m_filters.empty()
  11856. || m_filters[0] == ""
  11857. || std::find(m_filters.begin(), m_filters.end(), m_trimmed_name) != m_filters.end()) {
  11858. complete = TrackerBase::isComplete();
  11859. }
  11860. return complete;
  11861. }
  11862. bool SectionTracker::isSectionTracker() const { return true; }
  11863. SectionTracker& SectionTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ) {
  11864. std::shared_ptr<SectionTracker> section;
  11865. ITracker& currentTracker = ctx.currentTracker();
  11866. if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  11867. assert( childTracker );
  11868. assert( childTracker->isSectionTracker() );
  11869. section = std::static_pointer_cast<SectionTracker>( childTracker );
  11870. }
  11871. else {
  11872. section = std::make_shared<SectionTracker>( nameAndLocation, ctx, &currentTracker );
  11873. currentTracker.addChild( section );
  11874. }
  11875. if( !ctx.completedCycle() )
  11876. section->tryOpen();
  11877. return *section;
  11878. }
  11879. void SectionTracker::tryOpen() {
  11880. if( !isComplete() )
  11881. open();
  11882. }
  11883. void SectionTracker::addInitialFilters( std::vector<std::string> const& filters ) {
  11884. if( !filters.empty() ) {
  11885. m_filters.reserve( m_filters.size() + filters.size() + 2 );
  11886. m_filters.emplace_back(""); // Root - should never be consulted
  11887. m_filters.emplace_back(""); // Test Case - not a section filter
  11888. m_filters.insert( m_filters.end(), filters.begin(), filters.end() );
  11889. }
  11890. }
  11891. void SectionTracker::addNextFilters( std::vector<std::string> const& filters ) {
  11892. if( filters.size() > 1 )
  11893. m_filters.insert( m_filters.end(), filters.begin()+1, filters.end() );
  11894. }
  11895. std::vector<std::string> const& SectionTracker::getFilters() const {
  11896. return m_filters;
  11897. }
  11898. std::string const& SectionTracker::trimmedName() const {
  11899. return m_trimmed_name;
  11900. }
  11901. } // namespace TestCaseTracking
  11902. using TestCaseTracking::ITracker;
  11903. using TestCaseTracking::TrackerContext;
  11904. using TestCaseTracking::SectionTracker;
  11905. } // namespace Catch
  11906. #if defined(__clang__)
  11907. # pragma clang diagnostic pop
  11908. #endif
  11909. // end catch_test_case_tracker.cpp
  11910. // start catch_test_registry.cpp
  11911. namespace Catch {
  11912. auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker* {
  11913. return new(std::nothrow) TestInvokerAsFunction( testAsFunction );
  11914. }
  11915. NameAndTags::NameAndTags( StringRef const& name_ , StringRef const& tags_ ) noexcept : name( name_ ), tags( tags_ ) {}
  11916. AutoReg::AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept {
  11917. CATCH_TRY {
  11918. getMutableRegistryHub()
  11919. .registerTest(
  11920. makeTestCase(
  11921. invoker,
  11922. extractClassName( classOrMethod ),
  11923. nameAndTags,
  11924. lineInfo));
  11925. } CATCH_CATCH_ALL {
  11926. // Do not throw when constructing global objects, instead register the exception to be processed later
  11927. getMutableRegistryHub().registerStartupException();
  11928. }
  11929. }
  11930. AutoReg::~AutoReg() = default;
  11931. }
  11932. // end catch_test_registry.cpp
  11933. // start catch_test_spec.cpp
  11934. #include <algorithm>
  11935. #include <string>
  11936. #include <vector>
  11937. #include <memory>
  11938. namespace Catch {
  11939. TestSpec::Pattern::Pattern( std::string const& name )
  11940. : m_name( name )
  11941. {}
  11942. TestSpec::Pattern::~Pattern() = default;
  11943. std::string const& TestSpec::Pattern::name() const {
  11944. return m_name;
  11945. }
  11946. TestSpec::NamePattern::NamePattern( std::string const& name, std::string const& filterString )
  11947. : Pattern( filterString )
  11948. , m_wildcardPattern( toLower( name ), CaseSensitive::No )
  11949. {}
  11950. bool TestSpec::NamePattern::matches( TestCaseInfo const& testCase ) const {
  11951. return m_wildcardPattern.matches( testCase.name );
  11952. }
  11953. TestSpec::TagPattern::TagPattern( std::string const& tag, std::string const& filterString )
  11954. : Pattern( filterString )
  11955. , m_tag( toLower( tag ) )
  11956. {}
  11957. bool TestSpec::TagPattern::matches( TestCaseInfo const& testCase ) const {
  11958. return std::find(begin(testCase.lcaseTags),
  11959. end(testCase.lcaseTags),
  11960. m_tag) != end(testCase.lcaseTags);
  11961. }
  11962. TestSpec::ExcludedPattern::ExcludedPattern( PatternPtr const& underlyingPattern )
  11963. : Pattern( underlyingPattern->name() )
  11964. , m_underlyingPattern( underlyingPattern )
  11965. {}
  11966. bool TestSpec::ExcludedPattern::matches( TestCaseInfo const& testCase ) const {
  11967. return !m_underlyingPattern->matches( testCase );
  11968. }
  11969. bool TestSpec::Filter::matches( TestCaseInfo const& testCase ) const {
  11970. return std::all_of( m_patterns.begin(), m_patterns.end(), [&]( PatternPtr const& p ){ return p->matches( testCase ); } );
  11971. }
  11972. std::string TestSpec::Filter::name() const {
  11973. std::string name;
  11974. for( auto const& p : m_patterns )
  11975. name += p->name();
  11976. return name;
  11977. }
  11978. bool TestSpec::hasFilters() const {
  11979. return !m_filters.empty();
  11980. }
  11981. bool TestSpec::matches( TestCaseInfo const& testCase ) const {
  11982. return std::any_of( m_filters.begin(), m_filters.end(), [&]( Filter const& f ){ return f.matches( testCase ); } );
  11983. }
  11984. TestSpec::Matches TestSpec::matchesByFilter( std::vector<TestCase> const& testCases, IConfig const& config ) const
  11985. {
  11986. Matches matches( m_filters.size() );
  11987. std::transform( m_filters.begin(), m_filters.end(), matches.begin(), [&]( Filter const& filter ){
  11988. std::vector<TestCase const*> currentMatches;
  11989. for( auto const& test : testCases )
  11990. if( isThrowSafe( test, config ) && filter.matches( test ) )
  11991. currentMatches.emplace_back( &test );
  11992. return FilterMatch{ filter.name(), currentMatches };
  11993. } );
  11994. return matches;
  11995. }
  11996. const TestSpec::vectorStrings& TestSpec::getInvalidArgs() const{
  11997. return (m_invalidArgs);
  11998. }
  11999. }
  12000. // end catch_test_spec.cpp
  12001. // start catch_test_spec_parser.cpp
  12002. namespace Catch {
  12003. TestSpecParser::TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {}
  12004. TestSpecParser& TestSpecParser::parse( std::string const& arg ) {
  12005. m_mode = None;
  12006. m_exclusion = false;
  12007. m_arg = m_tagAliases->expandAliases( arg );
  12008. m_escapeChars.clear();
  12009. m_substring.reserve(m_arg.size());
  12010. m_patternName.reserve(m_arg.size());
  12011. m_realPatternPos = 0;
  12012. for( m_pos = 0; m_pos < m_arg.size(); ++m_pos )
  12013. //if visitChar fails
  12014. if( !visitChar( m_arg[m_pos] ) ){
  12015. m_testSpec.m_invalidArgs.push_back(arg);
  12016. break;
  12017. }
  12018. endMode();
  12019. return *this;
  12020. }
  12021. TestSpec TestSpecParser::testSpec() {
  12022. addFilter();
  12023. return m_testSpec;
  12024. }
  12025. bool TestSpecParser::visitChar( char c ) {
  12026. if( (m_mode != EscapedName) && (c == '\\') ) {
  12027. escape();
  12028. addCharToPattern(c);
  12029. return true;
  12030. }else if((m_mode != EscapedName) && (c == ',') ) {
  12031. return separate();
  12032. }
  12033. switch( m_mode ) {
  12034. case None:
  12035. if( processNoneChar( c ) )
  12036. return true;
  12037. break;
  12038. case Name:
  12039. processNameChar( c );
  12040. break;
  12041. case EscapedName:
  12042. endMode();
  12043. addCharToPattern(c);
  12044. return true;
  12045. default:
  12046. case Tag:
  12047. case QuotedName:
  12048. if( processOtherChar( c ) )
  12049. return true;
  12050. break;
  12051. }
  12052. m_substring += c;
  12053. if( !isControlChar( c ) ) {
  12054. m_patternName += c;
  12055. m_realPatternPos++;
  12056. }
  12057. return true;
  12058. }
  12059. // Two of the processing methods return true to signal the caller to return
  12060. // without adding the given character to the current pattern strings
  12061. bool TestSpecParser::processNoneChar( char c ) {
  12062. switch( c ) {
  12063. case ' ':
  12064. return true;
  12065. case '~':
  12066. m_exclusion = true;
  12067. return false;
  12068. case '[':
  12069. startNewMode( Tag );
  12070. return false;
  12071. case '"':
  12072. startNewMode( QuotedName );
  12073. return false;
  12074. default:
  12075. startNewMode( Name );
  12076. return false;
  12077. }
  12078. }
  12079. void TestSpecParser::processNameChar( char c ) {
  12080. if( c == '[' ) {
  12081. if( m_substring == "exclude:" )
  12082. m_exclusion = true;
  12083. else
  12084. endMode();
  12085. startNewMode( Tag );
  12086. }
  12087. }
  12088. bool TestSpecParser::processOtherChar( char c ) {
  12089. if( !isControlChar( c ) )
  12090. return false;
  12091. m_substring += c;
  12092. endMode();
  12093. return true;
  12094. }
  12095. void TestSpecParser::startNewMode( Mode mode ) {
  12096. m_mode = mode;
  12097. }
  12098. void TestSpecParser::endMode() {
  12099. switch( m_mode ) {
  12100. case Name:
  12101. case QuotedName:
  12102. return addNamePattern();
  12103. case Tag:
  12104. return addTagPattern();
  12105. case EscapedName:
  12106. revertBackToLastMode();
  12107. return;
  12108. case None:
  12109. default:
  12110. return startNewMode( None );
  12111. }
  12112. }
  12113. void TestSpecParser::escape() {
  12114. saveLastMode();
  12115. m_mode = EscapedName;
  12116. m_escapeChars.push_back(m_realPatternPos);
  12117. }
  12118. bool TestSpecParser::isControlChar( char c ) const {
  12119. switch( m_mode ) {
  12120. default:
  12121. return false;
  12122. case None:
  12123. return c == '~';
  12124. case Name:
  12125. return c == '[';
  12126. case EscapedName:
  12127. return true;
  12128. case QuotedName:
  12129. return c == '"';
  12130. case Tag:
  12131. return c == '[' || c == ']';
  12132. }
  12133. }
  12134. void TestSpecParser::addFilter() {
  12135. if( !m_currentFilter.m_patterns.empty() ) {
  12136. m_testSpec.m_filters.push_back( m_currentFilter );
  12137. m_currentFilter = TestSpec::Filter();
  12138. }
  12139. }
  12140. void TestSpecParser::saveLastMode() {
  12141. lastMode = m_mode;
  12142. }
  12143. void TestSpecParser::revertBackToLastMode() {
  12144. m_mode = lastMode;
  12145. }
  12146. bool TestSpecParser::separate() {
  12147. if( (m_mode==QuotedName) || (m_mode==Tag) ){
  12148. //invalid argument, signal failure to previous scope.
  12149. m_mode = None;
  12150. m_pos = m_arg.size();
  12151. m_substring.clear();
  12152. m_patternName.clear();
  12153. m_realPatternPos = 0;
  12154. return false;
  12155. }
  12156. endMode();
  12157. addFilter();
  12158. return true; //success
  12159. }
  12160. std::string TestSpecParser::preprocessPattern() {
  12161. std::string token = m_patternName;
  12162. for (std::size_t i = 0; i < m_escapeChars.size(); ++i)
  12163. token = token.substr(0, m_escapeChars[i] - i) + token.substr(m_escapeChars[i] - i + 1);
  12164. m_escapeChars.clear();
  12165. if (startsWith(token, "exclude:")) {
  12166. m_exclusion = true;
  12167. token = token.substr(8);
  12168. }
  12169. m_patternName.clear();
  12170. m_realPatternPos = 0;
  12171. return token;
  12172. }
  12173. void TestSpecParser::addNamePattern() {
  12174. auto token = preprocessPattern();
  12175. if (!token.empty()) {
  12176. TestSpec::PatternPtr pattern = std::make_shared<TestSpec::NamePattern>(token, m_substring);
  12177. if (m_exclusion)
  12178. pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
  12179. m_currentFilter.m_patterns.push_back(pattern);
  12180. }
  12181. m_substring.clear();
  12182. m_exclusion = false;
  12183. m_mode = None;
  12184. }
  12185. void TestSpecParser::addTagPattern() {
  12186. auto token = preprocessPattern();
  12187. if (!token.empty()) {
  12188. // If the tag pattern is the "hide and tag" shorthand (e.g. [.foo])
  12189. // we have to create a separate hide tag and shorten the real one
  12190. if (token.size() > 1 && token[0] == '.') {
  12191. token.erase(token.begin());
  12192. TestSpec::PatternPtr pattern = std::make_shared<TestSpec::TagPattern>(".", m_substring);
  12193. if (m_exclusion) {
  12194. pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
  12195. }
  12196. m_currentFilter.m_patterns.push_back(pattern);
  12197. }
  12198. TestSpec::PatternPtr pattern = std::make_shared<TestSpec::TagPattern>(token, m_substring);
  12199. if (m_exclusion) {
  12200. pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
  12201. }
  12202. m_currentFilter.m_patterns.push_back(pattern);
  12203. }
  12204. m_substring.clear();
  12205. m_exclusion = false;
  12206. m_mode = None;
  12207. }
  12208. TestSpec parseTestSpec( std::string const& arg ) {
  12209. return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec();
  12210. }
  12211. } // namespace Catch
  12212. // end catch_test_spec_parser.cpp
  12213. // start catch_timer.cpp
  12214. #include <chrono>
  12215. static const uint64_t nanosecondsInSecond = 1000000000;
  12216. namespace Catch {
  12217. auto getCurrentNanosecondsSinceEpoch() -> uint64_t {
  12218. return std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::high_resolution_clock::now().time_since_epoch() ).count();
  12219. }
  12220. namespace {
  12221. auto estimateClockResolution() -> uint64_t {
  12222. uint64_t sum = 0;
  12223. static const uint64_t iterations = 1000000;
  12224. auto startTime = getCurrentNanosecondsSinceEpoch();
  12225. for( std::size_t i = 0; i < iterations; ++i ) {
  12226. uint64_t ticks;
  12227. uint64_t baseTicks = getCurrentNanosecondsSinceEpoch();
  12228. do {
  12229. ticks = getCurrentNanosecondsSinceEpoch();
  12230. } while( ticks == baseTicks );
  12231. auto delta = ticks - baseTicks;
  12232. sum += delta;
  12233. // If we have been calibrating for over 3 seconds -- the clock
  12234. // is terrible and we should move on.
  12235. // TBD: How to signal that the measured resolution is probably wrong?
  12236. if (ticks > startTime + 3 * nanosecondsInSecond) {
  12237. return sum / ( i + 1u );
  12238. }
  12239. }
  12240. // We're just taking the mean, here. To do better we could take the std. dev and exclude outliers
  12241. // - and potentially do more iterations if there's a high variance.
  12242. return sum/iterations;
  12243. }
  12244. }
  12245. auto getEstimatedClockResolution() -> uint64_t {
  12246. static auto s_resolution = estimateClockResolution();
  12247. return s_resolution;
  12248. }
  12249. void Timer::start() {
  12250. m_nanoseconds = getCurrentNanosecondsSinceEpoch();
  12251. }
  12252. auto Timer::getElapsedNanoseconds() const -> uint64_t {
  12253. return getCurrentNanosecondsSinceEpoch() - m_nanoseconds;
  12254. }
  12255. auto Timer::getElapsedMicroseconds() const -> uint64_t {
  12256. return getElapsedNanoseconds()/1000;
  12257. }
  12258. auto Timer::getElapsedMilliseconds() const -> unsigned int {
  12259. return static_cast<unsigned int>(getElapsedMicroseconds()/1000);
  12260. }
  12261. auto Timer::getElapsedSeconds() const -> double {
  12262. return getElapsedMicroseconds()/1000000.0;
  12263. }
  12264. } // namespace Catch
  12265. // end catch_timer.cpp
  12266. // start catch_tostring.cpp
  12267. #if defined(__clang__)
  12268. # pragma clang diagnostic push
  12269. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  12270. # pragma clang diagnostic ignored "-Wglobal-constructors"
  12271. #endif
  12272. // Enable specific decls locally
  12273. #if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  12274. #define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  12275. #endif
  12276. #include <cmath>
  12277. #include <iomanip>
  12278. namespace Catch {
  12279. namespace Detail {
  12280. const std::string unprintableString = "{?}";
  12281. namespace {
  12282. const int hexThreshold = 255;
  12283. struct Endianness {
  12284. enum Arch { Big, Little };
  12285. static Arch which() {
  12286. int one = 1;
  12287. // If the lowest byte we read is non-zero, we can assume
  12288. // that little endian format is used.
  12289. auto value = *reinterpret_cast<char*>(&one);
  12290. return value ? Little : Big;
  12291. }
  12292. };
  12293. }
  12294. std::string rawMemoryToString( const void *object, std::size_t size ) {
  12295. // Reverse order for little endian architectures
  12296. int i = 0, end = static_cast<int>( size ), inc = 1;
  12297. if( Endianness::which() == Endianness::Little ) {
  12298. i = end-1;
  12299. end = inc = -1;
  12300. }
  12301. unsigned char const *bytes = static_cast<unsigned char const *>(object);
  12302. ReusableStringStream rss;
  12303. rss << "0x" << std::setfill('0') << std::hex;
  12304. for( ; i != end; i += inc )
  12305. rss << std::setw(2) << static_cast<unsigned>(bytes[i]);
  12306. return rss.str();
  12307. }
  12308. }
  12309. template<typename T>
  12310. std::string fpToString( T value, int precision ) {
  12311. if (Catch::isnan(value)) {
  12312. return "nan";
  12313. }
  12314. ReusableStringStream rss;
  12315. rss << std::setprecision( precision )
  12316. << std::fixed
  12317. << value;
  12318. std::string d = rss.str();
  12319. std::size_t i = d.find_last_not_of( '0' );
  12320. if( i != std::string::npos && i != d.size()-1 ) {
  12321. if( d[i] == '.' )
  12322. i++;
  12323. d = d.substr( 0, i+1 );
  12324. }
  12325. return d;
  12326. }
  12327. //// ======================================================= ////
  12328. //
  12329. // Out-of-line defs for full specialization of StringMaker
  12330. //
  12331. //// ======================================================= ////
  12332. std::string StringMaker<std::string>::convert(const std::string& str) {
  12333. if (!getCurrentContext().getConfig()->showInvisibles()) {
  12334. return '"' + str + '"';
  12335. }
  12336. std::string s("\"");
  12337. for (char c : str) {
  12338. switch (c) {
  12339. case '\n':
  12340. s.append("\\n");
  12341. break;
  12342. case '\t':
  12343. s.append("\\t");
  12344. break;
  12345. default:
  12346. s.push_back(c);
  12347. break;
  12348. }
  12349. }
  12350. s.append("\"");
  12351. return s;
  12352. }
  12353. #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  12354. std::string StringMaker<std::string_view>::convert(std::string_view str) {
  12355. return ::Catch::Detail::stringify(std::string{ str });
  12356. }
  12357. #endif
  12358. std::string StringMaker<char const*>::convert(char const* str) {
  12359. if (str) {
  12360. return ::Catch::Detail::stringify(std::string{ str });
  12361. } else {
  12362. return{ "{null string}" };
  12363. }
  12364. }
  12365. std::string StringMaker<char*>::convert(char* str) {
  12366. if (str) {
  12367. return ::Catch::Detail::stringify(std::string{ str });
  12368. } else {
  12369. return{ "{null string}" };
  12370. }
  12371. }
  12372. #ifdef CATCH_CONFIG_WCHAR
  12373. std::string StringMaker<std::wstring>::convert(const std::wstring& wstr) {
  12374. std::string s;
  12375. s.reserve(wstr.size());
  12376. for (auto c : wstr) {
  12377. s += (c <= 0xff) ? static_cast<char>(c) : '?';
  12378. }
  12379. return ::Catch::Detail::stringify(s);
  12380. }
  12381. # ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  12382. std::string StringMaker<std::wstring_view>::convert(std::wstring_view str) {
  12383. return StringMaker<std::wstring>::convert(std::wstring(str));
  12384. }
  12385. # endif
  12386. std::string StringMaker<wchar_t const*>::convert(wchar_t const * str) {
  12387. if (str) {
  12388. return ::Catch::Detail::stringify(std::wstring{ str });
  12389. } else {
  12390. return{ "{null string}" };
  12391. }
  12392. }
  12393. std::string StringMaker<wchar_t *>::convert(wchar_t * str) {
  12394. if (str) {
  12395. return ::Catch::Detail::stringify(std::wstring{ str });
  12396. } else {
  12397. return{ "{null string}" };
  12398. }
  12399. }
  12400. #endif
  12401. #if defined(CATCH_CONFIG_CPP17_BYTE)
  12402. #include <cstddef>
  12403. std::string StringMaker<std::byte>::convert(std::byte value) {
  12404. return ::Catch::Detail::stringify(std::to_integer<unsigned long long>(value));
  12405. }
  12406. #endif // defined(CATCH_CONFIG_CPP17_BYTE)
  12407. std::string StringMaker<int>::convert(int value) {
  12408. return ::Catch::Detail::stringify(static_cast<long long>(value));
  12409. }
  12410. std::string StringMaker<long>::convert(long value) {
  12411. return ::Catch::Detail::stringify(static_cast<long long>(value));
  12412. }
  12413. std::string StringMaker<long long>::convert(long long value) {
  12414. ReusableStringStream rss;
  12415. rss << value;
  12416. if (value > Detail::hexThreshold) {
  12417. rss << " (0x" << std::hex << value << ')';
  12418. }
  12419. return rss.str();
  12420. }
  12421. std::string StringMaker<unsigned int>::convert(unsigned int value) {
  12422. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  12423. }
  12424. std::string StringMaker<unsigned long>::convert(unsigned long value) {
  12425. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  12426. }
  12427. std::string StringMaker<unsigned long long>::convert(unsigned long long value) {
  12428. ReusableStringStream rss;
  12429. rss << value;
  12430. if (value > Detail::hexThreshold) {
  12431. rss << " (0x" << std::hex << value << ')';
  12432. }
  12433. return rss.str();
  12434. }
  12435. std::string StringMaker<bool>::convert(bool b) {
  12436. return b ? "true" : "false";
  12437. }
  12438. std::string StringMaker<signed char>::convert(signed char value) {
  12439. if (value == '\r') {
  12440. return "'\\r'";
  12441. } else if (value == '\f') {
  12442. return "'\\f'";
  12443. } else if (value == '\n') {
  12444. return "'\\n'";
  12445. } else if (value == '\t') {
  12446. return "'\\t'";
  12447. } else if ('\0' <= value && value < ' ') {
  12448. return ::Catch::Detail::stringify(static_cast<unsigned int>(value));
  12449. } else {
  12450. char chstr[] = "' '";
  12451. chstr[1] = value;
  12452. return chstr;
  12453. }
  12454. }
  12455. std::string StringMaker<char>::convert(char c) {
  12456. return ::Catch::Detail::stringify(static_cast<signed char>(c));
  12457. }
  12458. std::string StringMaker<unsigned char>::convert(unsigned char c) {
  12459. return ::Catch::Detail::stringify(static_cast<char>(c));
  12460. }
  12461. std::string StringMaker<std::nullptr_t>::convert(std::nullptr_t) {
  12462. return "nullptr";
  12463. }
  12464. int StringMaker<float>::precision = 5;
  12465. std::string StringMaker<float>::convert(float value) {
  12466. return fpToString(value, precision) + 'f';
  12467. }
  12468. int StringMaker<double>::precision = 10;
  12469. std::string StringMaker<double>::convert(double value) {
  12470. return fpToString(value, precision);
  12471. }
  12472. std::string ratio_string<std::atto>::symbol() { return "a"; }
  12473. std::string ratio_string<std::femto>::symbol() { return "f"; }
  12474. std::string ratio_string<std::pico>::symbol() { return "p"; }
  12475. std::string ratio_string<std::nano>::symbol() { return "n"; }
  12476. std::string ratio_string<std::micro>::symbol() { return "u"; }
  12477. std::string ratio_string<std::milli>::symbol() { return "m"; }
  12478. } // end namespace Catch
  12479. #if defined(__clang__)
  12480. # pragma clang diagnostic pop
  12481. #endif
  12482. // end catch_tostring.cpp
  12483. // start catch_totals.cpp
  12484. namespace Catch {
  12485. Counts Counts::operator - ( Counts const& other ) const {
  12486. Counts diff;
  12487. diff.passed = passed - other.passed;
  12488. diff.failed = failed - other.failed;
  12489. diff.failedButOk = failedButOk - other.failedButOk;
  12490. return diff;
  12491. }
  12492. Counts& Counts::operator += ( Counts const& other ) {
  12493. passed += other.passed;
  12494. failed += other.failed;
  12495. failedButOk += other.failedButOk;
  12496. return *this;
  12497. }
  12498. std::size_t Counts::total() const {
  12499. return passed + failed + failedButOk;
  12500. }
  12501. bool Counts::allPassed() const {
  12502. return failed == 0 && failedButOk == 0;
  12503. }
  12504. bool Counts::allOk() const {
  12505. return failed == 0;
  12506. }
  12507. Totals Totals::operator - ( Totals const& other ) const {
  12508. Totals diff;
  12509. diff.assertions = assertions - other.assertions;
  12510. diff.testCases = testCases - other.testCases;
  12511. return diff;
  12512. }
  12513. Totals& Totals::operator += ( Totals const& other ) {
  12514. assertions += other.assertions;
  12515. testCases += other.testCases;
  12516. return *this;
  12517. }
  12518. Totals Totals::delta( Totals const& prevTotals ) const {
  12519. Totals diff = *this - prevTotals;
  12520. if( diff.assertions.failed > 0 )
  12521. ++diff.testCases.failed;
  12522. else if( diff.assertions.failedButOk > 0 )
  12523. ++diff.testCases.failedButOk;
  12524. else
  12525. ++diff.testCases.passed;
  12526. return diff;
  12527. }
  12528. }
  12529. // end catch_totals.cpp
  12530. // start catch_uncaught_exceptions.cpp
  12531. // start catch_config_uncaught_exceptions.hpp
  12532. // Copyright Catch2 Authors
  12533. // Distributed under the Boost Software License, Version 1.0.
  12534. // (See accompanying file LICENSE_1_0.txt or copy at
  12535. // https://www.boost.org/LICENSE_1_0.txt)
  12536. // SPDX-License-Identifier: BSL-1.0
  12537. #ifndef CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP
  12538. #define CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP
  12539. #if defined(_MSC_VER)
  12540. # if _MSC_VER >= 1900 // Visual Studio 2015 or newer
  12541. # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
  12542. # endif
  12543. #endif
  12544. #include <exception>
  12545. #if defined(__cpp_lib_uncaught_exceptions) \
  12546. && !defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
  12547. # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
  12548. #endif // __cpp_lib_uncaught_exceptions
  12549. #if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) \
  12550. && !defined(CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) \
  12551. && !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
  12552. # define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
  12553. #endif
  12554. #endif // CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP
  12555. // end catch_config_uncaught_exceptions.hpp
  12556. #include <exception>
  12557. namespace Catch {
  12558. bool uncaught_exceptions() {
  12559. #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  12560. return false;
  12561. #elif defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
  12562. return std::uncaught_exceptions() > 0;
  12563. #else
  12564. return std::uncaught_exception();
  12565. #endif
  12566. }
  12567. } // end namespace Catch
  12568. // end catch_uncaught_exceptions.cpp
  12569. // start catch_version.cpp
  12570. #include <ostream>
  12571. namespace Catch {
  12572. Version::Version
  12573. ( unsigned int _majorVersion,
  12574. unsigned int _minorVersion,
  12575. unsigned int _patchNumber,
  12576. char const * const _branchName,
  12577. unsigned int _buildNumber )
  12578. : majorVersion( _majorVersion ),
  12579. minorVersion( _minorVersion ),
  12580. patchNumber( _patchNumber ),
  12581. branchName( _branchName ),
  12582. buildNumber( _buildNumber )
  12583. {}
  12584. std::ostream& operator << ( std::ostream& os, Version const& version ) {
  12585. os << version.majorVersion << '.'
  12586. << version.minorVersion << '.'
  12587. << version.patchNumber;
  12588. // branchName is never null -> 0th char is \0 if it is empty
  12589. if (version.branchName[0]) {
  12590. os << '-' << version.branchName
  12591. << '.' << version.buildNumber;
  12592. }
  12593. return os;
  12594. }
  12595. Version const& libraryVersion() {
  12596. static Version version( 2, 13, 6, "", 0 );
  12597. return version;
  12598. }
  12599. }
  12600. // end catch_version.cpp
  12601. // start catch_wildcard_pattern.cpp
  12602. namespace Catch {
  12603. WildcardPattern::WildcardPattern( std::string const& pattern,
  12604. CaseSensitive::Choice caseSensitivity )
  12605. : m_caseSensitivity( caseSensitivity ),
  12606. m_pattern( normaliseString( pattern ) )
  12607. {
  12608. if( startsWith( m_pattern, '*' ) ) {
  12609. m_pattern = m_pattern.substr( 1 );
  12610. m_wildcard = WildcardAtStart;
  12611. }
  12612. if( endsWith( m_pattern, '*' ) ) {
  12613. m_pattern = m_pattern.substr( 0, m_pattern.size()-1 );
  12614. m_wildcard = static_cast<WildcardPosition>( m_wildcard | WildcardAtEnd );
  12615. }
  12616. }
  12617. bool WildcardPattern::matches( std::string const& str ) const {
  12618. switch( m_wildcard ) {
  12619. case NoWildcard:
  12620. return m_pattern == normaliseString( str );
  12621. case WildcardAtStart:
  12622. return endsWith( normaliseString( str ), m_pattern );
  12623. case WildcardAtEnd:
  12624. return startsWith( normaliseString( str ), m_pattern );
  12625. case WildcardAtBothEnds:
  12626. return contains( normaliseString( str ), m_pattern );
  12627. default:
  12628. CATCH_INTERNAL_ERROR( "Unknown enum" );
  12629. }
  12630. }
  12631. std::string WildcardPattern::normaliseString( std::string const& str ) const {
  12632. return trim( m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str );
  12633. }
  12634. }
  12635. // end catch_wildcard_pattern.cpp
  12636. // start catch_xmlwriter.cpp
  12637. #include <iomanip>
  12638. #include <type_traits>
  12639. namespace Catch {
  12640. namespace {
  12641. size_t trailingBytes(unsigned char c) {
  12642. if ((c & 0xE0) == 0xC0) {
  12643. return 2;
  12644. }
  12645. if ((c & 0xF0) == 0xE0) {
  12646. return 3;
  12647. }
  12648. if ((c & 0xF8) == 0xF0) {
  12649. return 4;
  12650. }
  12651. CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
  12652. }
  12653. uint32_t headerValue(unsigned char c) {
  12654. if ((c & 0xE0) == 0xC0) {
  12655. return c & 0x1F;
  12656. }
  12657. if ((c & 0xF0) == 0xE0) {
  12658. return c & 0x0F;
  12659. }
  12660. if ((c & 0xF8) == 0xF0) {
  12661. return c & 0x07;
  12662. }
  12663. CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
  12664. }
  12665. void hexEscapeChar(std::ostream& os, unsigned char c) {
  12666. std::ios_base::fmtflags f(os.flags());
  12667. os << "\\x"
  12668. << std::uppercase << std::hex << std::setfill('0') << std::setw(2)
  12669. << static_cast<int>(c);
  12670. os.flags(f);
  12671. }
  12672. bool shouldNewline(XmlFormatting fmt) {
  12673. return !!(static_cast<std::underlying_type<XmlFormatting>::type>(fmt & XmlFormatting::Newline));
  12674. }
  12675. bool shouldIndent(XmlFormatting fmt) {
  12676. return !!(static_cast<std::underlying_type<XmlFormatting>::type>(fmt & XmlFormatting::Indent));
  12677. }
  12678. } // anonymous namespace
  12679. XmlFormatting operator | (XmlFormatting lhs, XmlFormatting rhs) {
  12680. return static_cast<XmlFormatting>(
  12681. static_cast<std::underlying_type<XmlFormatting>::type>(lhs) |
  12682. static_cast<std::underlying_type<XmlFormatting>::type>(rhs)
  12683. );
  12684. }
  12685. XmlFormatting operator & (XmlFormatting lhs, XmlFormatting rhs) {
  12686. return static_cast<XmlFormatting>(
  12687. static_cast<std::underlying_type<XmlFormatting>::type>(lhs) &
  12688. static_cast<std::underlying_type<XmlFormatting>::type>(rhs)
  12689. );
  12690. }
  12691. XmlEncode::XmlEncode( std::string const& str, ForWhat forWhat )
  12692. : m_str( str ),
  12693. m_forWhat( forWhat )
  12694. {}
  12695. void XmlEncode::encodeTo( std::ostream& os ) const {
  12696. // Apostrophe escaping not necessary if we always use " to write attributes
  12697. // (see: http://www.w3.org/TR/xml/#syntax)
  12698. for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) {
  12699. unsigned char c = m_str[idx];
  12700. switch (c) {
  12701. case '<': os << "&lt;"; break;
  12702. case '&': os << "&amp;"; break;
  12703. case '>':
  12704. // See: http://www.w3.org/TR/xml/#syntax
  12705. if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']')
  12706. os << "&gt;";
  12707. else
  12708. os << c;
  12709. break;
  12710. case '\"':
  12711. if (m_forWhat == ForAttributes)
  12712. os << "&quot;";
  12713. else
  12714. os << c;
  12715. break;
  12716. default:
  12717. // Check for control characters and invalid utf-8
  12718. // Escape control characters in standard ascii
  12719. // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0
  12720. if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) {
  12721. hexEscapeChar(os, c);
  12722. break;
  12723. }
  12724. // Plain ASCII: Write it to stream
  12725. if (c < 0x7F) {
  12726. os << c;
  12727. break;
  12728. }
  12729. // UTF-8 territory
  12730. // Check if the encoding is valid and if it is not, hex escape bytes.
  12731. // Important: We do not check the exact decoded values for validity, only the encoding format
  12732. // First check that this bytes is a valid lead byte:
  12733. // This means that it is not encoded as 1111 1XXX
  12734. // Or as 10XX XXXX
  12735. if (c < 0xC0 ||
  12736. c >= 0xF8) {
  12737. hexEscapeChar(os, c);
  12738. break;
  12739. }
  12740. auto encBytes = trailingBytes(c);
  12741. // Are there enough bytes left to avoid accessing out-of-bounds memory?
  12742. if (idx + encBytes - 1 >= m_str.size()) {
  12743. hexEscapeChar(os, c);
  12744. break;
  12745. }
  12746. // The header is valid, check data
  12747. // The next encBytes bytes must together be a valid utf-8
  12748. // This means: bitpattern 10XX XXXX and the extracted value is sane (ish)
  12749. bool valid = true;
  12750. uint32_t value = headerValue(c);
  12751. for (std::size_t n = 1; n < encBytes; ++n) {
  12752. unsigned char nc = m_str[idx + n];
  12753. valid &= ((nc & 0xC0) == 0x80);
  12754. value = (value << 6) | (nc & 0x3F);
  12755. }
  12756. if (
  12757. // Wrong bit pattern of following bytes
  12758. (!valid) ||
  12759. // Overlong encodings
  12760. (value < 0x80) ||
  12761. (0x80 <= value && value < 0x800 && encBytes > 2) ||
  12762. (0x800 < value && value < 0x10000 && encBytes > 3) ||
  12763. // Encoded value out of range
  12764. (value >= 0x110000)
  12765. ) {
  12766. hexEscapeChar(os, c);
  12767. break;
  12768. }
  12769. // If we got here, this is in fact a valid(ish) utf-8 sequence
  12770. for (std::size_t n = 0; n < encBytes; ++n) {
  12771. os << m_str[idx + n];
  12772. }
  12773. idx += encBytes - 1;
  12774. break;
  12775. }
  12776. }
  12777. }
  12778. std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) {
  12779. xmlEncode.encodeTo( os );
  12780. return os;
  12781. }
  12782. XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer, XmlFormatting fmt )
  12783. : m_writer( writer ),
  12784. m_fmt(fmt)
  12785. {}
  12786. XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept
  12787. : m_writer( other.m_writer ),
  12788. m_fmt(other.m_fmt)
  12789. {
  12790. other.m_writer = nullptr;
  12791. other.m_fmt = XmlFormatting::None;
  12792. }
  12793. XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) noexcept {
  12794. if ( m_writer ) {
  12795. m_writer->endElement();
  12796. }
  12797. m_writer = other.m_writer;
  12798. other.m_writer = nullptr;
  12799. m_fmt = other.m_fmt;
  12800. other.m_fmt = XmlFormatting::None;
  12801. return *this;
  12802. }
  12803. XmlWriter::ScopedElement::~ScopedElement() {
  12804. if (m_writer) {
  12805. m_writer->endElement(m_fmt);
  12806. }
  12807. }
  12808. XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string const& text, XmlFormatting fmt ) {
  12809. m_writer->writeText( text, fmt );
  12810. return *this;
  12811. }
  12812. XmlWriter::XmlWriter( std::ostream& os ) : m_os( os )
  12813. {
  12814. writeDeclaration();
  12815. }
  12816. XmlWriter::~XmlWriter() {
  12817. while (!m_tags.empty()) {
  12818. endElement();
  12819. }
  12820. newlineIfNecessary();
  12821. }
  12822. XmlWriter& XmlWriter::startElement( std::string const& name, XmlFormatting fmt ) {
  12823. ensureTagClosed();
  12824. newlineIfNecessary();
  12825. if (shouldIndent(fmt)) {
  12826. m_os << m_indent;
  12827. m_indent += " ";
  12828. }
  12829. m_os << '<' << name;
  12830. m_tags.push_back( name );
  12831. m_tagIsOpen = true;
  12832. applyFormatting(fmt);
  12833. return *this;
  12834. }
  12835. XmlWriter::ScopedElement XmlWriter::scopedElement( std::string const& name, XmlFormatting fmt ) {
  12836. ScopedElement scoped( this, fmt );
  12837. startElement( name, fmt );
  12838. return scoped;
  12839. }
  12840. XmlWriter& XmlWriter::endElement(XmlFormatting fmt) {
  12841. m_indent = m_indent.substr(0, m_indent.size() - 2);
  12842. if( m_tagIsOpen ) {
  12843. m_os << "/>";
  12844. m_tagIsOpen = false;
  12845. } else {
  12846. newlineIfNecessary();
  12847. if (shouldIndent(fmt)) {
  12848. m_os << m_indent;
  12849. }
  12850. m_os << "</" << m_tags.back() << ">";
  12851. }
  12852. m_os << std::flush;
  12853. applyFormatting(fmt);
  12854. m_tags.pop_back();
  12855. return *this;
  12856. }
  12857. XmlWriter& XmlWriter::writeAttribute( std::string const& name, std::string const& attribute ) {
  12858. if( !name.empty() && !attribute.empty() )
  12859. m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"';
  12860. return *this;
  12861. }
  12862. XmlWriter& XmlWriter::writeAttribute( std::string const& name, bool attribute ) {
  12863. m_os << ' ' << name << "=\"" << ( attribute ? "true" : "false" ) << '"';
  12864. return *this;
  12865. }
  12866. XmlWriter& XmlWriter::writeText( std::string const& text, XmlFormatting fmt) {
  12867. if( !text.empty() ){
  12868. bool tagWasOpen = m_tagIsOpen;
  12869. ensureTagClosed();
  12870. if (tagWasOpen && shouldIndent(fmt)) {
  12871. m_os << m_indent;
  12872. }
  12873. m_os << XmlEncode( text );
  12874. applyFormatting(fmt);
  12875. }
  12876. return *this;
  12877. }
  12878. XmlWriter& XmlWriter::writeComment( std::string const& text, XmlFormatting fmt) {
  12879. ensureTagClosed();
  12880. if (shouldIndent(fmt)) {
  12881. m_os << m_indent;
  12882. }
  12883. m_os << "<!--" << text << "-->";
  12884. applyFormatting(fmt);
  12885. return *this;
  12886. }
  12887. void XmlWriter::writeStylesheetRef( std::string const& url ) {
  12888. m_os << "<?xml-stylesheet type=\"text/xsl\" href=\"" << url << "\"?>\n";
  12889. }
  12890. XmlWriter& XmlWriter::writeBlankLine() {
  12891. ensureTagClosed();
  12892. m_os << '\n';
  12893. return *this;
  12894. }
  12895. void XmlWriter::ensureTagClosed() {
  12896. if( m_tagIsOpen ) {
  12897. m_os << '>' << std::flush;
  12898. newlineIfNecessary();
  12899. m_tagIsOpen = false;
  12900. }
  12901. }
  12902. void XmlWriter::applyFormatting(XmlFormatting fmt) {
  12903. m_needsNewline = shouldNewline(fmt);
  12904. }
  12905. void XmlWriter::writeDeclaration() {
  12906. m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
  12907. }
  12908. void XmlWriter::newlineIfNecessary() {
  12909. if( m_needsNewline ) {
  12910. m_os << std::endl;
  12911. m_needsNewline = false;
  12912. }
  12913. }
  12914. }
  12915. // end catch_xmlwriter.cpp
  12916. // start catch_reporter_bases.cpp
  12917. #include <cstring>
  12918. #include <cfloat>
  12919. #include <cstdio>
  12920. #include <cassert>
  12921. #include <memory>
  12922. namespace Catch {
  12923. void prepareExpandedExpression(AssertionResult& result) {
  12924. result.getExpandedExpression();
  12925. }
  12926. // Because formatting using c++ streams is stateful, drop down to C is required
  12927. // Alternatively we could use stringstream, but its performance is... not good.
  12928. std::string getFormattedDuration( double duration ) {
  12929. // Max exponent + 1 is required to represent the whole part
  12930. // + 1 for decimal point
  12931. // + 3 for the 3 decimal places
  12932. // + 1 for null terminator
  12933. const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1;
  12934. char buffer[maxDoubleSize];
  12935. // Save previous errno, to prevent sprintf from overwriting it
  12936. ErrnoGuard guard;
  12937. #ifdef _MSC_VER
  12938. sprintf_s(buffer, "%.3f", duration);
  12939. #else
  12940. std::sprintf(buffer, "%.3f", duration);
  12941. #endif
  12942. return std::string(buffer);
  12943. }
  12944. bool shouldShowDuration( IConfig const& config, double duration ) {
  12945. if ( config.showDurations() == ShowDurations::Always ) {
  12946. return true;
  12947. }
  12948. if ( config.showDurations() == ShowDurations::Never ) {
  12949. return false;
  12950. }
  12951. const double min = config.minDuration();
  12952. return min >= 0 && duration >= min;
  12953. }
  12954. std::string serializeFilters( std::vector<std::string> const& container ) {
  12955. ReusableStringStream oss;
  12956. bool first = true;
  12957. for (auto&& filter : container)
  12958. {
  12959. if (!first)
  12960. oss << ' ';
  12961. else
  12962. first = false;
  12963. oss << filter;
  12964. }
  12965. return oss.str();
  12966. }
  12967. TestEventListenerBase::TestEventListenerBase(ReporterConfig const & _config)
  12968. :StreamingReporterBase(_config) {}
  12969. std::set<Verbosity> TestEventListenerBase::getSupportedVerbosities() {
  12970. return { Verbosity::Quiet, Verbosity::Normal, Verbosity::High };
  12971. }
  12972. void TestEventListenerBase::assertionStarting(AssertionInfo const &) {}
  12973. bool TestEventListenerBase::assertionEnded(AssertionStats const &) {
  12974. return false;
  12975. }
  12976. } // end namespace Catch
  12977. // end catch_reporter_bases.cpp
  12978. // start catch_reporter_compact.cpp
  12979. namespace {
  12980. #ifdef CATCH_PLATFORM_MAC
  12981. const char* failedString() { return "FAILED"; }
  12982. const char* passedString() { return "PASSED"; }
  12983. #else
  12984. const char* failedString() { return "failed"; }
  12985. const char* passedString() { return "passed"; }
  12986. #endif
  12987. // Colour::LightGrey
  12988. Catch::Colour::Code dimColour() { return Catch::Colour::FileName; }
  12989. std::string bothOrAll( std::size_t count ) {
  12990. return count == 1 ? std::string() :
  12991. count == 2 ? "both " : "all " ;
  12992. }
  12993. } // anon namespace
  12994. namespace Catch {
  12995. namespace {
  12996. // Colour, message variants:
  12997. // - white: No tests ran.
  12998. // - red: Failed [both/all] N test cases, failed [both/all] M assertions.
  12999. // - white: Passed [both/all] N test cases (no assertions).
  13000. // - red: Failed N tests cases, failed M assertions.
  13001. // - green: Passed [both/all] N tests cases with M assertions.
  13002. void printTotals(std::ostream& out, const Totals& totals) {
  13003. if (totals.testCases.total() == 0) {
  13004. out << "No tests ran.";
  13005. } else if (totals.testCases.failed == totals.testCases.total()) {
  13006. Colour colour(Colour::ResultError);
  13007. const std::string qualify_assertions_failed =
  13008. totals.assertions.failed == totals.assertions.total() ?
  13009. bothOrAll(totals.assertions.failed) : std::string();
  13010. out <<
  13011. "Failed " << bothOrAll(totals.testCases.failed)
  13012. << pluralise(totals.testCases.failed, "test case") << ", "
  13013. "failed " << qualify_assertions_failed <<
  13014. pluralise(totals.assertions.failed, "assertion") << '.';
  13015. } else if (totals.assertions.total() == 0) {
  13016. out <<
  13017. "Passed " << bothOrAll(totals.testCases.total())
  13018. << pluralise(totals.testCases.total(), "test case")
  13019. << " (no assertions).";
  13020. } else if (totals.assertions.failed) {
  13021. Colour colour(Colour::ResultError);
  13022. out <<
  13023. "Failed " << pluralise(totals.testCases.failed, "test case") << ", "
  13024. "failed " << pluralise(totals.assertions.failed, "assertion") << '.';
  13025. } else {
  13026. Colour colour(Colour::ResultSuccess);
  13027. out <<
  13028. "Passed " << bothOrAll(totals.testCases.passed)
  13029. << pluralise(totals.testCases.passed, "test case") <<
  13030. " with " << pluralise(totals.assertions.passed, "assertion") << '.';
  13031. }
  13032. }
  13033. // Implementation of CompactReporter formatting
  13034. class AssertionPrinter {
  13035. public:
  13036. AssertionPrinter& operator= (AssertionPrinter const&) = delete;
  13037. AssertionPrinter(AssertionPrinter const&) = delete;
  13038. AssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
  13039. : stream(_stream)
  13040. , result(_stats.assertionResult)
  13041. , messages(_stats.infoMessages)
  13042. , itMessage(_stats.infoMessages.begin())
  13043. , printInfoMessages(_printInfoMessages) {}
  13044. void print() {
  13045. printSourceInfo();
  13046. itMessage = messages.begin();
  13047. switch (result.getResultType()) {
  13048. case ResultWas::Ok:
  13049. printResultType(Colour::ResultSuccess, passedString());
  13050. printOriginalExpression();
  13051. printReconstructedExpression();
  13052. if (!result.hasExpression())
  13053. printRemainingMessages(Colour::None);
  13054. else
  13055. printRemainingMessages();
  13056. break;
  13057. case ResultWas::ExpressionFailed:
  13058. if (result.isOk())
  13059. printResultType(Colour::ResultSuccess, failedString() + std::string(" - but was ok"));
  13060. else
  13061. printResultType(Colour::Error, failedString());
  13062. printOriginalExpression();
  13063. printReconstructedExpression();
  13064. printRemainingMessages();
  13065. break;
  13066. case ResultWas::ThrewException:
  13067. printResultType(Colour::Error, failedString());
  13068. printIssue("unexpected exception with message:");
  13069. printMessage();
  13070. printExpressionWas();
  13071. printRemainingMessages();
  13072. break;
  13073. case ResultWas::FatalErrorCondition:
  13074. printResultType(Colour::Error, failedString());
  13075. printIssue("fatal error condition with message:");
  13076. printMessage();
  13077. printExpressionWas();
  13078. printRemainingMessages();
  13079. break;
  13080. case ResultWas::DidntThrowException:
  13081. printResultType(Colour::Error, failedString());
  13082. printIssue("expected exception, got none");
  13083. printExpressionWas();
  13084. printRemainingMessages();
  13085. break;
  13086. case ResultWas::Info:
  13087. printResultType(Colour::None, "info");
  13088. printMessage();
  13089. printRemainingMessages();
  13090. break;
  13091. case ResultWas::Warning:
  13092. printResultType(Colour::None, "warning");
  13093. printMessage();
  13094. printRemainingMessages();
  13095. break;
  13096. case ResultWas::ExplicitFailure:
  13097. printResultType(Colour::Error, failedString());
  13098. printIssue("explicitly");
  13099. printRemainingMessages(Colour::None);
  13100. break;
  13101. // These cases are here to prevent compiler warnings
  13102. case ResultWas::Unknown:
  13103. case ResultWas::FailureBit:
  13104. case ResultWas::Exception:
  13105. printResultType(Colour::Error, "** internal error **");
  13106. break;
  13107. }
  13108. }
  13109. private:
  13110. void printSourceInfo() const {
  13111. Colour colourGuard(Colour::FileName);
  13112. stream << result.getSourceInfo() << ':';
  13113. }
  13114. void printResultType(Colour::Code colour, std::string const& passOrFail) const {
  13115. if (!passOrFail.empty()) {
  13116. {
  13117. Colour colourGuard(colour);
  13118. stream << ' ' << passOrFail;
  13119. }
  13120. stream << ':';
  13121. }
  13122. }
  13123. void printIssue(std::string const& issue) const {
  13124. stream << ' ' << issue;
  13125. }
  13126. void printExpressionWas() {
  13127. if (result.hasExpression()) {
  13128. stream << ';';
  13129. {
  13130. Colour colour(dimColour());
  13131. stream << " expression was:";
  13132. }
  13133. printOriginalExpression();
  13134. }
  13135. }
  13136. void printOriginalExpression() const {
  13137. if (result.hasExpression()) {
  13138. stream << ' ' << result.getExpression();
  13139. }
  13140. }
  13141. void printReconstructedExpression() const {
  13142. if (result.hasExpandedExpression()) {
  13143. {
  13144. Colour colour(dimColour());
  13145. stream << " for: ";
  13146. }
  13147. stream << result.getExpandedExpression();
  13148. }
  13149. }
  13150. void printMessage() {
  13151. if (itMessage != messages.end()) {
  13152. stream << " '" << itMessage->message << '\'';
  13153. ++itMessage;
  13154. }
  13155. }
  13156. void printRemainingMessages(Colour::Code colour = dimColour()) {
  13157. if (itMessage == messages.end())
  13158. return;
  13159. const auto itEnd = messages.cend();
  13160. const auto N = static_cast<std::size_t>(std::distance(itMessage, itEnd));
  13161. {
  13162. Colour colourGuard(colour);
  13163. stream << " with " << pluralise(N, "message") << ':';
  13164. }
  13165. while (itMessage != itEnd) {
  13166. // If this assertion is a warning ignore any INFO messages
  13167. if (printInfoMessages || itMessage->type != ResultWas::Info) {
  13168. printMessage();
  13169. if (itMessage != itEnd) {
  13170. Colour colourGuard(dimColour());
  13171. stream << " and";
  13172. }
  13173. continue;
  13174. }
  13175. ++itMessage;
  13176. }
  13177. }
  13178. private:
  13179. std::ostream& stream;
  13180. AssertionResult const& result;
  13181. std::vector<MessageInfo> messages;
  13182. std::vector<MessageInfo>::const_iterator itMessage;
  13183. bool printInfoMessages;
  13184. };
  13185. } // anon namespace
  13186. std::string CompactReporter::getDescription() {
  13187. return "Reports test results on a single line, suitable for IDEs";
  13188. }
  13189. void CompactReporter::noMatchingTestCases( std::string const& spec ) {
  13190. stream << "No test cases matched '" << spec << '\'' << std::endl;
  13191. }
  13192. void CompactReporter::assertionStarting( AssertionInfo const& ) {}
  13193. bool CompactReporter::assertionEnded( AssertionStats const& _assertionStats ) {
  13194. AssertionResult const& result = _assertionStats.assertionResult;
  13195. bool printInfoMessages = true;
  13196. // Drop out if result was successful and we're not printing those
  13197. if( !m_config->includeSuccessfulResults() && result.isOk() ) {
  13198. if( result.getResultType() != ResultWas::Warning )
  13199. return false;
  13200. printInfoMessages = false;
  13201. }
  13202. AssertionPrinter printer( stream, _assertionStats, printInfoMessages );
  13203. printer.print();
  13204. stream << std::endl;
  13205. return true;
  13206. }
  13207. void CompactReporter::sectionEnded(SectionStats const& _sectionStats) {
  13208. double dur = _sectionStats.durationInSeconds;
  13209. if ( shouldShowDuration( *m_config, dur ) ) {
  13210. stream << getFormattedDuration( dur ) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  13211. }
  13212. }
  13213. void CompactReporter::testRunEnded( TestRunStats const& _testRunStats ) {
  13214. printTotals( stream, _testRunStats.totals );
  13215. stream << '\n' << std::endl;
  13216. StreamingReporterBase::testRunEnded( _testRunStats );
  13217. }
  13218. CompactReporter::~CompactReporter() {}
  13219. CATCH_REGISTER_REPORTER( "compact", CompactReporter )
  13220. } // end namespace Catch
  13221. // end catch_reporter_compact.cpp
  13222. // start catch_reporter_console.cpp
  13223. #include <cfloat>
  13224. #include <cstdio>
  13225. #if defined(_MSC_VER)
  13226. #pragma warning(push)
  13227. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  13228. // Note that 4062 (not all labels are handled and default is missing) is enabled
  13229. #endif
  13230. #if defined(__clang__)
  13231. # pragma clang diagnostic push
  13232. // For simplicity, benchmarking-only helpers are always enabled
  13233. # pragma clang diagnostic ignored "-Wunused-function"
  13234. #endif
  13235. namespace Catch {
  13236. namespace {
  13237. // Formatter impl for ConsoleReporter
  13238. class ConsoleAssertionPrinter {
  13239. public:
  13240. ConsoleAssertionPrinter& operator= (ConsoleAssertionPrinter const&) = delete;
  13241. ConsoleAssertionPrinter(ConsoleAssertionPrinter const&) = delete;
  13242. ConsoleAssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
  13243. : stream(_stream),
  13244. stats(_stats),
  13245. result(_stats.assertionResult),
  13246. colour(Colour::None),
  13247. message(result.getMessage()),
  13248. messages(_stats.infoMessages),
  13249. printInfoMessages(_printInfoMessages) {
  13250. switch (result.getResultType()) {
  13251. case ResultWas::Ok:
  13252. colour = Colour::Success;
  13253. passOrFail = "PASSED";
  13254. //if( result.hasMessage() )
  13255. if (_stats.infoMessages.size() == 1)
  13256. messageLabel = "with message";
  13257. if (_stats.infoMessages.size() > 1)
  13258. messageLabel = "with messages";
  13259. break;
  13260. case ResultWas::ExpressionFailed:
  13261. if (result.isOk()) {
  13262. colour = Colour::Success;
  13263. passOrFail = "FAILED - but was ok";
  13264. } else {
  13265. colour = Colour::Error;
  13266. passOrFail = "FAILED";
  13267. }
  13268. if (_stats.infoMessages.size() == 1)
  13269. messageLabel = "with message";
  13270. if (_stats.infoMessages.size() > 1)
  13271. messageLabel = "with messages";
  13272. break;
  13273. case ResultWas::ThrewException:
  13274. colour = Colour::Error;
  13275. passOrFail = "FAILED";
  13276. messageLabel = "due to unexpected exception with ";
  13277. if (_stats.infoMessages.size() == 1)
  13278. messageLabel += "message";
  13279. if (_stats.infoMessages.size() > 1)
  13280. messageLabel += "messages";
  13281. break;
  13282. case ResultWas::FatalErrorCondition:
  13283. colour = Colour::Error;
  13284. passOrFail = "FAILED";
  13285. messageLabel = "due to a fatal error condition";
  13286. break;
  13287. case ResultWas::DidntThrowException:
  13288. colour = Colour::Error;
  13289. passOrFail = "FAILED";
  13290. messageLabel = "because no exception was thrown where one was expected";
  13291. break;
  13292. case ResultWas::Info:
  13293. messageLabel = "info";
  13294. break;
  13295. case ResultWas::Warning:
  13296. messageLabel = "warning";
  13297. break;
  13298. case ResultWas::ExplicitFailure:
  13299. passOrFail = "FAILED";
  13300. colour = Colour::Error;
  13301. if (_stats.infoMessages.size() == 1)
  13302. messageLabel = "explicitly with message";
  13303. if (_stats.infoMessages.size() > 1)
  13304. messageLabel = "explicitly with messages";
  13305. break;
  13306. // These cases are here to prevent compiler warnings
  13307. case ResultWas::Unknown:
  13308. case ResultWas::FailureBit:
  13309. case ResultWas::Exception:
  13310. passOrFail = "** internal error **";
  13311. colour = Colour::Error;
  13312. break;
  13313. }
  13314. }
  13315. void print() const {
  13316. printSourceInfo();
  13317. if (stats.totals.assertions.total() > 0) {
  13318. printResultType();
  13319. printOriginalExpression();
  13320. printReconstructedExpression();
  13321. } else {
  13322. stream << '\n';
  13323. }
  13324. printMessage();
  13325. }
  13326. private:
  13327. void printResultType() const {
  13328. if (!passOrFail.empty()) {
  13329. Colour colourGuard(colour);
  13330. stream << passOrFail << ":\n";
  13331. }
  13332. }
  13333. void printOriginalExpression() const {
  13334. if (result.hasExpression()) {
  13335. Colour colourGuard(Colour::OriginalExpression);
  13336. stream << " ";
  13337. stream << result.getExpressionInMacro();
  13338. stream << '\n';
  13339. }
  13340. }
  13341. void printReconstructedExpression() const {
  13342. if (result.hasExpandedExpression()) {
  13343. stream << "with expansion:\n";
  13344. Colour colourGuard(Colour::ReconstructedExpression);
  13345. stream << Column(result.getExpandedExpression()).indent(2) << '\n';
  13346. }
  13347. }
  13348. void printMessage() const {
  13349. if (!messageLabel.empty())
  13350. stream << messageLabel << ':' << '\n';
  13351. for (auto const& msg : messages) {
  13352. // If this assertion is a warning ignore any INFO messages
  13353. if (printInfoMessages || msg.type != ResultWas::Info)
  13354. stream << Column(msg.message).indent(2) << '\n';
  13355. }
  13356. }
  13357. void printSourceInfo() const {
  13358. Colour colourGuard(Colour::FileName);
  13359. stream << result.getSourceInfo() << ": ";
  13360. }
  13361. std::ostream& stream;
  13362. AssertionStats const& stats;
  13363. AssertionResult const& result;
  13364. Colour::Code colour;
  13365. std::string passOrFail;
  13366. std::string messageLabel;
  13367. std::string message;
  13368. std::vector<MessageInfo> messages;
  13369. bool printInfoMessages;
  13370. };
  13371. std::size_t makeRatio(std::size_t number, std::size_t total) {
  13372. std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0;
  13373. return (ratio == 0 && number > 0) ? 1 : ratio;
  13374. }
  13375. std::size_t& findMax(std::size_t& i, std::size_t& j, std::size_t& k) {
  13376. if (i > j && i > k)
  13377. return i;
  13378. else if (j > k)
  13379. return j;
  13380. else
  13381. return k;
  13382. }
  13383. struct ColumnInfo {
  13384. enum Justification { Left, Right };
  13385. std::string name;
  13386. int width;
  13387. Justification justification;
  13388. };
  13389. struct ColumnBreak {};
  13390. struct RowBreak {};
  13391. class Duration {
  13392. enum class Unit {
  13393. Auto,
  13394. Nanoseconds,
  13395. Microseconds,
  13396. Milliseconds,
  13397. Seconds,
  13398. Minutes
  13399. };
  13400. static const uint64_t s_nanosecondsInAMicrosecond = 1000;
  13401. static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond;
  13402. static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond;
  13403. static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond;
  13404. double m_inNanoseconds;
  13405. Unit m_units;
  13406. public:
  13407. explicit Duration(double inNanoseconds, Unit units = Unit::Auto)
  13408. : m_inNanoseconds(inNanoseconds),
  13409. m_units(units) {
  13410. if (m_units == Unit::Auto) {
  13411. if (m_inNanoseconds < s_nanosecondsInAMicrosecond)
  13412. m_units = Unit::Nanoseconds;
  13413. else if (m_inNanoseconds < s_nanosecondsInAMillisecond)
  13414. m_units = Unit::Microseconds;
  13415. else if (m_inNanoseconds < s_nanosecondsInASecond)
  13416. m_units = Unit::Milliseconds;
  13417. else if (m_inNanoseconds < s_nanosecondsInAMinute)
  13418. m_units = Unit::Seconds;
  13419. else
  13420. m_units = Unit::Minutes;
  13421. }
  13422. }
  13423. auto value() const -> double {
  13424. switch (m_units) {
  13425. case Unit::Microseconds:
  13426. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMicrosecond);
  13427. case Unit::Milliseconds:
  13428. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMillisecond);
  13429. case Unit::Seconds:
  13430. return m_inNanoseconds / static_cast<double>(s_nanosecondsInASecond);
  13431. case Unit::Minutes:
  13432. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMinute);
  13433. default:
  13434. return m_inNanoseconds;
  13435. }
  13436. }
  13437. auto unitsAsString() const -> std::string {
  13438. switch (m_units) {
  13439. case Unit::Nanoseconds:
  13440. return "ns";
  13441. case Unit::Microseconds:
  13442. return "us";
  13443. case Unit::Milliseconds:
  13444. return "ms";
  13445. case Unit::Seconds:
  13446. return "s";
  13447. case Unit::Minutes:
  13448. return "m";
  13449. default:
  13450. return "** internal error **";
  13451. }
  13452. }
  13453. friend auto operator << (std::ostream& os, Duration const& duration) -> std::ostream& {
  13454. return os << duration.value() << ' ' << duration.unitsAsString();
  13455. }
  13456. };
  13457. } // end anon namespace
  13458. class TablePrinter {
  13459. std::ostream& m_os;
  13460. std::vector<ColumnInfo> m_columnInfos;
  13461. std::ostringstream m_oss;
  13462. int m_currentColumn = -1;
  13463. bool m_isOpen = false;
  13464. public:
  13465. TablePrinter( std::ostream& os, std::vector<ColumnInfo> columnInfos )
  13466. : m_os( os ),
  13467. m_columnInfos( std::move( columnInfos ) ) {}
  13468. auto columnInfos() const -> std::vector<ColumnInfo> const& {
  13469. return m_columnInfos;
  13470. }
  13471. void open() {
  13472. if (!m_isOpen) {
  13473. m_isOpen = true;
  13474. *this << RowBreak();
  13475. Columns headerCols;
  13476. Spacer spacer(2);
  13477. for (auto const& info : m_columnInfos) {
  13478. headerCols += Column(info.name).width(static_cast<std::size_t>(info.width - 2));
  13479. headerCols += spacer;
  13480. }
  13481. m_os << headerCols << '\n';
  13482. m_os << Catch::getLineOfChars<'-'>() << '\n';
  13483. }
  13484. }
  13485. void close() {
  13486. if (m_isOpen) {
  13487. *this << RowBreak();
  13488. m_os << std::endl;
  13489. m_isOpen = false;
  13490. }
  13491. }
  13492. template<typename T>
  13493. friend TablePrinter& operator << (TablePrinter& tp, T const& value) {
  13494. tp.m_oss << value;
  13495. return tp;
  13496. }
  13497. friend TablePrinter& operator << (TablePrinter& tp, ColumnBreak) {
  13498. auto colStr = tp.m_oss.str();
  13499. const auto strSize = colStr.size();
  13500. tp.m_oss.str("");
  13501. tp.open();
  13502. if (tp.m_currentColumn == static_cast<int>(tp.m_columnInfos.size() - 1)) {
  13503. tp.m_currentColumn = -1;
  13504. tp.m_os << '\n';
  13505. }
  13506. tp.m_currentColumn++;
  13507. auto colInfo = tp.m_columnInfos[tp.m_currentColumn];
  13508. auto padding = (strSize + 1 < static_cast<std::size_t>(colInfo.width))
  13509. ? std::string(colInfo.width - (strSize + 1), ' ')
  13510. : std::string();
  13511. if (colInfo.justification == ColumnInfo::Left)
  13512. tp.m_os << colStr << padding << ' ';
  13513. else
  13514. tp.m_os << padding << colStr << ' ';
  13515. return tp;
  13516. }
  13517. friend TablePrinter& operator << (TablePrinter& tp, RowBreak) {
  13518. if (tp.m_currentColumn > 0) {
  13519. tp.m_os << '\n';
  13520. tp.m_currentColumn = -1;
  13521. }
  13522. return tp;
  13523. }
  13524. };
  13525. ConsoleReporter::ConsoleReporter(ReporterConfig const& config)
  13526. : StreamingReporterBase(config),
  13527. m_tablePrinter(new TablePrinter(config.stream(),
  13528. [&config]() -> std::vector<ColumnInfo> {
  13529. if (config.fullConfig()->benchmarkNoAnalysis())
  13530. {
  13531. return{
  13532. { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, ColumnInfo::Left },
  13533. { " samples", 14, ColumnInfo::Right },
  13534. { " iterations", 14, ColumnInfo::Right },
  13535. { " mean", 14, ColumnInfo::Right }
  13536. };
  13537. }
  13538. else
  13539. {
  13540. return{
  13541. { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, ColumnInfo::Left },
  13542. { "samples mean std dev", 14, ColumnInfo::Right },
  13543. { "iterations low mean low std dev", 14, ColumnInfo::Right },
  13544. { "estimated high mean high std dev", 14, ColumnInfo::Right }
  13545. };
  13546. }
  13547. }())) {}
  13548. ConsoleReporter::~ConsoleReporter() = default;
  13549. std::string ConsoleReporter::getDescription() {
  13550. return "Reports test results as plain lines of text";
  13551. }
  13552. void ConsoleReporter::noMatchingTestCases(std::string const& spec) {
  13553. stream << "No test cases matched '" << spec << '\'' << std::endl;
  13554. }
  13555. void ConsoleReporter::reportInvalidArguments(std::string const&arg){
  13556. stream << "Invalid Filter: " << arg << std::endl;
  13557. }
  13558. void ConsoleReporter::assertionStarting(AssertionInfo const&) {}
  13559. bool ConsoleReporter::assertionEnded(AssertionStats const& _assertionStats) {
  13560. AssertionResult const& result = _assertionStats.assertionResult;
  13561. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  13562. // Drop out if result was successful but we're not printing them.
  13563. if (!includeResults && result.getResultType() != ResultWas::Warning)
  13564. return false;
  13565. lazyPrint();
  13566. ConsoleAssertionPrinter printer(stream, _assertionStats, includeResults);
  13567. printer.print();
  13568. stream << std::endl;
  13569. return true;
  13570. }
  13571. void ConsoleReporter::sectionStarting(SectionInfo const& _sectionInfo) {
  13572. m_tablePrinter->close();
  13573. m_headerPrinted = false;
  13574. StreamingReporterBase::sectionStarting(_sectionInfo);
  13575. }
  13576. void ConsoleReporter::sectionEnded(SectionStats const& _sectionStats) {
  13577. m_tablePrinter->close();
  13578. if (_sectionStats.missingAssertions) {
  13579. lazyPrint();
  13580. Colour colour(Colour::ResultError);
  13581. if (m_sectionStack.size() > 1)
  13582. stream << "\nNo assertions in section";
  13583. else
  13584. stream << "\nNo assertions in test case";
  13585. stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl;
  13586. }
  13587. double dur = _sectionStats.durationInSeconds;
  13588. if (shouldShowDuration(*m_config, dur)) {
  13589. stream << getFormattedDuration(dur) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  13590. }
  13591. if (m_headerPrinted) {
  13592. m_headerPrinted = false;
  13593. }
  13594. StreamingReporterBase::sectionEnded(_sectionStats);
  13595. }
  13596. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  13597. void ConsoleReporter::benchmarkPreparing(std::string const& name) {
  13598. lazyPrintWithoutClosingBenchmarkTable();
  13599. auto nameCol = Column(name).width(static_cast<std::size_t>(m_tablePrinter->columnInfos()[0].width - 2));
  13600. bool firstLine = true;
  13601. for (auto line : nameCol) {
  13602. if (!firstLine)
  13603. (*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak();
  13604. else
  13605. firstLine = false;
  13606. (*m_tablePrinter) << line << ColumnBreak();
  13607. }
  13608. }
  13609. void ConsoleReporter::benchmarkStarting(BenchmarkInfo const& info) {
  13610. (*m_tablePrinter) << info.samples << ColumnBreak()
  13611. << info.iterations << ColumnBreak();
  13612. if (!m_config->benchmarkNoAnalysis())
  13613. (*m_tablePrinter) << Duration(info.estimatedDuration) << ColumnBreak();
  13614. }
  13615. void ConsoleReporter::benchmarkEnded(BenchmarkStats<> const& stats) {
  13616. if (m_config->benchmarkNoAnalysis())
  13617. {
  13618. (*m_tablePrinter) << Duration(stats.mean.point.count()) << ColumnBreak();
  13619. }
  13620. else
  13621. {
  13622. (*m_tablePrinter) << ColumnBreak()
  13623. << Duration(stats.mean.point.count()) << ColumnBreak()
  13624. << Duration(stats.mean.lower_bound.count()) << ColumnBreak()
  13625. << Duration(stats.mean.upper_bound.count()) << ColumnBreak() << ColumnBreak()
  13626. << Duration(stats.standardDeviation.point.count()) << ColumnBreak()
  13627. << Duration(stats.standardDeviation.lower_bound.count()) << ColumnBreak()
  13628. << Duration(stats.standardDeviation.upper_bound.count()) << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak();
  13629. }
  13630. }
  13631. void ConsoleReporter::benchmarkFailed(std::string const& error) {
  13632. Colour colour(Colour::Red);
  13633. (*m_tablePrinter)
  13634. << "Benchmark failed (" << error << ')'
  13635. << ColumnBreak() << RowBreak();
  13636. }
  13637. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  13638. void ConsoleReporter::testCaseEnded(TestCaseStats const& _testCaseStats) {
  13639. m_tablePrinter->close();
  13640. StreamingReporterBase::testCaseEnded(_testCaseStats);
  13641. m_headerPrinted = false;
  13642. }
  13643. void ConsoleReporter::testGroupEnded(TestGroupStats const& _testGroupStats) {
  13644. if (currentGroupInfo.used) {
  13645. printSummaryDivider();
  13646. stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n";
  13647. printTotals(_testGroupStats.totals);
  13648. stream << '\n' << std::endl;
  13649. }
  13650. StreamingReporterBase::testGroupEnded(_testGroupStats);
  13651. }
  13652. void ConsoleReporter::testRunEnded(TestRunStats const& _testRunStats) {
  13653. printTotalsDivider(_testRunStats.totals);
  13654. printTotals(_testRunStats.totals);
  13655. stream << std::endl;
  13656. StreamingReporterBase::testRunEnded(_testRunStats);
  13657. }
  13658. void ConsoleReporter::testRunStarting(TestRunInfo const& _testInfo) {
  13659. StreamingReporterBase::testRunStarting(_testInfo);
  13660. printTestFilters();
  13661. }
  13662. void ConsoleReporter::lazyPrint() {
  13663. m_tablePrinter->close();
  13664. lazyPrintWithoutClosingBenchmarkTable();
  13665. }
  13666. void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() {
  13667. if (!currentTestRunInfo.used)
  13668. lazyPrintRunInfo();
  13669. if (!currentGroupInfo.used)
  13670. lazyPrintGroupInfo();
  13671. if (!m_headerPrinted) {
  13672. printTestCaseAndSectionHeader();
  13673. m_headerPrinted = true;
  13674. }
  13675. }
  13676. void ConsoleReporter::lazyPrintRunInfo() {
  13677. stream << '\n' << getLineOfChars<'~'>() << '\n';
  13678. Colour colour(Colour::SecondaryText);
  13679. stream << currentTestRunInfo->name
  13680. << " is a Catch v" << libraryVersion() << " host application.\n"
  13681. << "Run with -? for options\n\n";
  13682. if (m_config->rngSeed() != 0)
  13683. stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n";
  13684. currentTestRunInfo.used = true;
  13685. }
  13686. void ConsoleReporter::lazyPrintGroupInfo() {
  13687. if (!currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1) {
  13688. printClosedHeader("Group: " + currentGroupInfo->name);
  13689. currentGroupInfo.used = true;
  13690. }
  13691. }
  13692. void ConsoleReporter::printTestCaseAndSectionHeader() {
  13693. assert(!m_sectionStack.empty());
  13694. printOpenHeader(currentTestCaseInfo->name);
  13695. if (m_sectionStack.size() > 1) {
  13696. Colour colourGuard(Colour::Headers);
  13697. auto
  13698. it = m_sectionStack.begin() + 1, // Skip first section (test case)
  13699. itEnd = m_sectionStack.end();
  13700. for (; it != itEnd; ++it)
  13701. printHeaderString(it->name, 2);
  13702. }
  13703. SourceLineInfo lineInfo = m_sectionStack.back().lineInfo;
  13704. stream << getLineOfChars<'-'>() << '\n';
  13705. Colour colourGuard(Colour::FileName);
  13706. stream << lineInfo << '\n';
  13707. stream << getLineOfChars<'.'>() << '\n' << std::endl;
  13708. }
  13709. void ConsoleReporter::printClosedHeader(std::string const& _name) {
  13710. printOpenHeader(_name);
  13711. stream << getLineOfChars<'.'>() << '\n';
  13712. }
  13713. void ConsoleReporter::printOpenHeader(std::string const& _name) {
  13714. stream << getLineOfChars<'-'>() << '\n';
  13715. {
  13716. Colour colourGuard(Colour::Headers);
  13717. printHeaderString(_name);
  13718. }
  13719. }
  13720. // if string has a : in first line will set indent to follow it on
  13721. // subsequent lines
  13722. void ConsoleReporter::printHeaderString(std::string const& _string, std::size_t indent) {
  13723. std::size_t i = _string.find(": ");
  13724. if (i != std::string::npos)
  13725. i += 2;
  13726. else
  13727. i = 0;
  13728. stream << Column(_string).indent(indent + i).initialIndent(indent) << '\n';
  13729. }
  13730. struct SummaryColumn {
  13731. SummaryColumn( std::string _label, Colour::Code _colour )
  13732. : label( std::move( _label ) ),
  13733. colour( _colour ) {}
  13734. SummaryColumn addRow( std::size_t count ) {
  13735. ReusableStringStream rss;
  13736. rss << count;
  13737. std::string row = rss.str();
  13738. for (auto& oldRow : rows) {
  13739. while (oldRow.size() < row.size())
  13740. oldRow = ' ' + oldRow;
  13741. while (oldRow.size() > row.size())
  13742. row = ' ' + row;
  13743. }
  13744. rows.push_back(row);
  13745. return *this;
  13746. }
  13747. std::string label;
  13748. Colour::Code colour;
  13749. std::vector<std::string> rows;
  13750. };
  13751. void ConsoleReporter::printTotals( Totals const& totals ) {
  13752. if (totals.testCases.total() == 0) {
  13753. stream << Colour(Colour::Warning) << "No tests ran\n";
  13754. } else if (totals.assertions.total() > 0 && totals.testCases.allPassed()) {
  13755. stream << Colour(Colour::ResultSuccess) << "All tests passed";
  13756. stream << " ("
  13757. << pluralise(totals.assertions.passed, "assertion") << " in "
  13758. << pluralise(totals.testCases.passed, "test case") << ')'
  13759. << '\n';
  13760. } else {
  13761. std::vector<SummaryColumn> columns;
  13762. columns.push_back(SummaryColumn("", Colour::None)
  13763. .addRow(totals.testCases.total())
  13764. .addRow(totals.assertions.total()));
  13765. columns.push_back(SummaryColumn("passed", Colour::Success)
  13766. .addRow(totals.testCases.passed)
  13767. .addRow(totals.assertions.passed));
  13768. columns.push_back(SummaryColumn("failed", Colour::ResultError)
  13769. .addRow(totals.testCases.failed)
  13770. .addRow(totals.assertions.failed));
  13771. columns.push_back(SummaryColumn("failed as expected", Colour::ResultExpectedFailure)
  13772. .addRow(totals.testCases.failedButOk)
  13773. .addRow(totals.assertions.failedButOk));
  13774. printSummaryRow("test cases", columns, 0);
  13775. printSummaryRow("assertions", columns, 1);
  13776. }
  13777. }
  13778. void ConsoleReporter::printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row) {
  13779. for (auto col : cols) {
  13780. std::string value = col.rows[row];
  13781. if (col.label.empty()) {
  13782. stream << label << ": ";
  13783. if (value != "0")
  13784. stream << value;
  13785. else
  13786. stream << Colour(Colour::Warning) << "- none -";
  13787. } else if (value != "0") {
  13788. stream << Colour(Colour::LightGrey) << " | ";
  13789. stream << Colour(col.colour)
  13790. << value << ' ' << col.label;
  13791. }
  13792. }
  13793. stream << '\n';
  13794. }
  13795. void ConsoleReporter::printTotalsDivider(Totals const& totals) {
  13796. if (totals.testCases.total() > 0) {
  13797. std::size_t failedRatio = makeRatio(totals.testCases.failed, totals.testCases.total());
  13798. std::size_t failedButOkRatio = makeRatio(totals.testCases.failedButOk, totals.testCases.total());
  13799. std::size_t passedRatio = makeRatio(totals.testCases.passed, totals.testCases.total());
  13800. while (failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1)
  13801. findMax(failedRatio, failedButOkRatio, passedRatio)++;
  13802. while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1)
  13803. findMax(failedRatio, failedButOkRatio, passedRatio)--;
  13804. stream << Colour(Colour::Error) << std::string(failedRatio, '=');
  13805. stream << Colour(Colour::ResultExpectedFailure) << std::string(failedButOkRatio, '=');
  13806. if (totals.testCases.allPassed())
  13807. stream << Colour(Colour::ResultSuccess) << std::string(passedRatio, '=');
  13808. else
  13809. stream << Colour(Colour::Success) << std::string(passedRatio, '=');
  13810. } else {
  13811. stream << Colour(Colour::Warning) << std::string(CATCH_CONFIG_CONSOLE_WIDTH - 1, '=');
  13812. }
  13813. stream << '\n';
  13814. }
  13815. void ConsoleReporter::printSummaryDivider() {
  13816. stream << getLineOfChars<'-'>() << '\n';
  13817. }
  13818. void ConsoleReporter::printTestFilters() {
  13819. if (m_config->testSpec().hasFilters()) {
  13820. Colour guard(Colour::BrightYellow);
  13821. stream << "Filters: " << serializeFilters(m_config->getTestsOrTags()) << '\n';
  13822. }
  13823. }
  13824. CATCH_REGISTER_REPORTER("console", ConsoleReporter)
  13825. } // end namespace Catch
  13826. #if defined(_MSC_VER)
  13827. #pragma warning(pop)
  13828. #endif
  13829. #if defined(__clang__)
  13830. # pragma clang diagnostic pop
  13831. #endif
  13832. // end catch_reporter_console.cpp
  13833. // start catch_reporter_junit.cpp
  13834. #include <cassert>
  13835. #include <sstream>
  13836. #include <ctime>
  13837. #include <algorithm>
  13838. namespace Catch {
  13839. namespace {
  13840. std::string getCurrentTimestamp() {
  13841. // Beware, this is not reentrant because of backward compatibility issues
  13842. // Also, UTC only, again because of backward compatibility (%z is C++11)
  13843. time_t rawtime;
  13844. std::time(&rawtime);
  13845. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  13846. #ifdef _MSC_VER
  13847. std::tm timeInfo = {};
  13848. gmtime_s(&timeInfo, &rawtime);
  13849. #else
  13850. std::tm* timeInfo;
  13851. timeInfo = std::gmtime(&rawtime);
  13852. #endif
  13853. char timeStamp[timeStampSize];
  13854. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  13855. #ifdef _MSC_VER
  13856. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  13857. #else
  13858. std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
  13859. #endif
  13860. return std::string(timeStamp);
  13861. }
  13862. std::string fileNameTag(const std::vector<std::string> &tags) {
  13863. auto it = std::find_if(begin(tags),
  13864. end(tags),
  13865. [] (std::string const& tag) {return tag.front() == '#'; });
  13866. if (it != tags.end())
  13867. return it->substr(1);
  13868. return std::string();
  13869. }
  13870. } // anonymous namespace
  13871. JunitReporter::JunitReporter( ReporterConfig const& _config )
  13872. : CumulativeReporterBase( _config ),
  13873. xml( _config.stream() )
  13874. {
  13875. m_reporterPrefs.shouldRedirectStdOut = true;
  13876. m_reporterPrefs.shouldReportAllAssertions = true;
  13877. }
  13878. JunitReporter::~JunitReporter() {}
  13879. std::string JunitReporter::getDescription() {
  13880. return "Reports test results in an XML format that looks like Ant's junitreport target";
  13881. }
  13882. void JunitReporter::noMatchingTestCases( std::string const& /*spec*/ ) {}
  13883. void JunitReporter::testRunStarting( TestRunInfo const& runInfo ) {
  13884. CumulativeReporterBase::testRunStarting( runInfo );
  13885. xml.startElement( "testsuites" );
  13886. }
  13887. void JunitReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  13888. suiteTimer.start();
  13889. stdOutForSuite.clear();
  13890. stdErrForSuite.clear();
  13891. unexpectedExceptions = 0;
  13892. CumulativeReporterBase::testGroupStarting( groupInfo );
  13893. }
  13894. void JunitReporter::testCaseStarting( TestCaseInfo const& testCaseInfo ) {
  13895. m_okToFail = testCaseInfo.okToFail();
  13896. }
  13897. bool JunitReporter::assertionEnded( AssertionStats const& assertionStats ) {
  13898. if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail )
  13899. unexpectedExceptions++;
  13900. return CumulativeReporterBase::assertionEnded( assertionStats );
  13901. }
  13902. void JunitReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  13903. stdOutForSuite += testCaseStats.stdOut;
  13904. stdErrForSuite += testCaseStats.stdErr;
  13905. CumulativeReporterBase::testCaseEnded( testCaseStats );
  13906. }
  13907. void JunitReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  13908. double suiteTime = suiteTimer.getElapsedSeconds();
  13909. CumulativeReporterBase::testGroupEnded( testGroupStats );
  13910. writeGroup( *m_testGroups.back(), suiteTime );
  13911. }
  13912. void JunitReporter::testRunEndedCumulative() {
  13913. xml.endElement();
  13914. }
  13915. void JunitReporter::writeGroup( TestGroupNode const& groupNode, double suiteTime ) {
  13916. XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" );
  13917. TestGroupStats const& stats = groupNode.value;
  13918. xml.writeAttribute( "name", stats.groupInfo.name );
  13919. xml.writeAttribute( "errors", unexpectedExceptions );
  13920. xml.writeAttribute( "failures", stats.totals.assertions.failed-unexpectedExceptions );
  13921. xml.writeAttribute( "tests", stats.totals.assertions.total() );
  13922. xml.writeAttribute( "hostname", "tbd" ); // !TBD
  13923. if( m_config->showDurations() == ShowDurations::Never )
  13924. xml.writeAttribute( "time", "" );
  13925. else
  13926. xml.writeAttribute( "time", suiteTime );
  13927. xml.writeAttribute( "timestamp", getCurrentTimestamp() );
  13928. // Write properties if there are any
  13929. if (m_config->hasTestFilters() || m_config->rngSeed() != 0) {
  13930. auto properties = xml.scopedElement("properties");
  13931. if (m_config->hasTestFilters()) {
  13932. xml.scopedElement("property")
  13933. .writeAttribute("name", "filters")
  13934. .writeAttribute("value", serializeFilters(m_config->getTestsOrTags()));
  13935. }
  13936. if (m_config->rngSeed() != 0) {
  13937. xml.scopedElement("property")
  13938. .writeAttribute("name", "random-seed")
  13939. .writeAttribute("value", m_config->rngSeed());
  13940. }
  13941. }
  13942. // Write test cases
  13943. for( auto const& child : groupNode.children )
  13944. writeTestCase( *child );
  13945. xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite ), XmlFormatting::Newline );
  13946. xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite ), XmlFormatting::Newline );
  13947. }
  13948. void JunitReporter::writeTestCase( TestCaseNode const& testCaseNode ) {
  13949. TestCaseStats const& stats = testCaseNode.value;
  13950. // All test cases have exactly one section - which represents the
  13951. // test case itself. That section may have 0-n nested sections
  13952. assert( testCaseNode.children.size() == 1 );
  13953. SectionNode const& rootSection = *testCaseNode.children.front();
  13954. std::string className = stats.testInfo.className;
  13955. if( className.empty() ) {
  13956. className = fileNameTag(stats.testInfo.tags);
  13957. if ( className.empty() )
  13958. className = "global";
  13959. }
  13960. if ( !m_config->name().empty() )
  13961. className = m_config->name() + "." + className;
  13962. writeSection( className, "", rootSection );
  13963. }
  13964. void JunitReporter::writeSection( std::string const& className,
  13965. std::string const& rootName,
  13966. SectionNode const& sectionNode ) {
  13967. std::string name = trim( sectionNode.stats.sectionInfo.name );
  13968. if( !rootName.empty() )
  13969. name = rootName + '/' + name;
  13970. if( !sectionNode.assertions.empty() ||
  13971. !sectionNode.stdOut.empty() ||
  13972. !sectionNode.stdErr.empty() ) {
  13973. XmlWriter::ScopedElement e = xml.scopedElement( "testcase" );
  13974. if( className.empty() ) {
  13975. xml.writeAttribute( "classname", name );
  13976. xml.writeAttribute( "name", "root" );
  13977. }
  13978. else {
  13979. xml.writeAttribute( "classname", className );
  13980. xml.writeAttribute( "name", name );
  13981. }
  13982. xml.writeAttribute( "time", ::Catch::Detail::stringify( sectionNode.stats.durationInSeconds ) );
  13983. // This is not ideal, but it should be enough to mimic gtest's
  13984. // junit output.
  13985. // Ideally the JUnit reporter would also handle `skipTest`
  13986. // events and write those out appropriately.
  13987. xml.writeAttribute( "status", "run" );
  13988. writeAssertions( sectionNode );
  13989. if( !sectionNode.stdOut.empty() )
  13990. xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), XmlFormatting::Newline );
  13991. if( !sectionNode.stdErr.empty() )
  13992. xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), XmlFormatting::Newline );
  13993. }
  13994. for( auto const& childNode : sectionNode.childSections )
  13995. if( className.empty() )
  13996. writeSection( name, "", *childNode );
  13997. else
  13998. writeSection( className, name, *childNode );
  13999. }
  14000. void JunitReporter::writeAssertions( SectionNode const& sectionNode ) {
  14001. for( auto const& assertion : sectionNode.assertions )
  14002. writeAssertion( assertion );
  14003. }
  14004. void JunitReporter::writeAssertion( AssertionStats const& stats ) {
  14005. AssertionResult const& result = stats.assertionResult;
  14006. if( !result.isOk() ) {
  14007. std::string elementName;
  14008. switch( result.getResultType() ) {
  14009. case ResultWas::ThrewException:
  14010. case ResultWas::FatalErrorCondition:
  14011. elementName = "error";
  14012. break;
  14013. case ResultWas::ExplicitFailure:
  14014. case ResultWas::ExpressionFailed:
  14015. case ResultWas::DidntThrowException:
  14016. elementName = "failure";
  14017. break;
  14018. // We should never see these here:
  14019. case ResultWas::Info:
  14020. case ResultWas::Warning:
  14021. case ResultWas::Ok:
  14022. case ResultWas::Unknown:
  14023. case ResultWas::FailureBit:
  14024. case ResultWas::Exception:
  14025. elementName = "internalError";
  14026. break;
  14027. }
  14028. XmlWriter::ScopedElement e = xml.scopedElement( elementName );
  14029. xml.writeAttribute( "message", result.getExpression() );
  14030. xml.writeAttribute( "type", result.getTestMacroName() );
  14031. ReusableStringStream rss;
  14032. if (stats.totals.assertions.total() > 0) {
  14033. rss << "FAILED" << ":\n";
  14034. if (result.hasExpression()) {
  14035. rss << " ";
  14036. rss << result.getExpressionInMacro();
  14037. rss << '\n';
  14038. }
  14039. if (result.hasExpandedExpression()) {
  14040. rss << "with expansion:\n";
  14041. rss << Column(result.getExpandedExpression()).indent(2) << '\n';
  14042. }
  14043. } else {
  14044. rss << '\n';
  14045. }
  14046. if( !result.getMessage().empty() )
  14047. rss << result.getMessage() << '\n';
  14048. for( auto const& msg : stats.infoMessages )
  14049. if( msg.type == ResultWas::Info )
  14050. rss << msg.message << '\n';
  14051. rss << "at " << result.getSourceInfo();
  14052. xml.writeText( rss.str(), XmlFormatting::Newline );
  14053. }
  14054. }
  14055. CATCH_REGISTER_REPORTER( "junit", JunitReporter )
  14056. } // end namespace Catch
  14057. // end catch_reporter_junit.cpp
  14058. // start catch_reporter_listening.cpp
  14059. #include <cassert>
  14060. namespace Catch {
  14061. ListeningReporter::ListeningReporter() {
  14062. // We will assume that listeners will always want all assertions
  14063. m_preferences.shouldReportAllAssertions = true;
  14064. }
  14065. void ListeningReporter::addListener( IStreamingReporterPtr&& listener ) {
  14066. m_listeners.push_back( std::move( listener ) );
  14067. }
  14068. void ListeningReporter::addReporter(IStreamingReporterPtr&& reporter) {
  14069. assert(!m_reporter && "Listening reporter can wrap only 1 real reporter");
  14070. m_reporter = std::move( reporter );
  14071. m_preferences.shouldRedirectStdOut = m_reporter->getPreferences().shouldRedirectStdOut;
  14072. }
  14073. ReporterPreferences ListeningReporter::getPreferences() const {
  14074. return m_preferences;
  14075. }
  14076. std::set<Verbosity> ListeningReporter::getSupportedVerbosities() {
  14077. return std::set<Verbosity>{ };
  14078. }
  14079. void ListeningReporter::noMatchingTestCases( std::string const& spec ) {
  14080. for ( auto const& listener : m_listeners ) {
  14081. listener->noMatchingTestCases( spec );
  14082. }
  14083. m_reporter->noMatchingTestCases( spec );
  14084. }
  14085. void ListeningReporter::reportInvalidArguments(std::string const&arg){
  14086. for ( auto const& listener : m_listeners ) {
  14087. listener->reportInvalidArguments( arg );
  14088. }
  14089. m_reporter->reportInvalidArguments( arg );
  14090. }
  14091. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  14092. void ListeningReporter::benchmarkPreparing( std::string const& name ) {
  14093. for (auto const& listener : m_listeners) {
  14094. listener->benchmarkPreparing(name);
  14095. }
  14096. m_reporter->benchmarkPreparing(name);
  14097. }
  14098. void ListeningReporter::benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) {
  14099. for ( auto const& listener : m_listeners ) {
  14100. listener->benchmarkStarting( benchmarkInfo );
  14101. }
  14102. m_reporter->benchmarkStarting( benchmarkInfo );
  14103. }
  14104. void ListeningReporter::benchmarkEnded( BenchmarkStats<> const& benchmarkStats ) {
  14105. for ( auto const& listener : m_listeners ) {
  14106. listener->benchmarkEnded( benchmarkStats );
  14107. }
  14108. m_reporter->benchmarkEnded( benchmarkStats );
  14109. }
  14110. void ListeningReporter::benchmarkFailed( std::string const& error ) {
  14111. for (auto const& listener : m_listeners) {
  14112. listener->benchmarkFailed(error);
  14113. }
  14114. m_reporter->benchmarkFailed(error);
  14115. }
  14116. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  14117. void ListeningReporter::testRunStarting( TestRunInfo const& testRunInfo ) {
  14118. for ( auto const& listener : m_listeners ) {
  14119. listener->testRunStarting( testRunInfo );
  14120. }
  14121. m_reporter->testRunStarting( testRunInfo );
  14122. }
  14123. void ListeningReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  14124. for ( auto const& listener : m_listeners ) {
  14125. listener->testGroupStarting( groupInfo );
  14126. }
  14127. m_reporter->testGroupStarting( groupInfo );
  14128. }
  14129. void ListeningReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
  14130. for ( auto const& listener : m_listeners ) {
  14131. listener->testCaseStarting( testInfo );
  14132. }
  14133. m_reporter->testCaseStarting( testInfo );
  14134. }
  14135. void ListeningReporter::sectionStarting( SectionInfo const& sectionInfo ) {
  14136. for ( auto const& listener : m_listeners ) {
  14137. listener->sectionStarting( sectionInfo );
  14138. }
  14139. m_reporter->sectionStarting( sectionInfo );
  14140. }
  14141. void ListeningReporter::assertionStarting( AssertionInfo const& assertionInfo ) {
  14142. for ( auto const& listener : m_listeners ) {
  14143. listener->assertionStarting( assertionInfo );
  14144. }
  14145. m_reporter->assertionStarting( assertionInfo );
  14146. }
  14147. // The return value indicates if the messages buffer should be cleared:
  14148. bool ListeningReporter::assertionEnded( AssertionStats const& assertionStats ) {
  14149. for( auto const& listener : m_listeners ) {
  14150. static_cast<void>( listener->assertionEnded( assertionStats ) );
  14151. }
  14152. return m_reporter->assertionEnded( assertionStats );
  14153. }
  14154. void ListeningReporter::sectionEnded( SectionStats const& sectionStats ) {
  14155. for ( auto const& listener : m_listeners ) {
  14156. listener->sectionEnded( sectionStats );
  14157. }
  14158. m_reporter->sectionEnded( sectionStats );
  14159. }
  14160. void ListeningReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  14161. for ( auto const& listener : m_listeners ) {
  14162. listener->testCaseEnded( testCaseStats );
  14163. }
  14164. m_reporter->testCaseEnded( testCaseStats );
  14165. }
  14166. void ListeningReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  14167. for ( auto const& listener : m_listeners ) {
  14168. listener->testGroupEnded( testGroupStats );
  14169. }
  14170. m_reporter->testGroupEnded( testGroupStats );
  14171. }
  14172. void ListeningReporter::testRunEnded( TestRunStats const& testRunStats ) {
  14173. for ( auto const& listener : m_listeners ) {
  14174. listener->testRunEnded( testRunStats );
  14175. }
  14176. m_reporter->testRunEnded( testRunStats );
  14177. }
  14178. void ListeningReporter::skipTest( TestCaseInfo const& testInfo ) {
  14179. for ( auto const& listener : m_listeners ) {
  14180. listener->skipTest( testInfo );
  14181. }
  14182. m_reporter->skipTest( testInfo );
  14183. }
  14184. bool ListeningReporter::isMulti() const {
  14185. return true;
  14186. }
  14187. } // end namespace Catch
  14188. // end catch_reporter_listening.cpp
  14189. // start catch_reporter_xml.cpp
  14190. #if defined(_MSC_VER)
  14191. #pragma warning(push)
  14192. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  14193. // Note that 4062 (not all labels are handled
  14194. // and default is missing) is enabled
  14195. #endif
  14196. namespace Catch {
  14197. XmlReporter::XmlReporter( ReporterConfig const& _config )
  14198. : StreamingReporterBase( _config ),
  14199. m_xml(_config.stream())
  14200. {
  14201. m_reporterPrefs.shouldRedirectStdOut = true;
  14202. m_reporterPrefs.shouldReportAllAssertions = true;
  14203. }
  14204. XmlReporter::~XmlReporter() = default;
  14205. std::string XmlReporter::getDescription() {
  14206. return "Reports test results as an XML document";
  14207. }
  14208. std::string XmlReporter::getStylesheetRef() const {
  14209. return std::string();
  14210. }
  14211. void XmlReporter::writeSourceInfo( SourceLineInfo const& sourceInfo ) {
  14212. m_xml
  14213. .writeAttribute( "filename", sourceInfo.file )
  14214. .writeAttribute( "line", sourceInfo.line );
  14215. }
  14216. void XmlReporter::noMatchingTestCases( std::string const& s ) {
  14217. StreamingReporterBase::noMatchingTestCases( s );
  14218. }
  14219. void XmlReporter::testRunStarting( TestRunInfo const& testInfo ) {
  14220. StreamingReporterBase::testRunStarting( testInfo );
  14221. std::string stylesheetRef = getStylesheetRef();
  14222. if( !stylesheetRef.empty() )
  14223. m_xml.writeStylesheetRef( stylesheetRef );
  14224. m_xml.startElement( "Catch" );
  14225. if( !m_config->name().empty() )
  14226. m_xml.writeAttribute( "name", m_config->name() );
  14227. if (m_config->testSpec().hasFilters())
  14228. m_xml.writeAttribute( "filters", serializeFilters( m_config->getTestsOrTags() ) );
  14229. if( m_config->rngSeed() != 0 )
  14230. m_xml.scopedElement( "Randomness" )
  14231. .writeAttribute( "seed", m_config->rngSeed() );
  14232. }
  14233. void XmlReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  14234. StreamingReporterBase::testGroupStarting( groupInfo );
  14235. m_xml.startElement( "Group" )
  14236. .writeAttribute( "name", groupInfo.name );
  14237. }
  14238. void XmlReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
  14239. StreamingReporterBase::testCaseStarting(testInfo);
  14240. m_xml.startElement( "TestCase" )
  14241. .writeAttribute( "name", trim( testInfo.name ) )
  14242. .writeAttribute( "description", testInfo.description )
  14243. .writeAttribute( "tags", testInfo.tagsAsString() );
  14244. writeSourceInfo( testInfo.lineInfo );
  14245. if ( m_config->showDurations() == ShowDurations::Always )
  14246. m_testCaseTimer.start();
  14247. m_xml.ensureTagClosed();
  14248. }
  14249. void XmlReporter::sectionStarting( SectionInfo const& sectionInfo ) {
  14250. StreamingReporterBase::sectionStarting( sectionInfo );
  14251. if( m_sectionDepth++ > 0 ) {
  14252. m_xml.startElement( "Section" )
  14253. .writeAttribute( "name", trim( sectionInfo.name ) );
  14254. writeSourceInfo( sectionInfo.lineInfo );
  14255. m_xml.ensureTagClosed();
  14256. }
  14257. }
  14258. void XmlReporter::assertionStarting( AssertionInfo const& ) { }
  14259. bool XmlReporter::assertionEnded( AssertionStats const& assertionStats ) {
  14260. AssertionResult const& result = assertionStats.assertionResult;
  14261. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  14262. if( includeResults || result.getResultType() == ResultWas::Warning ) {
  14263. // Print any info messages in <Info> tags.
  14264. for( auto const& msg : assertionStats.infoMessages ) {
  14265. if( msg.type == ResultWas::Info && includeResults ) {
  14266. m_xml.scopedElement( "Info" )
  14267. .writeText( msg.message );
  14268. } else if ( msg.type == ResultWas::Warning ) {
  14269. m_xml.scopedElement( "Warning" )
  14270. .writeText( msg.message );
  14271. }
  14272. }
  14273. }
  14274. // Drop out if result was successful but we're not printing them.
  14275. if( !includeResults && result.getResultType() != ResultWas::Warning )
  14276. return true;
  14277. // Print the expression if there is one.
  14278. if( result.hasExpression() ) {
  14279. m_xml.startElement( "Expression" )
  14280. .writeAttribute( "success", result.succeeded() )
  14281. .writeAttribute( "type", result.getTestMacroName() );
  14282. writeSourceInfo( result.getSourceInfo() );
  14283. m_xml.scopedElement( "Original" )
  14284. .writeText( result.getExpression() );
  14285. m_xml.scopedElement( "Expanded" )
  14286. .writeText( result.getExpandedExpression() );
  14287. }
  14288. // And... Print a result applicable to each result type.
  14289. switch( result.getResultType() ) {
  14290. case ResultWas::ThrewException:
  14291. m_xml.startElement( "Exception" );
  14292. writeSourceInfo( result.getSourceInfo() );
  14293. m_xml.writeText( result.getMessage() );
  14294. m_xml.endElement();
  14295. break;
  14296. case ResultWas::FatalErrorCondition:
  14297. m_xml.startElement( "FatalErrorCondition" );
  14298. writeSourceInfo( result.getSourceInfo() );
  14299. m_xml.writeText( result.getMessage() );
  14300. m_xml.endElement();
  14301. break;
  14302. case ResultWas::Info:
  14303. m_xml.scopedElement( "Info" )
  14304. .writeText( result.getMessage() );
  14305. break;
  14306. case ResultWas::Warning:
  14307. // Warning will already have been written
  14308. break;
  14309. case ResultWas::ExplicitFailure:
  14310. m_xml.startElement( "Failure" );
  14311. writeSourceInfo( result.getSourceInfo() );
  14312. m_xml.writeText( result.getMessage() );
  14313. m_xml.endElement();
  14314. break;
  14315. default:
  14316. break;
  14317. }
  14318. if( result.hasExpression() )
  14319. m_xml.endElement();
  14320. return true;
  14321. }
  14322. void XmlReporter::sectionEnded( SectionStats const& sectionStats ) {
  14323. StreamingReporterBase::sectionEnded( sectionStats );
  14324. if( --m_sectionDepth > 0 ) {
  14325. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResults" );
  14326. e.writeAttribute( "successes", sectionStats.assertions.passed );
  14327. e.writeAttribute( "failures", sectionStats.assertions.failed );
  14328. e.writeAttribute( "expectedFailures", sectionStats.assertions.failedButOk );
  14329. if ( m_config->showDurations() == ShowDurations::Always )
  14330. e.writeAttribute( "durationInSeconds", sectionStats.durationInSeconds );
  14331. m_xml.endElement();
  14332. }
  14333. }
  14334. void XmlReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  14335. StreamingReporterBase::testCaseEnded( testCaseStats );
  14336. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResult" );
  14337. e.writeAttribute( "success", testCaseStats.totals.assertions.allOk() );
  14338. if ( m_config->showDurations() == ShowDurations::Always )
  14339. e.writeAttribute( "durationInSeconds", m_testCaseTimer.getElapsedSeconds() );
  14340. if( !testCaseStats.stdOut.empty() )
  14341. m_xml.scopedElement( "StdOut" ).writeText( trim( testCaseStats.stdOut ), XmlFormatting::Newline );
  14342. if( !testCaseStats.stdErr.empty() )
  14343. m_xml.scopedElement( "StdErr" ).writeText( trim( testCaseStats.stdErr ), XmlFormatting::Newline );
  14344. m_xml.endElement();
  14345. }
  14346. void XmlReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  14347. StreamingReporterBase::testGroupEnded( testGroupStats );
  14348. // TODO: Check testGroupStats.aborting and act accordingly.
  14349. m_xml.scopedElement( "OverallResults" )
  14350. .writeAttribute( "successes", testGroupStats.totals.assertions.passed )
  14351. .writeAttribute( "failures", testGroupStats.totals.assertions.failed )
  14352. .writeAttribute( "expectedFailures", testGroupStats.totals.assertions.failedButOk );
  14353. m_xml.scopedElement( "OverallResultsCases")
  14354. .writeAttribute( "successes", testGroupStats.totals.testCases.passed )
  14355. .writeAttribute( "failures", testGroupStats.totals.testCases.failed )
  14356. .writeAttribute( "expectedFailures", testGroupStats.totals.testCases.failedButOk );
  14357. m_xml.endElement();
  14358. }
  14359. void XmlReporter::testRunEnded( TestRunStats const& testRunStats ) {
  14360. StreamingReporterBase::testRunEnded( testRunStats );
  14361. m_xml.scopedElement( "OverallResults" )
  14362. .writeAttribute( "successes", testRunStats.totals.assertions.passed )
  14363. .writeAttribute( "failures", testRunStats.totals.assertions.failed )
  14364. .writeAttribute( "expectedFailures", testRunStats.totals.assertions.failedButOk );
  14365. m_xml.scopedElement( "OverallResultsCases")
  14366. .writeAttribute( "successes", testRunStats.totals.testCases.passed )
  14367. .writeAttribute( "failures", testRunStats.totals.testCases.failed )
  14368. .writeAttribute( "expectedFailures", testRunStats.totals.testCases.failedButOk );
  14369. m_xml.endElement();
  14370. }
  14371. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  14372. void XmlReporter::benchmarkPreparing(std::string const& name) {
  14373. m_xml.startElement("BenchmarkResults")
  14374. .writeAttribute("name", name);
  14375. }
  14376. void XmlReporter::benchmarkStarting(BenchmarkInfo const &info) {
  14377. m_xml.writeAttribute("samples", info.samples)
  14378. .writeAttribute("resamples", info.resamples)
  14379. .writeAttribute("iterations", info.iterations)
  14380. .writeAttribute("clockResolution", info.clockResolution)
  14381. .writeAttribute("estimatedDuration", info.estimatedDuration)
  14382. .writeComment("All values in nano seconds");
  14383. }
  14384. void XmlReporter::benchmarkEnded(BenchmarkStats<> const& benchmarkStats) {
  14385. m_xml.startElement("mean")
  14386. .writeAttribute("value", benchmarkStats.mean.point.count())
  14387. .writeAttribute("lowerBound", benchmarkStats.mean.lower_bound.count())
  14388. .writeAttribute("upperBound", benchmarkStats.mean.upper_bound.count())
  14389. .writeAttribute("ci", benchmarkStats.mean.confidence_interval);
  14390. m_xml.endElement();
  14391. m_xml.startElement("standardDeviation")
  14392. .writeAttribute("value", benchmarkStats.standardDeviation.point.count())
  14393. .writeAttribute("lowerBound", benchmarkStats.standardDeviation.lower_bound.count())
  14394. .writeAttribute("upperBound", benchmarkStats.standardDeviation.upper_bound.count())
  14395. .writeAttribute("ci", benchmarkStats.standardDeviation.confidence_interval);
  14396. m_xml.endElement();
  14397. m_xml.startElement("outliers")
  14398. .writeAttribute("variance", benchmarkStats.outlierVariance)
  14399. .writeAttribute("lowMild", benchmarkStats.outliers.low_mild)
  14400. .writeAttribute("lowSevere", benchmarkStats.outliers.low_severe)
  14401. .writeAttribute("highMild", benchmarkStats.outliers.high_mild)
  14402. .writeAttribute("highSevere", benchmarkStats.outliers.high_severe);
  14403. m_xml.endElement();
  14404. m_xml.endElement();
  14405. }
  14406. void XmlReporter::benchmarkFailed(std::string const &error) {
  14407. m_xml.scopedElement("failed").
  14408. writeAttribute("message", error);
  14409. m_xml.endElement();
  14410. }
  14411. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  14412. CATCH_REGISTER_REPORTER( "xml", XmlReporter )
  14413. } // end namespace Catch
  14414. #if defined(_MSC_VER)
  14415. #pragma warning(pop)
  14416. #endif
  14417. // end catch_reporter_xml.cpp
  14418. namespace Catch {
  14419. LeakDetector leakDetector;
  14420. }
  14421. #ifdef __clang__
  14422. #pragma clang diagnostic pop
  14423. #endif
  14424. // end catch_impl.hpp
  14425. #endif
  14426. #ifdef CATCH_CONFIG_MAIN
  14427. // start catch_default_main.hpp
  14428. #ifndef __OBJC__
  14429. #if defined(CATCH_CONFIG_WCHAR) && defined(CATCH_PLATFORM_WINDOWS) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN)
  14430. // Standard C/C++ Win32 Unicode wmain entry point
  14431. extern "C" int wmain (int argc, wchar_t * argv[], wchar_t * []) {
  14432. #else
  14433. // Standard C/C++ main entry point
  14434. int main (int argc, char * argv[]) {
  14435. #endif
  14436. return Catch::Session().run( argc, argv );
  14437. }
  14438. #else // __OBJC__
  14439. // Objective-C entry point
  14440. int main (int argc, char * const argv[]) {
  14441. #if !CATCH_ARC_ENABLED
  14442. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  14443. #endif
  14444. Catch::registerTestMethods();
  14445. int result = Catch::Session().run( argc, (char**)argv );
  14446. #if !CATCH_ARC_ENABLED
  14447. [pool drain];
  14448. #endif
  14449. return result;
  14450. }
  14451. #endif // __OBJC__
  14452. // end catch_default_main.hpp
  14453. #endif
  14454. #if !defined(CATCH_CONFIG_IMPL_ONLY)
  14455. #ifdef CLARA_CONFIG_MAIN_NOT_DEFINED
  14456. # undef CLARA_CONFIG_MAIN
  14457. #endif
  14458. #if !defined(CATCH_CONFIG_DISABLE)
  14459. //////
  14460. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  14461. #ifdef CATCH_CONFIG_PREFIX_ALL
  14462. #define CATCH_REQUIRE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  14463. #define CATCH_REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  14464. #define CATCH_REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  14465. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  14466. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  14467. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14468. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  14469. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  14470. #define CATCH_REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  14471. #define CATCH_CHECK( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14472. #define CATCH_CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  14473. #define CATCH_CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14474. #define CATCH_CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14475. #define CATCH_CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  14476. #define CATCH_CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14477. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  14478. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  14479. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14480. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  14481. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14482. #define CATCH_CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14483. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14484. #define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  14485. #define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  14486. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14487. #define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg )
  14488. #define CATCH_UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "CATCH_UNSCOPED_INFO", msg )
  14489. #define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  14490. #define CATCH_CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CATCH_CAPTURE",__VA_ARGS__ )
  14491. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  14492. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14493. #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  14494. #define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  14495. #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  14496. #define CATCH_DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
  14497. #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  14498. #define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14499. #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14500. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  14501. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  14502. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14503. #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ )
  14504. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14505. #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
  14506. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )
  14507. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ )
  14508. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14509. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
  14510. #else
  14511. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
  14512. #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) )
  14513. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  14514. #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
  14515. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )
  14516. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) )
  14517. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  14518. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
  14519. #endif
  14520. #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
  14521. #define CATCH_STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__ , #__VA_ARGS__ ); CATCH_SUCCEED( #__VA_ARGS__ )
  14522. #define CATCH_STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); CATCH_SUCCEED( #__VA_ARGS__ )
  14523. #else
  14524. #define CATCH_STATIC_REQUIRE( ... ) CATCH_REQUIRE( __VA_ARGS__ )
  14525. #define CATCH_STATIC_REQUIRE_FALSE( ... ) CATCH_REQUIRE_FALSE( __VA_ARGS__ )
  14526. #endif
  14527. // "BDD-style" convenience wrappers
  14528. #define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ )
  14529. #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  14530. #define CATCH_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
  14531. #define CATCH_AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
  14532. #define CATCH_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
  14533. #define CATCH_AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
  14534. #define CATCH_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
  14535. #define CATCH_AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
  14536. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  14537. #define CATCH_BENCHMARK(...) \
  14538. 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__,,))
  14539. #define CATCH_BENCHMARK_ADVANCED(name) \
  14540. INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), name)
  14541. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  14542. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  14543. #else
  14544. #define REQUIRE( ... ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  14545. #define REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  14546. #define REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  14547. #define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  14548. #define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  14549. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14550. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  14551. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14552. #define REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  14553. #define CHECK( ... ) INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14554. #define CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  14555. #define CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14556. #define CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14557. #define CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  14558. #define CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14559. #define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  14560. #define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  14561. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14562. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  14563. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14564. #define CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14565. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14566. #define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  14567. #define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  14568. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14569. #define INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg )
  14570. #define UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "UNSCOPED_INFO", msg )
  14571. #define WARN( msg ) INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  14572. #define CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CAPTURE",__VA_ARGS__ )
  14573. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  14574. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14575. #define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  14576. #define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  14577. #define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  14578. #define DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
  14579. #define FAIL( ... ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  14580. #define FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14581. #define SUCCEED( ... ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14582. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  14583. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  14584. #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14585. #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ )
  14586. #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14587. #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
  14588. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )
  14589. #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ )
  14590. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14591. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
  14592. #define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(__VA_ARGS__)
  14593. #define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14594. #else
  14595. #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
  14596. #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) )
  14597. #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  14598. #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
  14599. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )
  14600. #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) )
  14601. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  14602. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
  14603. #define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE( __VA_ARGS__ ) )
  14604. #define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  14605. #endif
  14606. #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
  14607. #define STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__, #__VA_ARGS__ ); SUCCEED( #__VA_ARGS__ )
  14608. #define STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); SUCCEED( "!(" #__VA_ARGS__ ")" )
  14609. #else
  14610. #define STATIC_REQUIRE( ... ) REQUIRE( __VA_ARGS__ )
  14611. #define STATIC_REQUIRE_FALSE( ... ) REQUIRE_FALSE( __VA_ARGS__ )
  14612. #endif
  14613. #endif
  14614. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature )
  14615. // "BDD-style" convenience wrappers
  14616. #define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ )
  14617. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  14618. #define GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
  14619. #define AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
  14620. #define WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
  14621. #define AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
  14622. #define THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
  14623. #define AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
  14624. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  14625. #define BENCHMARK(...) \
  14626. 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__,,))
  14627. #define BENCHMARK_ADVANCED(name) \
  14628. INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), name)
  14629. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  14630. using Catch::Detail::Approx;
  14631. #else // CATCH_CONFIG_DISABLE
  14632. //////
  14633. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  14634. #ifdef CATCH_CONFIG_PREFIX_ALL
  14635. #define CATCH_REQUIRE( ... ) (void)(0)
  14636. #define CATCH_REQUIRE_FALSE( ... ) (void)(0)
  14637. #define CATCH_REQUIRE_THROWS( ... ) (void)(0)
  14638. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  14639. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  14640. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14641. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  14642. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  14643. #define CATCH_REQUIRE_NOTHROW( ... ) (void)(0)
  14644. #define CATCH_CHECK( ... ) (void)(0)
  14645. #define CATCH_CHECK_FALSE( ... ) (void)(0)
  14646. #define CATCH_CHECKED_IF( ... ) if (__VA_ARGS__)
  14647. #define CATCH_CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  14648. #define CATCH_CHECK_NOFAIL( ... ) (void)(0)
  14649. #define CATCH_CHECK_THROWS( ... ) (void)(0)
  14650. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  14651. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  14652. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14653. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  14654. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14655. #define CATCH_CHECK_NOTHROW( ... ) (void)(0)
  14656. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14657. #define CATCH_CHECK_THAT( arg, matcher ) (void)(0)
  14658. #define CATCH_REQUIRE_THAT( arg, matcher ) (void)(0)
  14659. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14660. #define CATCH_INFO( msg ) (void)(0)
  14661. #define CATCH_UNSCOPED_INFO( msg ) (void)(0)
  14662. #define CATCH_WARN( msg ) (void)(0)
  14663. #define CATCH_CAPTURE( msg ) (void)(0)
  14664. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  14665. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  14666. #define CATCH_METHOD_AS_TEST_CASE( method, ... )
  14667. #define CATCH_REGISTER_TEST_CASE( Function, ... ) (void)(0)
  14668. #define CATCH_SECTION( ... )
  14669. #define CATCH_DYNAMIC_SECTION( ... )
  14670. #define CATCH_FAIL( ... ) (void)(0)
  14671. #define CATCH_FAIL_CHECK( ... ) (void)(0)
  14672. #define CATCH_SUCCEED( ... ) (void)(0)
  14673. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  14674. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  14675. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
  14676. #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
  14677. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
  14678. #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ )
  14679. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14680. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14681. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14682. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14683. #else
  14684. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) )
  14685. #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) )
  14686. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) )
  14687. #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) )
  14688. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14689. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14690. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14691. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14692. #endif
  14693. // "BDD-style" convenience wrappers
  14694. #define CATCH_SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  14695. #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 )
  14696. #define CATCH_GIVEN( desc )
  14697. #define CATCH_AND_GIVEN( desc )
  14698. #define CATCH_WHEN( desc )
  14699. #define CATCH_AND_WHEN( desc )
  14700. #define CATCH_THEN( desc )
  14701. #define CATCH_AND_THEN( desc )
  14702. #define CATCH_STATIC_REQUIRE( ... ) (void)(0)
  14703. #define CATCH_STATIC_REQUIRE_FALSE( ... ) (void)(0)
  14704. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  14705. #else
  14706. #define REQUIRE( ... ) (void)(0)
  14707. #define REQUIRE_FALSE( ... ) (void)(0)
  14708. #define REQUIRE_THROWS( ... ) (void)(0)
  14709. #define REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  14710. #define REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  14711. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14712. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  14713. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14714. #define REQUIRE_NOTHROW( ... ) (void)(0)
  14715. #define CHECK( ... ) (void)(0)
  14716. #define CHECK_FALSE( ... ) (void)(0)
  14717. #define CHECKED_IF( ... ) if (__VA_ARGS__)
  14718. #define CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  14719. #define CHECK_NOFAIL( ... ) (void)(0)
  14720. #define CHECK_THROWS( ... ) (void)(0)
  14721. #define CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  14722. #define CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  14723. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14724. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  14725. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14726. #define CHECK_NOTHROW( ... ) (void)(0)
  14727. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14728. #define CHECK_THAT( arg, matcher ) (void)(0)
  14729. #define REQUIRE_THAT( arg, matcher ) (void)(0)
  14730. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14731. #define INFO( msg ) (void)(0)
  14732. #define UNSCOPED_INFO( msg ) (void)(0)
  14733. #define WARN( msg ) (void)(0)
  14734. #define CAPTURE( msg ) (void)(0)
  14735. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  14736. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  14737. #define METHOD_AS_TEST_CASE( method, ... )
  14738. #define REGISTER_TEST_CASE( Function, ... ) (void)(0)
  14739. #define SECTION( ... )
  14740. #define DYNAMIC_SECTION( ... )
  14741. #define FAIL( ... ) (void)(0)
  14742. #define FAIL_CHECK( ... ) (void)(0)
  14743. #define SUCCEED( ... ) (void)(0)
  14744. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  14745. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  14746. #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
  14747. #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
  14748. #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
  14749. #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ )
  14750. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14751. #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14752. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14753. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14754. #else
  14755. #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) )
  14756. #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) )
  14757. #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) )
  14758. #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) )
  14759. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14760. #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14761. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14762. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14763. #endif
  14764. #define STATIC_REQUIRE( ... ) (void)(0)
  14765. #define STATIC_REQUIRE_FALSE( ... ) (void)(0)
  14766. #endif
  14767. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
  14768. // "BDD-style" convenience wrappers
  14769. #define SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) )
  14770. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className )
  14771. #define GIVEN( desc )
  14772. #define AND_GIVEN( desc )
  14773. #define WHEN( desc )
  14774. #define AND_WHEN( desc )
  14775. #define THEN( desc )
  14776. #define AND_THEN( desc )
  14777. using Catch::Detail::Approx;
  14778. #endif
  14779. #endif // ! CATCH_CONFIG_IMPL_ONLY
  14780. // start catch_reenable_warnings.h
  14781. #ifdef __clang__
  14782. # ifdef __ICC // icpc defines the __clang__ macro
  14783. # pragma warning(pop)
  14784. # else
  14785. # pragma clang diagnostic pop
  14786. # endif
  14787. #elif defined __GNUC__
  14788. # pragma GCC diagnostic pop
  14789. #endif
  14790. // end catch_reenable_warnings.h
  14791. // end catch.hpp
  14792. #endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED