catch.hpp 642 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960
  1. /*
  2. * Catch v2.13.7
  3. * Generated: 2021-07-28 20:29:27.753164
  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 7
  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 defined(__cpp_lib_byte) && (__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. #include <iterator>
  4503. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  4504. #include <string>
  4505. #include <iosfwd>
  4506. #include <map>
  4507. #include <set>
  4508. #include <memory>
  4509. #include <algorithm>
  4510. namespace Catch {
  4511. struct ReporterConfig {
  4512. explicit ReporterConfig( IConfigPtr const& _fullConfig );
  4513. ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream );
  4514. std::ostream& stream() const;
  4515. IConfigPtr fullConfig() const;
  4516. private:
  4517. std::ostream* m_stream;
  4518. IConfigPtr m_fullConfig;
  4519. };
  4520. struct ReporterPreferences {
  4521. bool shouldRedirectStdOut = false;
  4522. bool shouldReportAllAssertions = false;
  4523. };
  4524. template<typename T>
  4525. struct LazyStat : Option<T> {
  4526. LazyStat& operator=( T const& _value ) {
  4527. Option<T>::operator=( _value );
  4528. used = false;
  4529. return *this;
  4530. }
  4531. void reset() {
  4532. Option<T>::reset();
  4533. used = false;
  4534. }
  4535. bool used = false;
  4536. };
  4537. struct TestRunInfo {
  4538. TestRunInfo( std::string const& _name );
  4539. std::string name;
  4540. };
  4541. struct GroupInfo {
  4542. GroupInfo( std::string const& _name,
  4543. std::size_t _groupIndex,
  4544. std::size_t _groupsCount );
  4545. std::string name;
  4546. std::size_t groupIndex;
  4547. std::size_t groupsCounts;
  4548. };
  4549. struct AssertionStats {
  4550. AssertionStats( AssertionResult const& _assertionResult,
  4551. std::vector<MessageInfo> const& _infoMessages,
  4552. Totals const& _totals );
  4553. AssertionStats( AssertionStats const& ) = default;
  4554. AssertionStats( AssertionStats && ) = default;
  4555. AssertionStats& operator = ( AssertionStats const& ) = delete;
  4556. AssertionStats& operator = ( AssertionStats && ) = delete;
  4557. virtual ~AssertionStats();
  4558. AssertionResult assertionResult;
  4559. std::vector<MessageInfo> infoMessages;
  4560. Totals totals;
  4561. };
  4562. struct SectionStats {
  4563. SectionStats( SectionInfo const& _sectionInfo,
  4564. Counts const& _assertions,
  4565. double _durationInSeconds,
  4566. bool _missingAssertions );
  4567. SectionStats( SectionStats const& ) = default;
  4568. SectionStats( SectionStats && ) = default;
  4569. SectionStats& operator = ( SectionStats const& ) = default;
  4570. SectionStats& operator = ( SectionStats && ) = default;
  4571. virtual ~SectionStats();
  4572. SectionInfo sectionInfo;
  4573. Counts assertions;
  4574. double durationInSeconds;
  4575. bool missingAssertions;
  4576. };
  4577. struct TestCaseStats {
  4578. TestCaseStats( TestCaseInfo const& _testInfo,
  4579. Totals const& _totals,
  4580. std::string const& _stdOut,
  4581. std::string const& _stdErr,
  4582. bool _aborting );
  4583. TestCaseStats( TestCaseStats const& ) = default;
  4584. TestCaseStats( TestCaseStats && ) = default;
  4585. TestCaseStats& operator = ( TestCaseStats const& ) = default;
  4586. TestCaseStats& operator = ( TestCaseStats && ) = default;
  4587. virtual ~TestCaseStats();
  4588. TestCaseInfo testInfo;
  4589. Totals totals;
  4590. std::string stdOut;
  4591. std::string stdErr;
  4592. bool aborting;
  4593. };
  4594. struct TestGroupStats {
  4595. TestGroupStats( GroupInfo const& _groupInfo,
  4596. Totals const& _totals,
  4597. bool _aborting );
  4598. TestGroupStats( GroupInfo const& _groupInfo );
  4599. TestGroupStats( TestGroupStats const& ) = default;
  4600. TestGroupStats( TestGroupStats && ) = default;
  4601. TestGroupStats& operator = ( TestGroupStats const& ) = default;
  4602. TestGroupStats& operator = ( TestGroupStats && ) = default;
  4603. virtual ~TestGroupStats();
  4604. GroupInfo groupInfo;
  4605. Totals totals;
  4606. bool aborting;
  4607. };
  4608. struct TestRunStats {
  4609. TestRunStats( TestRunInfo const& _runInfo,
  4610. Totals const& _totals,
  4611. bool _aborting );
  4612. TestRunStats( TestRunStats const& ) = default;
  4613. TestRunStats( TestRunStats && ) = default;
  4614. TestRunStats& operator = ( TestRunStats const& ) = default;
  4615. TestRunStats& operator = ( TestRunStats && ) = default;
  4616. virtual ~TestRunStats();
  4617. TestRunInfo runInfo;
  4618. Totals totals;
  4619. bool aborting;
  4620. };
  4621. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  4622. struct BenchmarkInfo {
  4623. std::string name;
  4624. double estimatedDuration;
  4625. int iterations;
  4626. int samples;
  4627. unsigned int resamples;
  4628. double clockResolution;
  4629. double clockCost;
  4630. };
  4631. template <class Duration>
  4632. struct BenchmarkStats {
  4633. BenchmarkInfo info;
  4634. std::vector<Duration> samples;
  4635. Benchmark::Estimate<Duration> mean;
  4636. Benchmark::Estimate<Duration> standardDeviation;
  4637. Benchmark::OutlierClassification outliers;
  4638. double outlierVariance;
  4639. template <typename Duration2>
  4640. operator BenchmarkStats<Duration2>() const {
  4641. std::vector<Duration2> samples2;
  4642. samples2.reserve(samples.size());
  4643. std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration d) { return Duration2(d); });
  4644. return {
  4645. info,
  4646. std::move(samples2),
  4647. mean,
  4648. standardDeviation,
  4649. outliers,
  4650. outlierVariance,
  4651. };
  4652. }
  4653. };
  4654. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  4655. struct IStreamingReporter {
  4656. virtual ~IStreamingReporter() = default;
  4657. // Implementing class must also provide the following static methods:
  4658. // static std::string getDescription();
  4659. // static std::set<Verbosity> getSupportedVerbosities()
  4660. virtual ReporterPreferences getPreferences() const = 0;
  4661. virtual void noMatchingTestCases( std::string const& spec ) = 0;
  4662. virtual void reportInvalidArguments(std::string const&) {}
  4663. virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0;
  4664. virtual void testGroupStarting( GroupInfo const& groupInfo ) = 0;
  4665. virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0;
  4666. virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0;
  4667. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  4668. virtual void benchmarkPreparing( std::string const& ) {}
  4669. virtual void benchmarkStarting( BenchmarkInfo const& ) {}
  4670. virtual void benchmarkEnded( BenchmarkStats<> const& ) {}
  4671. virtual void benchmarkFailed( std::string const& ) {}
  4672. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  4673. virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0;
  4674. // The return value indicates if the messages buffer should be cleared:
  4675. virtual bool assertionEnded( AssertionStats const& assertionStats ) = 0;
  4676. virtual void sectionEnded( SectionStats const& sectionStats ) = 0;
  4677. virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0;
  4678. virtual void testGroupEnded( TestGroupStats const& testGroupStats ) = 0;
  4679. virtual void testRunEnded( TestRunStats const& testRunStats ) = 0;
  4680. virtual void skipTest( TestCaseInfo const& testInfo ) = 0;
  4681. // Default empty implementation provided
  4682. virtual void fatalErrorEncountered( StringRef name );
  4683. virtual bool isMulti() const;
  4684. };
  4685. using IStreamingReporterPtr = std::unique_ptr<IStreamingReporter>;
  4686. struct IReporterFactory {
  4687. virtual ~IReporterFactory();
  4688. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const = 0;
  4689. virtual std::string getDescription() const = 0;
  4690. };
  4691. using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
  4692. struct IReporterRegistry {
  4693. using FactoryMap = std::map<std::string, IReporterFactoryPtr>;
  4694. using Listeners = std::vector<IReporterFactoryPtr>;
  4695. virtual ~IReporterRegistry();
  4696. virtual IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const = 0;
  4697. virtual FactoryMap const& getFactories() const = 0;
  4698. virtual Listeners const& getListeners() const = 0;
  4699. };
  4700. } // end namespace Catch
  4701. // end catch_interfaces_reporter.h
  4702. #include <algorithm>
  4703. #include <cstring>
  4704. #include <cfloat>
  4705. #include <cstdio>
  4706. #include <cassert>
  4707. #include <memory>
  4708. #include <ostream>
  4709. namespace Catch {
  4710. void prepareExpandedExpression(AssertionResult& result);
  4711. // Returns double formatted as %.3f (format expected on output)
  4712. std::string getFormattedDuration( double duration );
  4713. //! Should the reporter show
  4714. bool shouldShowDuration( IConfig const& config, double duration );
  4715. std::string serializeFilters( std::vector<std::string> const& container );
  4716. template<typename DerivedT>
  4717. struct StreamingReporterBase : IStreamingReporter {
  4718. StreamingReporterBase( ReporterConfig const& _config )
  4719. : m_config( _config.fullConfig() ),
  4720. stream( _config.stream() )
  4721. {
  4722. m_reporterPrefs.shouldRedirectStdOut = false;
  4723. if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
  4724. CATCH_ERROR( "Verbosity level not supported by this reporter" );
  4725. }
  4726. ReporterPreferences getPreferences() const override {
  4727. return m_reporterPrefs;
  4728. }
  4729. static std::set<Verbosity> getSupportedVerbosities() {
  4730. return { Verbosity::Normal };
  4731. }
  4732. ~StreamingReporterBase() override = default;
  4733. void noMatchingTestCases(std::string const&) override {}
  4734. void reportInvalidArguments(std::string const&) override {}
  4735. void testRunStarting(TestRunInfo const& _testRunInfo) override {
  4736. currentTestRunInfo = _testRunInfo;
  4737. }
  4738. void testGroupStarting(GroupInfo const& _groupInfo) override {
  4739. currentGroupInfo = _groupInfo;
  4740. }
  4741. void testCaseStarting(TestCaseInfo const& _testInfo) override {
  4742. currentTestCaseInfo = _testInfo;
  4743. }
  4744. void sectionStarting(SectionInfo const& _sectionInfo) override {
  4745. m_sectionStack.push_back(_sectionInfo);
  4746. }
  4747. void sectionEnded(SectionStats const& /* _sectionStats */) override {
  4748. m_sectionStack.pop_back();
  4749. }
  4750. void testCaseEnded(TestCaseStats const& /* _testCaseStats */) override {
  4751. currentTestCaseInfo.reset();
  4752. }
  4753. void testGroupEnded(TestGroupStats const& /* _testGroupStats */) override {
  4754. currentGroupInfo.reset();
  4755. }
  4756. void testRunEnded(TestRunStats const& /* _testRunStats */) override {
  4757. currentTestCaseInfo.reset();
  4758. currentGroupInfo.reset();
  4759. currentTestRunInfo.reset();
  4760. }
  4761. void skipTest(TestCaseInfo const&) override {
  4762. // Don't do anything with this by default.
  4763. // It can optionally be overridden in the derived class.
  4764. }
  4765. IConfigPtr m_config;
  4766. std::ostream& stream;
  4767. LazyStat<TestRunInfo> currentTestRunInfo;
  4768. LazyStat<GroupInfo> currentGroupInfo;
  4769. LazyStat<TestCaseInfo> currentTestCaseInfo;
  4770. std::vector<SectionInfo> m_sectionStack;
  4771. ReporterPreferences m_reporterPrefs;
  4772. };
  4773. template<typename DerivedT>
  4774. struct CumulativeReporterBase : IStreamingReporter {
  4775. template<typename T, typename ChildNodeT>
  4776. struct Node {
  4777. explicit Node( T const& _value ) : value( _value ) {}
  4778. virtual ~Node() {}
  4779. using ChildNodes = std::vector<std::shared_ptr<ChildNodeT>>;
  4780. T value;
  4781. ChildNodes children;
  4782. };
  4783. struct SectionNode {
  4784. explicit SectionNode(SectionStats const& _stats) : stats(_stats) {}
  4785. virtual ~SectionNode() = default;
  4786. bool operator == (SectionNode const& other) const {
  4787. return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;
  4788. }
  4789. bool operator == (std::shared_ptr<SectionNode> const& other) const {
  4790. return operator==(*other);
  4791. }
  4792. SectionStats stats;
  4793. using ChildSections = std::vector<std::shared_ptr<SectionNode>>;
  4794. using Assertions = std::vector<AssertionStats>;
  4795. ChildSections childSections;
  4796. Assertions assertions;
  4797. std::string stdOut;
  4798. std::string stdErr;
  4799. };
  4800. struct BySectionInfo {
  4801. BySectionInfo( SectionInfo const& other ) : m_other( other ) {}
  4802. BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {}
  4803. bool operator() (std::shared_ptr<SectionNode> const& node) const {
  4804. return ((node->stats.sectionInfo.name == m_other.name) &&
  4805. (node->stats.sectionInfo.lineInfo == m_other.lineInfo));
  4806. }
  4807. void operator=(BySectionInfo const&) = delete;
  4808. private:
  4809. SectionInfo const& m_other;
  4810. };
  4811. using TestCaseNode = Node<TestCaseStats, SectionNode>;
  4812. using TestGroupNode = Node<TestGroupStats, TestCaseNode>;
  4813. using TestRunNode = Node<TestRunStats, TestGroupNode>;
  4814. CumulativeReporterBase( ReporterConfig const& _config )
  4815. : m_config( _config.fullConfig() ),
  4816. stream( _config.stream() )
  4817. {
  4818. m_reporterPrefs.shouldRedirectStdOut = false;
  4819. if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
  4820. CATCH_ERROR( "Verbosity level not supported by this reporter" );
  4821. }
  4822. ~CumulativeReporterBase() override = default;
  4823. ReporterPreferences getPreferences() const override {
  4824. return m_reporterPrefs;
  4825. }
  4826. static std::set<Verbosity> getSupportedVerbosities() {
  4827. return { Verbosity::Normal };
  4828. }
  4829. void testRunStarting( TestRunInfo const& ) override {}
  4830. void testGroupStarting( GroupInfo const& ) override {}
  4831. void testCaseStarting( TestCaseInfo const& ) override {}
  4832. void sectionStarting( SectionInfo const& sectionInfo ) override {
  4833. SectionStats incompleteStats( sectionInfo, Counts(), 0, false );
  4834. std::shared_ptr<SectionNode> node;
  4835. if( m_sectionStack.empty() ) {
  4836. if( !m_rootSection )
  4837. m_rootSection = std::make_shared<SectionNode>( incompleteStats );
  4838. node = m_rootSection;
  4839. }
  4840. else {
  4841. SectionNode& parentNode = *m_sectionStack.back();
  4842. auto it =
  4843. std::find_if( parentNode.childSections.begin(),
  4844. parentNode.childSections.end(),
  4845. BySectionInfo( sectionInfo ) );
  4846. if( it == parentNode.childSections.end() ) {
  4847. node = std::make_shared<SectionNode>( incompleteStats );
  4848. parentNode.childSections.push_back( node );
  4849. }
  4850. else
  4851. node = *it;
  4852. }
  4853. m_sectionStack.push_back( node );
  4854. m_deepestSection = std::move(node);
  4855. }
  4856. void assertionStarting(AssertionInfo const&) override {}
  4857. bool assertionEnded(AssertionStats const& assertionStats) override {
  4858. assert(!m_sectionStack.empty());
  4859. // AssertionResult holds a pointer to a temporary DecomposedExpression,
  4860. // which getExpandedExpression() calls to build the expression string.
  4861. // Our section stack copy of the assertionResult will likely outlive the
  4862. // temporary, so it must be expanded or discarded now to avoid calling
  4863. // a destroyed object later.
  4864. prepareExpandedExpression(const_cast<AssertionResult&>( assertionStats.assertionResult ) );
  4865. SectionNode& sectionNode = *m_sectionStack.back();
  4866. sectionNode.assertions.push_back(assertionStats);
  4867. return true;
  4868. }
  4869. void sectionEnded(SectionStats const& sectionStats) override {
  4870. assert(!m_sectionStack.empty());
  4871. SectionNode& node = *m_sectionStack.back();
  4872. node.stats = sectionStats;
  4873. m_sectionStack.pop_back();
  4874. }
  4875. void testCaseEnded(TestCaseStats const& testCaseStats) override {
  4876. auto node = std::make_shared<TestCaseNode>(testCaseStats);
  4877. assert(m_sectionStack.size() == 0);
  4878. node->children.push_back(m_rootSection);
  4879. m_testCases.push_back(node);
  4880. m_rootSection.reset();
  4881. assert(m_deepestSection);
  4882. m_deepestSection->stdOut = testCaseStats.stdOut;
  4883. m_deepestSection->stdErr = testCaseStats.stdErr;
  4884. }
  4885. void testGroupEnded(TestGroupStats const& testGroupStats) override {
  4886. auto node = std::make_shared<TestGroupNode>(testGroupStats);
  4887. node->children.swap(m_testCases);
  4888. m_testGroups.push_back(node);
  4889. }
  4890. void testRunEnded(TestRunStats const& testRunStats) override {
  4891. auto node = std::make_shared<TestRunNode>(testRunStats);
  4892. node->children.swap(m_testGroups);
  4893. m_testRuns.push_back(node);
  4894. testRunEndedCumulative();
  4895. }
  4896. virtual void testRunEndedCumulative() = 0;
  4897. void skipTest(TestCaseInfo const&) override {}
  4898. IConfigPtr m_config;
  4899. std::ostream& stream;
  4900. std::vector<AssertionStats> m_assertions;
  4901. std::vector<std::vector<std::shared_ptr<SectionNode>>> m_sections;
  4902. std::vector<std::shared_ptr<TestCaseNode>> m_testCases;
  4903. std::vector<std::shared_ptr<TestGroupNode>> m_testGroups;
  4904. std::vector<std::shared_ptr<TestRunNode>> m_testRuns;
  4905. std::shared_ptr<SectionNode> m_rootSection;
  4906. std::shared_ptr<SectionNode> m_deepestSection;
  4907. std::vector<std::shared_ptr<SectionNode>> m_sectionStack;
  4908. ReporterPreferences m_reporterPrefs;
  4909. };
  4910. template<char C>
  4911. char const* getLineOfChars() {
  4912. static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
  4913. if( !*line ) {
  4914. std::memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 );
  4915. line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0;
  4916. }
  4917. return line;
  4918. }
  4919. struct TestEventListenerBase : StreamingReporterBase<TestEventListenerBase> {
  4920. TestEventListenerBase( ReporterConfig const& _config );
  4921. static std::set<Verbosity> getSupportedVerbosities();
  4922. void assertionStarting(AssertionInfo const&) override;
  4923. bool assertionEnded(AssertionStats const&) override;
  4924. };
  4925. } // end namespace Catch
  4926. // end catch_reporter_bases.hpp
  4927. // start catch_console_colour.h
  4928. namespace Catch {
  4929. struct Colour {
  4930. enum Code {
  4931. None = 0,
  4932. White,
  4933. Red,
  4934. Green,
  4935. Blue,
  4936. Cyan,
  4937. Yellow,
  4938. Grey,
  4939. Bright = 0x10,
  4940. BrightRed = Bright | Red,
  4941. BrightGreen = Bright | Green,
  4942. LightGrey = Bright | Grey,
  4943. BrightWhite = Bright | White,
  4944. BrightYellow = Bright | Yellow,
  4945. // By intention
  4946. FileName = LightGrey,
  4947. Warning = BrightYellow,
  4948. ResultError = BrightRed,
  4949. ResultSuccess = BrightGreen,
  4950. ResultExpectedFailure = Warning,
  4951. Error = BrightRed,
  4952. Success = Green,
  4953. OriginalExpression = Cyan,
  4954. ReconstructedExpression = BrightYellow,
  4955. SecondaryText = LightGrey,
  4956. Headers = White
  4957. };
  4958. // Use constructed object for RAII guard
  4959. Colour( Code _colourCode );
  4960. Colour( Colour&& other ) noexcept;
  4961. Colour& operator=( Colour&& other ) noexcept;
  4962. ~Colour();
  4963. // Use static method for one-shot changes
  4964. static void use( Code _colourCode );
  4965. private:
  4966. bool m_moved = false;
  4967. };
  4968. std::ostream& operator << ( std::ostream& os, Colour const& );
  4969. } // end namespace Catch
  4970. // end catch_console_colour.h
  4971. // start catch_reporter_registrars.hpp
  4972. namespace Catch {
  4973. template<typename T>
  4974. class ReporterRegistrar {
  4975. class ReporterFactory : public IReporterFactory {
  4976. IStreamingReporterPtr create( ReporterConfig const& config ) const override {
  4977. return std::unique_ptr<T>( new T( config ) );
  4978. }
  4979. std::string getDescription() const override {
  4980. return T::getDescription();
  4981. }
  4982. };
  4983. public:
  4984. explicit ReporterRegistrar( std::string const& name ) {
  4985. getMutableRegistryHub().registerReporter( name, std::make_shared<ReporterFactory>() );
  4986. }
  4987. };
  4988. template<typename T>
  4989. class ListenerRegistrar {
  4990. class ListenerFactory : public IReporterFactory {
  4991. IStreamingReporterPtr create( ReporterConfig const& config ) const override {
  4992. return std::unique_ptr<T>( new T( config ) );
  4993. }
  4994. std::string getDescription() const override {
  4995. return std::string();
  4996. }
  4997. };
  4998. public:
  4999. ListenerRegistrar() {
  5000. getMutableRegistryHub().registerListener( std::make_shared<ListenerFactory>() );
  5001. }
  5002. };
  5003. }
  5004. #if !defined(CATCH_CONFIG_DISABLE)
  5005. #define CATCH_REGISTER_REPORTER( name, reporterType ) \
  5006. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
  5007. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  5008. namespace{ Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); } \
  5009. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
  5010. #define CATCH_REGISTER_LISTENER( listenerType ) \
  5011. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
  5012. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  5013. namespace{ Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; } \
  5014. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
  5015. #else // CATCH_CONFIG_DISABLE
  5016. #define CATCH_REGISTER_REPORTER(name, reporterType)
  5017. #define CATCH_REGISTER_LISTENER(listenerType)
  5018. #endif // CATCH_CONFIG_DISABLE
  5019. // end catch_reporter_registrars.hpp
  5020. // Allow users to base their work off existing reporters
  5021. // start catch_reporter_compact.h
  5022. namespace Catch {
  5023. struct CompactReporter : StreamingReporterBase<CompactReporter> {
  5024. using StreamingReporterBase::StreamingReporterBase;
  5025. ~CompactReporter() override;
  5026. static std::string getDescription();
  5027. void noMatchingTestCases(std::string const& spec) override;
  5028. void assertionStarting(AssertionInfo const&) override;
  5029. bool assertionEnded(AssertionStats const& _assertionStats) override;
  5030. void sectionEnded(SectionStats const& _sectionStats) override;
  5031. void testRunEnded(TestRunStats const& _testRunStats) override;
  5032. };
  5033. } // end namespace Catch
  5034. // end catch_reporter_compact.h
  5035. // start catch_reporter_console.h
  5036. #if defined(_MSC_VER)
  5037. #pragma warning(push)
  5038. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  5039. // Note that 4062 (not all labels are handled
  5040. // and default is missing) is enabled
  5041. #endif
  5042. namespace Catch {
  5043. // Fwd decls
  5044. struct SummaryColumn;
  5045. class TablePrinter;
  5046. struct ConsoleReporter : StreamingReporterBase<ConsoleReporter> {
  5047. std::unique_ptr<TablePrinter> m_tablePrinter;
  5048. ConsoleReporter(ReporterConfig const& config);
  5049. ~ConsoleReporter() override;
  5050. static std::string getDescription();
  5051. void noMatchingTestCases(std::string const& spec) override;
  5052. void reportInvalidArguments(std::string const&arg) override;
  5053. void assertionStarting(AssertionInfo const&) override;
  5054. bool assertionEnded(AssertionStats const& _assertionStats) override;
  5055. void sectionStarting(SectionInfo const& _sectionInfo) override;
  5056. void sectionEnded(SectionStats const& _sectionStats) override;
  5057. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  5058. void benchmarkPreparing(std::string const& name) override;
  5059. void benchmarkStarting(BenchmarkInfo const& info) override;
  5060. void benchmarkEnded(BenchmarkStats<> const& stats) override;
  5061. void benchmarkFailed(std::string const& error) override;
  5062. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  5063. void testCaseEnded(TestCaseStats const& _testCaseStats) override;
  5064. void testGroupEnded(TestGroupStats const& _testGroupStats) override;
  5065. void testRunEnded(TestRunStats const& _testRunStats) override;
  5066. void testRunStarting(TestRunInfo const& _testRunInfo) override;
  5067. private:
  5068. void lazyPrint();
  5069. void lazyPrintWithoutClosingBenchmarkTable();
  5070. void lazyPrintRunInfo();
  5071. void lazyPrintGroupInfo();
  5072. void printTestCaseAndSectionHeader();
  5073. void printClosedHeader(std::string const& _name);
  5074. void printOpenHeader(std::string const& _name);
  5075. // if string has a : in first line will set indent to follow it on
  5076. // subsequent lines
  5077. void printHeaderString(std::string const& _string, std::size_t indent = 0);
  5078. void printTotals(Totals const& totals);
  5079. void printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row);
  5080. void printTotalsDivider(Totals const& totals);
  5081. void printSummaryDivider();
  5082. void printTestFilters();
  5083. private:
  5084. bool m_headerPrinted = false;
  5085. };
  5086. } // end namespace Catch
  5087. #if defined(_MSC_VER)
  5088. #pragma warning(pop)
  5089. #endif
  5090. // end catch_reporter_console.h
  5091. // start catch_reporter_junit.h
  5092. // start catch_xmlwriter.h
  5093. #include <vector>
  5094. namespace Catch {
  5095. enum class XmlFormatting {
  5096. None = 0x00,
  5097. Indent = 0x01,
  5098. Newline = 0x02,
  5099. };
  5100. XmlFormatting operator | (XmlFormatting lhs, XmlFormatting rhs);
  5101. XmlFormatting operator & (XmlFormatting lhs, XmlFormatting rhs);
  5102. class XmlEncode {
  5103. public:
  5104. enum ForWhat { ForTextNodes, ForAttributes };
  5105. XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes );
  5106. void encodeTo( std::ostream& os ) const;
  5107. friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode );
  5108. private:
  5109. std::string m_str;
  5110. ForWhat m_forWhat;
  5111. };
  5112. class XmlWriter {
  5113. public:
  5114. class ScopedElement {
  5115. public:
  5116. ScopedElement( XmlWriter* writer, XmlFormatting fmt );
  5117. ScopedElement( ScopedElement&& other ) noexcept;
  5118. ScopedElement& operator=( ScopedElement&& other ) noexcept;
  5119. ~ScopedElement();
  5120. ScopedElement& writeText( std::string const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent );
  5121. template<typename T>
  5122. ScopedElement& writeAttribute( std::string const& name, T const& attribute ) {
  5123. m_writer->writeAttribute( name, attribute );
  5124. return *this;
  5125. }
  5126. private:
  5127. mutable XmlWriter* m_writer = nullptr;
  5128. XmlFormatting m_fmt;
  5129. };
  5130. XmlWriter( std::ostream& os = Catch::cout() );
  5131. ~XmlWriter();
  5132. XmlWriter( XmlWriter const& ) = delete;
  5133. XmlWriter& operator=( XmlWriter const& ) = delete;
  5134. XmlWriter& startElement( std::string const& name, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
  5135. ScopedElement scopedElement( std::string const& name, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
  5136. XmlWriter& endElement(XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
  5137. XmlWriter& writeAttribute( std::string const& name, std::string const& attribute );
  5138. XmlWriter& writeAttribute( std::string const& name, bool attribute );
  5139. template<typename T>
  5140. XmlWriter& writeAttribute( std::string const& name, T const& attribute ) {
  5141. ReusableStringStream rss;
  5142. rss << attribute;
  5143. return writeAttribute( name, rss.str() );
  5144. }
  5145. XmlWriter& writeText( std::string const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
  5146. XmlWriter& writeComment(std::string const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
  5147. void writeStylesheetRef( std::string const& url );
  5148. XmlWriter& writeBlankLine();
  5149. void ensureTagClosed();
  5150. private:
  5151. void applyFormatting(XmlFormatting fmt);
  5152. void writeDeclaration();
  5153. void newlineIfNecessary();
  5154. bool m_tagIsOpen = false;
  5155. bool m_needsNewline = false;
  5156. std::vector<std::string> m_tags;
  5157. std::string m_indent;
  5158. std::ostream& m_os;
  5159. };
  5160. }
  5161. // end catch_xmlwriter.h
  5162. namespace Catch {
  5163. class JunitReporter : public CumulativeReporterBase<JunitReporter> {
  5164. public:
  5165. JunitReporter(ReporterConfig const& _config);
  5166. ~JunitReporter() override;
  5167. static std::string getDescription();
  5168. void noMatchingTestCases(std::string const& /*spec*/) override;
  5169. void testRunStarting(TestRunInfo const& runInfo) override;
  5170. void testGroupStarting(GroupInfo const& groupInfo) override;
  5171. void testCaseStarting(TestCaseInfo const& testCaseInfo) override;
  5172. bool assertionEnded(AssertionStats const& assertionStats) override;
  5173. void testCaseEnded(TestCaseStats const& testCaseStats) override;
  5174. void testGroupEnded(TestGroupStats const& testGroupStats) override;
  5175. void testRunEndedCumulative() override;
  5176. void writeGroup(TestGroupNode const& groupNode, double suiteTime);
  5177. void writeTestCase(TestCaseNode const& testCaseNode);
  5178. void writeSection( std::string const& className,
  5179. std::string const& rootName,
  5180. SectionNode const& sectionNode,
  5181. bool testOkToFail );
  5182. void writeAssertions(SectionNode const& sectionNode);
  5183. void writeAssertion(AssertionStats const& stats);
  5184. XmlWriter xml;
  5185. Timer suiteTimer;
  5186. std::string stdOutForSuite;
  5187. std::string stdErrForSuite;
  5188. unsigned int unexpectedExceptions = 0;
  5189. bool m_okToFail = false;
  5190. };
  5191. } // end namespace Catch
  5192. // end catch_reporter_junit.h
  5193. // start catch_reporter_xml.h
  5194. namespace Catch {
  5195. class XmlReporter : public StreamingReporterBase<XmlReporter> {
  5196. public:
  5197. XmlReporter(ReporterConfig const& _config);
  5198. ~XmlReporter() override;
  5199. static std::string getDescription();
  5200. virtual std::string getStylesheetRef() const;
  5201. void writeSourceInfo(SourceLineInfo const& sourceInfo);
  5202. public: // StreamingReporterBase
  5203. void noMatchingTestCases(std::string const& s) override;
  5204. void testRunStarting(TestRunInfo const& testInfo) override;
  5205. void testGroupStarting(GroupInfo const& groupInfo) override;
  5206. void testCaseStarting(TestCaseInfo const& testInfo) override;
  5207. void sectionStarting(SectionInfo const& sectionInfo) override;
  5208. void assertionStarting(AssertionInfo const&) override;
  5209. bool assertionEnded(AssertionStats const& assertionStats) override;
  5210. void sectionEnded(SectionStats const& sectionStats) override;
  5211. void testCaseEnded(TestCaseStats const& testCaseStats) override;
  5212. void testGroupEnded(TestGroupStats const& testGroupStats) override;
  5213. void testRunEnded(TestRunStats const& testRunStats) override;
  5214. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  5215. void benchmarkPreparing(std::string const& name) override;
  5216. void benchmarkStarting(BenchmarkInfo const&) override;
  5217. void benchmarkEnded(BenchmarkStats<> const&) override;
  5218. void benchmarkFailed(std::string const&) override;
  5219. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  5220. private:
  5221. Timer m_testCaseTimer;
  5222. XmlWriter m_xml;
  5223. int m_sectionDepth = 0;
  5224. };
  5225. } // end namespace Catch
  5226. // end catch_reporter_xml.h
  5227. // end catch_external_interfaces.h
  5228. #endif
  5229. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  5230. // start catch_benchmarking_all.hpp
  5231. // A proxy header that includes all of the benchmarking headers to allow
  5232. // concise include of the benchmarking features. You should prefer the
  5233. // individual includes in standard use.
  5234. // start catch_benchmark.hpp
  5235. // Benchmark
  5236. // start catch_chronometer.hpp
  5237. // User-facing chronometer
  5238. // start catch_clock.hpp
  5239. // Clocks
  5240. #include <chrono>
  5241. #include <ratio>
  5242. namespace Catch {
  5243. namespace Benchmark {
  5244. template <typename Clock>
  5245. using ClockDuration = typename Clock::duration;
  5246. template <typename Clock>
  5247. using FloatDuration = std::chrono::duration<double, typename Clock::period>;
  5248. template <typename Clock>
  5249. using TimePoint = typename Clock::time_point;
  5250. using default_clock = std::chrono::steady_clock;
  5251. template <typename Clock>
  5252. struct now {
  5253. TimePoint<Clock> operator()() const {
  5254. return Clock::now();
  5255. }
  5256. };
  5257. using fp_seconds = std::chrono::duration<double, std::ratio<1>>;
  5258. } // namespace Benchmark
  5259. } // namespace Catch
  5260. // end catch_clock.hpp
  5261. // start catch_optimizer.hpp
  5262. // Hinting the optimizer
  5263. #if defined(_MSC_VER)
  5264. # include <atomic> // atomic_thread_fence
  5265. #endif
  5266. namespace Catch {
  5267. namespace Benchmark {
  5268. #if defined(__GNUC__) || defined(__clang__)
  5269. template <typename T>
  5270. inline void keep_memory(T* p) {
  5271. asm volatile("" : : "g"(p) : "memory");
  5272. }
  5273. inline void keep_memory() {
  5274. asm volatile("" : : : "memory");
  5275. }
  5276. namespace Detail {
  5277. inline void optimizer_barrier() { keep_memory(); }
  5278. } // namespace Detail
  5279. #elif defined(_MSC_VER)
  5280. #pragma optimize("", off)
  5281. template <typename T>
  5282. inline void keep_memory(T* p) {
  5283. // thanks @milleniumbug
  5284. *reinterpret_cast<char volatile*>(p) = *reinterpret_cast<char const volatile*>(p);
  5285. }
  5286. // TODO equivalent keep_memory()
  5287. #pragma optimize("", on)
  5288. namespace Detail {
  5289. inline void optimizer_barrier() {
  5290. std::atomic_thread_fence(std::memory_order_seq_cst);
  5291. }
  5292. } // namespace Detail
  5293. #endif
  5294. template <typename T>
  5295. inline void deoptimize_value(T&& x) {
  5296. keep_memory(&x);
  5297. }
  5298. template <typename Fn, typename... Args>
  5299. inline auto invoke_deoptimized(Fn&& fn, Args&&... args) -> typename std::enable_if<!std::is_same<void, decltype(fn(args...))>::value>::type {
  5300. deoptimize_value(std::forward<Fn>(fn) (std::forward<Args...>(args...)));
  5301. }
  5302. template <typename Fn, typename... Args>
  5303. inline auto invoke_deoptimized(Fn&& fn, Args&&... args) -> typename std::enable_if<std::is_same<void, decltype(fn(args...))>::value>::type {
  5304. std::forward<Fn>(fn) (std::forward<Args...>(args...));
  5305. }
  5306. } // namespace Benchmark
  5307. } // namespace Catch
  5308. // end catch_optimizer.hpp
  5309. // start catch_complete_invoke.hpp
  5310. // Invoke with a special case for void
  5311. #include <type_traits>
  5312. #include <utility>
  5313. namespace Catch {
  5314. namespace Benchmark {
  5315. namespace Detail {
  5316. template <typename T>
  5317. struct CompleteType { using type = T; };
  5318. template <>
  5319. struct CompleteType<void> { struct type {}; };
  5320. template <typename T>
  5321. using CompleteType_t = typename CompleteType<T>::type;
  5322. template <typename Result>
  5323. struct CompleteInvoker {
  5324. template <typename Fun, typename... Args>
  5325. static Result invoke(Fun&& fun, Args&&... args) {
  5326. return std::forward<Fun>(fun)(std::forward<Args>(args)...);
  5327. }
  5328. };
  5329. template <>
  5330. struct CompleteInvoker<void> {
  5331. template <typename Fun, typename... Args>
  5332. static CompleteType_t<void> invoke(Fun&& fun, Args&&... args) {
  5333. std::forward<Fun>(fun)(std::forward<Args>(args)...);
  5334. return {};
  5335. }
  5336. };
  5337. // invoke and not return void :(
  5338. template <typename Fun, typename... Args>
  5339. CompleteType_t<FunctionReturnType<Fun, Args...>> complete_invoke(Fun&& fun, Args&&... args) {
  5340. return CompleteInvoker<FunctionReturnType<Fun, Args...>>::invoke(std::forward<Fun>(fun), std::forward<Args>(args)...);
  5341. }
  5342. const std::string benchmarkErrorMsg = "a benchmark failed to run successfully";
  5343. } // namespace Detail
  5344. template <typename Fun>
  5345. Detail::CompleteType_t<FunctionReturnType<Fun>> user_code(Fun&& fun) {
  5346. CATCH_TRY{
  5347. return Detail::complete_invoke(std::forward<Fun>(fun));
  5348. } CATCH_CATCH_ALL{
  5349. getResultCapture().benchmarkFailed(translateActiveException());
  5350. CATCH_RUNTIME_ERROR(Detail::benchmarkErrorMsg);
  5351. }
  5352. }
  5353. } // namespace Benchmark
  5354. } // namespace Catch
  5355. // end catch_complete_invoke.hpp
  5356. namespace Catch {
  5357. namespace Benchmark {
  5358. namespace Detail {
  5359. struct ChronometerConcept {
  5360. virtual void start() = 0;
  5361. virtual void finish() = 0;
  5362. virtual ~ChronometerConcept() = default;
  5363. };
  5364. template <typename Clock>
  5365. struct ChronometerModel final : public ChronometerConcept {
  5366. void start() override { started = Clock::now(); }
  5367. void finish() override { finished = Clock::now(); }
  5368. ClockDuration<Clock> elapsed() const { return finished - started; }
  5369. TimePoint<Clock> started;
  5370. TimePoint<Clock> finished;
  5371. };
  5372. } // namespace Detail
  5373. struct Chronometer {
  5374. public:
  5375. template <typename Fun>
  5376. void measure(Fun&& fun) { measure(std::forward<Fun>(fun), is_callable<Fun(int)>()); }
  5377. int runs() const { return k; }
  5378. Chronometer(Detail::ChronometerConcept& meter, int k)
  5379. : impl(&meter)
  5380. , k(k) {}
  5381. private:
  5382. template <typename Fun>
  5383. void measure(Fun&& fun, std::false_type) {
  5384. measure([&fun](int) { return fun(); }, std::true_type());
  5385. }
  5386. template <typename Fun>
  5387. void measure(Fun&& fun, std::true_type) {
  5388. Detail::optimizer_barrier();
  5389. impl->start();
  5390. for (int i = 0; i < k; ++i) invoke_deoptimized(fun, i);
  5391. impl->finish();
  5392. Detail::optimizer_barrier();
  5393. }
  5394. Detail::ChronometerConcept* impl;
  5395. int k;
  5396. };
  5397. } // namespace Benchmark
  5398. } // namespace Catch
  5399. // end catch_chronometer.hpp
  5400. // start catch_environment.hpp
  5401. // Environment information
  5402. namespace Catch {
  5403. namespace Benchmark {
  5404. template <typename Duration>
  5405. struct EnvironmentEstimate {
  5406. Duration mean;
  5407. OutlierClassification outliers;
  5408. template <typename Duration2>
  5409. operator EnvironmentEstimate<Duration2>() const {
  5410. return { mean, outliers };
  5411. }
  5412. };
  5413. template <typename Clock>
  5414. struct Environment {
  5415. using clock_type = Clock;
  5416. EnvironmentEstimate<FloatDuration<Clock>> clock_resolution;
  5417. EnvironmentEstimate<FloatDuration<Clock>> clock_cost;
  5418. };
  5419. } // namespace Benchmark
  5420. } // namespace Catch
  5421. // end catch_environment.hpp
  5422. // start catch_execution_plan.hpp
  5423. // Execution plan
  5424. // start catch_benchmark_function.hpp
  5425. // Dumb std::function implementation for consistent call overhead
  5426. #include <cassert>
  5427. #include <type_traits>
  5428. #include <utility>
  5429. #include <memory>
  5430. namespace Catch {
  5431. namespace Benchmark {
  5432. namespace Detail {
  5433. template <typename T>
  5434. using Decay = typename std::decay<T>::type;
  5435. template <typename T, typename U>
  5436. struct is_related
  5437. : std::is_same<Decay<T>, Decay<U>> {};
  5438. /// We need to reinvent std::function because every piece of code that might add overhead
  5439. /// in a measurement context needs to have consistent performance characteristics so that we
  5440. /// can account for it in the measurement.
  5441. /// Implementations of std::function with optimizations that aren't always applicable, like
  5442. /// small buffer optimizations, are not uncommon.
  5443. /// This is effectively an implementation of std::function without any such optimizations;
  5444. /// it may be slow, but it is consistently slow.
  5445. struct BenchmarkFunction {
  5446. private:
  5447. struct callable {
  5448. virtual void call(Chronometer meter) const = 0;
  5449. virtual callable* clone() const = 0;
  5450. virtual ~callable() = default;
  5451. };
  5452. template <typename Fun>
  5453. struct model : public callable {
  5454. model(Fun&& fun) : fun(std::move(fun)) {}
  5455. model(Fun const& fun) : fun(fun) {}
  5456. model<Fun>* clone() const override { return new model<Fun>(*this); }
  5457. void call(Chronometer meter) const override {
  5458. call(meter, is_callable<Fun(Chronometer)>());
  5459. }
  5460. void call(Chronometer meter, std::true_type) const {
  5461. fun(meter);
  5462. }
  5463. void call(Chronometer meter, std::false_type) const {
  5464. meter.measure(fun);
  5465. }
  5466. Fun fun;
  5467. };
  5468. struct do_nothing { void operator()() const {} };
  5469. template <typename T>
  5470. BenchmarkFunction(model<T>* c) : f(c) {}
  5471. public:
  5472. BenchmarkFunction()
  5473. : f(new model<do_nothing>{ {} }) {}
  5474. template <typename Fun,
  5475. typename std::enable_if<!is_related<Fun, BenchmarkFunction>::value, int>::type = 0>
  5476. BenchmarkFunction(Fun&& fun)
  5477. : f(new model<typename std::decay<Fun>::type>(std::forward<Fun>(fun))) {}
  5478. BenchmarkFunction(BenchmarkFunction&& that)
  5479. : f(std::move(that.f)) {}
  5480. BenchmarkFunction(BenchmarkFunction const& that)
  5481. : f(that.f->clone()) {}
  5482. BenchmarkFunction& operator=(BenchmarkFunction&& that) {
  5483. f = std::move(that.f);
  5484. return *this;
  5485. }
  5486. BenchmarkFunction& operator=(BenchmarkFunction const& that) {
  5487. f.reset(that.f->clone());
  5488. return *this;
  5489. }
  5490. void operator()(Chronometer meter) const { f->call(meter); }
  5491. private:
  5492. std::unique_ptr<callable> f;
  5493. };
  5494. } // namespace Detail
  5495. } // namespace Benchmark
  5496. } // namespace Catch
  5497. // end catch_benchmark_function.hpp
  5498. // start catch_repeat.hpp
  5499. // repeat algorithm
  5500. #include <type_traits>
  5501. #include <utility>
  5502. namespace Catch {
  5503. namespace Benchmark {
  5504. namespace Detail {
  5505. template <typename Fun>
  5506. struct repeater {
  5507. void operator()(int k) const {
  5508. for (int i = 0; i < k; ++i) {
  5509. fun();
  5510. }
  5511. }
  5512. Fun fun;
  5513. };
  5514. template <typename Fun>
  5515. repeater<typename std::decay<Fun>::type> repeat(Fun&& fun) {
  5516. return { std::forward<Fun>(fun) };
  5517. }
  5518. } // namespace Detail
  5519. } // namespace Benchmark
  5520. } // namespace Catch
  5521. // end catch_repeat.hpp
  5522. // start catch_run_for_at_least.hpp
  5523. // Run a function for a minimum amount of time
  5524. // start catch_measure.hpp
  5525. // Measure
  5526. // start catch_timing.hpp
  5527. // Timing
  5528. #include <tuple>
  5529. #include <type_traits>
  5530. namespace Catch {
  5531. namespace Benchmark {
  5532. template <typename Duration, typename Result>
  5533. struct Timing {
  5534. Duration elapsed;
  5535. Result result;
  5536. int iterations;
  5537. };
  5538. template <typename Clock, typename Func, typename... Args>
  5539. using TimingOf = Timing<ClockDuration<Clock>, Detail::CompleteType_t<FunctionReturnType<Func, Args...>>>;
  5540. } // namespace Benchmark
  5541. } // namespace Catch
  5542. // end catch_timing.hpp
  5543. #include <utility>
  5544. namespace Catch {
  5545. namespace Benchmark {
  5546. namespace Detail {
  5547. template <typename Clock, typename Fun, typename... Args>
  5548. TimingOf<Clock, Fun, Args...> measure(Fun&& fun, Args&&... args) {
  5549. auto start = Clock::now();
  5550. auto&& r = Detail::complete_invoke(fun, std::forward<Args>(args)...);
  5551. auto end = Clock::now();
  5552. auto delta = end - start;
  5553. return { delta, std::forward<decltype(r)>(r), 1 };
  5554. }
  5555. } // namespace Detail
  5556. } // namespace Benchmark
  5557. } // namespace Catch
  5558. // end catch_measure.hpp
  5559. #include <utility>
  5560. #include <type_traits>
  5561. namespace Catch {
  5562. namespace Benchmark {
  5563. namespace Detail {
  5564. template <typename Clock, typename Fun>
  5565. TimingOf<Clock, Fun, int> measure_one(Fun&& fun, int iters, std::false_type) {
  5566. return Detail::measure<Clock>(fun, iters);
  5567. }
  5568. template <typename Clock, typename Fun>
  5569. TimingOf<Clock, Fun, Chronometer> measure_one(Fun&& fun, int iters, std::true_type) {
  5570. Detail::ChronometerModel<Clock> meter;
  5571. auto&& result = Detail::complete_invoke(fun, Chronometer(meter, iters));
  5572. return { meter.elapsed(), std::move(result), iters };
  5573. }
  5574. template <typename Clock, typename Fun>
  5575. using run_for_at_least_argument_t = typename std::conditional<is_callable<Fun(Chronometer)>::value, Chronometer, int>::type;
  5576. struct optimized_away_error : std::exception {
  5577. const char* what() const noexcept override {
  5578. return "could not measure benchmark, maybe it was optimized away";
  5579. }
  5580. };
  5581. template <typename Clock, typename Fun>
  5582. TimingOf<Clock, Fun, run_for_at_least_argument_t<Clock, Fun>> run_for_at_least(ClockDuration<Clock> how_long, int seed, Fun&& fun) {
  5583. auto iters = seed;
  5584. while (iters < (1 << 30)) {
  5585. auto&& Timing = measure_one<Clock>(fun, iters, is_callable<Fun(Chronometer)>());
  5586. if (Timing.elapsed >= how_long) {
  5587. return { Timing.elapsed, std::move(Timing.result), iters };
  5588. }
  5589. iters *= 2;
  5590. }
  5591. Catch::throw_exception(optimized_away_error{});
  5592. }
  5593. } // namespace Detail
  5594. } // namespace Benchmark
  5595. } // namespace Catch
  5596. // end catch_run_for_at_least.hpp
  5597. #include <algorithm>
  5598. #include <iterator>
  5599. namespace Catch {
  5600. namespace Benchmark {
  5601. template <typename Duration>
  5602. struct ExecutionPlan {
  5603. int iterations_per_sample;
  5604. Duration estimated_duration;
  5605. Detail::BenchmarkFunction benchmark;
  5606. Duration warmup_time;
  5607. int warmup_iterations;
  5608. template <typename Duration2>
  5609. operator ExecutionPlan<Duration2>() const {
  5610. return { iterations_per_sample, estimated_duration, benchmark, warmup_time, warmup_iterations };
  5611. }
  5612. template <typename Clock>
  5613. std::vector<FloatDuration<Clock>> run(const IConfig &cfg, Environment<FloatDuration<Clock>> env) const {
  5614. // warmup a bit
  5615. Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_iterations, Detail::repeat(now<Clock>{}));
  5616. std::vector<FloatDuration<Clock>> times;
  5617. times.reserve(cfg.benchmarkSamples());
  5618. std::generate_n(std::back_inserter(times), cfg.benchmarkSamples(), [this, env] {
  5619. Detail::ChronometerModel<Clock> model;
  5620. this->benchmark(Chronometer(model, iterations_per_sample));
  5621. auto sample_time = model.elapsed() - env.clock_cost.mean;
  5622. if (sample_time < FloatDuration<Clock>::zero()) sample_time = FloatDuration<Clock>::zero();
  5623. return sample_time / iterations_per_sample;
  5624. });
  5625. return times;
  5626. }
  5627. };
  5628. } // namespace Benchmark
  5629. } // namespace Catch
  5630. // end catch_execution_plan.hpp
  5631. // start catch_estimate_clock.hpp
  5632. // Environment measurement
  5633. // start catch_stats.hpp
  5634. // Statistical analysis tools
  5635. #include <algorithm>
  5636. #include <functional>
  5637. #include <vector>
  5638. #include <iterator>
  5639. #include <numeric>
  5640. #include <tuple>
  5641. #include <cmath>
  5642. #include <utility>
  5643. #include <cstddef>
  5644. #include <random>
  5645. namespace Catch {
  5646. namespace Benchmark {
  5647. namespace Detail {
  5648. using sample = std::vector<double>;
  5649. double weighted_average_quantile(int k, int q, std::vector<double>::iterator first, std::vector<double>::iterator last);
  5650. template <typename Iterator>
  5651. OutlierClassification classify_outliers(Iterator first, Iterator last) {
  5652. std::vector<double> copy(first, last);
  5653. auto q1 = weighted_average_quantile(1, 4, copy.begin(), copy.end());
  5654. auto q3 = weighted_average_quantile(3, 4, copy.begin(), copy.end());
  5655. auto iqr = q3 - q1;
  5656. auto los = q1 - (iqr * 3.);
  5657. auto lom = q1 - (iqr * 1.5);
  5658. auto him = q3 + (iqr * 1.5);
  5659. auto his = q3 + (iqr * 3.);
  5660. OutlierClassification o;
  5661. for (; first != last; ++first) {
  5662. auto&& t = *first;
  5663. if (t < los) ++o.low_severe;
  5664. else if (t < lom) ++o.low_mild;
  5665. else if (t > his) ++o.high_severe;
  5666. else if (t > him) ++o.high_mild;
  5667. ++o.samples_seen;
  5668. }
  5669. return o;
  5670. }
  5671. template <typename Iterator>
  5672. double mean(Iterator first, Iterator last) {
  5673. auto count = last - first;
  5674. double sum = std::accumulate(first, last, 0.);
  5675. return sum / count;
  5676. }
  5677. template <typename URng, typename Iterator, typename Estimator>
  5678. sample resample(URng& rng, int resamples, Iterator first, Iterator last, Estimator& estimator) {
  5679. auto n = last - first;
  5680. std::uniform_int_distribution<decltype(n)> dist(0, n - 1);
  5681. sample out;
  5682. out.reserve(resamples);
  5683. std::generate_n(std::back_inserter(out), resamples, [n, first, &estimator, &dist, &rng] {
  5684. std::vector<double> resampled;
  5685. resampled.reserve(n);
  5686. std::generate_n(std::back_inserter(resampled), n, [first, &dist, &rng] { return first[dist(rng)]; });
  5687. return estimator(resampled.begin(), resampled.end());
  5688. });
  5689. std::sort(out.begin(), out.end());
  5690. return out;
  5691. }
  5692. template <typename Estimator, typename Iterator>
  5693. sample jackknife(Estimator&& estimator, Iterator first, Iterator last) {
  5694. auto n = last - first;
  5695. auto second = std::next(first);
  5696. sample results;
  5697. results.reserve(n);
  5698. for (auto it = first; it != last; ++it) {
  5699. std::iter_swap(it, first);
  5700. results.push_back(estimator(second, last));
  5701. }
  5702. return results;
  5703. }
  5704. inline double normal_cdf(double x) {
  5705. return std::erfc(-x / std::sqrt(2.0)) / 2.0;
  5706. }
  5707. double erfc_inv(double x);
  5708. double normal_quantile(double p);
  5709. template <typename Iterator, typename Estimator>
  5710. Estimate<double> bootstrap(double confidence_level, Iterator first, Iterator last, sample const& resample, Estimator&& estimator) {
  5711. auto n_samples = last - first;
  5712. double point = estimator(first, last);
  5713. // Degenerate case with a single sample
  5714. if (n_samples == 1) return { point, point, point, confidence_level };
  5715. sample jack = jackknife(estimator, first, last);
  5716. double jack_mean = mean(jack.begin(), jack.end());
  5717. double sum_squares, sum_cubes;
  5718. 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> {
  5719. auto d = jack_mean - x;
  5720. auto d2 = d * d;
  5721. auto d3 = d2 * d;
  5722. return { sqcb.first + d2, sqcb.second + d3 };
  5723. });
  5724. double accel = sum_cubes / (6 * std::pow(sum_squares, 1.5));
  5725. int n = static_cast<int>(resample.size());
  5726. double prob_n = std::count_if(resample.begin(), resample.end(), [point](double x) { return x < point; }) / (double)n;
  5727. // degenerate case with uniform samples
  5728. if (prob_n == 0) return { point, point, point, confidence_level };
  5729. double bias = normal_quantile(prob_n);
  5730. double z1 = normal_quantile((1. - confidence_level) / 2.);
  5731. auto cumn = [n](double x) -> int {
  5732. return std::lround(normal_cdf(x) * n); };
  5733. auto a = [bias, accel](double b) { return bias + b / (1. - accel * b); };
  5734. double b1 = bias + z1;
  5735. double b2 = bias - z1;
  5736. double a1 = a(b1);
  5737. double a2 = a(b2);
  5738. auto lo = (std::max)(cumn(a1), 0);
  5739. auto hi = (std::min)(cumn(a2), n - 1);
  5740. return { point, resample[lo], resample[hi], confidence_level };
  5741. }
  5742. double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n);
  5743. struct bootstrap_analysis {
  5744. Estimate<double> mean;
  5745. Estimate<double> standard_deviation;
  5746. double outlier_variance;
  5747. };
  5748. bootstrap_analysis analyse_samples(double confidence_level, int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last);
  5749. } // namespace Detail
  5750. } // namespace Benchmark
  5751. } // namespace Catch
  5752. // end catch_stats.hpp
  5753. #include <algorithm>
  5754. #include <iterator>
  5755. #include <tuple>
  5756. #include <vector>
  5757. #include <cmath>
  5758. namespace Catch {
  5759. namespace Benchmark {
  5760. namespace Detail {
  5761. template <typename Clock>
  5762. std::vector<double> resolution(int k) {
  5763. std::vector<TimePoint<Clock>> times;
  5764. times.reserve(k + 1);
  5765. std::generate_n(std::back_inserter(times), k + 1, now<Clock>{});
  5766. std::vector<double> deltas;
  5767. deltas.reserve(k);
  5768. std::transform(std::next(times.begin()), times.end(), times.begin(),
  5769. std::back_inserter(deltas),
  5770. [](TimePoint<Clock> a, TimePoint<Clock> b) { return static_cast<double>((a - b).count()); });
  5771. return deltas;
  5772. }
  5773. const auto warmup_iterations = 10000;
  5774. const auto warmup_time = std::chrono::milliseconds(100);
  5775. const auto minimum_ticks = 1000;
  5776. const auto warmup_seed = 10000;
  5777. const auto clock_resolution_estimation_time = std::chrono::milliseconds(500);
  5778. const auto clock_cost_estimation_time_limit = std::chrono::seconds(1);
  5779. const auto clock_cost_estimation_tick_limit = 100000;
  5780. const auto clock_cost_estimation_time = std::chrono::milliseconds(10);
  5781. const auto clock_cost_estimation_iterations = 10000;
  5782. template <typename Clock>
  5783. int warmup() {
  5784. return run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_seed, &resolution<Clock>)
  5785. .iterations;
  5786. }
  5787. template <typename Clock>
  5788. EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_resolution(int iterations) {
  5789. auto r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_resolution_estimation_time), iterations, &resolution<Clock>)
  5790. .result;
  5791. return {
  5792. FloatDuration<Clock>(mean(r.begin(), r.end())),
  5793. classify_outliers(r.begin(), r.end()),
  5794. };
  5795. }
  5796. template <typename Clock>
  5797. EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_cost(FloatDuration<Clock> resolution) {
  5798. auto time_limit = (std::min)(
  5799. resolution * clock_cost_estimation_tick_limit,
  5800. FloatDuration<Clock>(clock_cost_estimation_time_limit));
  5801. auto time_clock = [](int k) {
  5802. return Detail::measure<Clock>([k] {
  5803. for (int i = 0; i < k; ++i) {
  5804. volatile auto ignored = Clock::now();
  5805. (void)ignored;
  5806. }
  5807. }).elapsed;
  5808. };
  5809. time_clock(1);
  5810. int iters = clock_cost_estimation_iterations;
  5811. auto&& r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_cost_estimation_time), iters, time_clock);
  5812. std::vector<double> times;
  5813. int nsamples = static_cast<int>(std::ceil(time_limit / r.elapsed));
  5814. times.reserve(nsamples);
  5815. std::generate_n(std::back_inserter(times), nsamples, [time_clock, &r] {
  5816. return static_cast<double>((time_clock(r.iterations) / r.iterations).count());
  5817. });
  5818. return {
  5819. FloatDuration<Clock>(mean(times.begin(), times.end())),
  5820. classify_outliers(times.begin(), times.end()),
  5821. };
  5822. }
  5823. template <typename Clock>
  5824. Environment<FloatDuration<Clock>> measure_environment() {
  5825. static Environment<FloatDuration<Clock>>* env = nullptr;
  5826. if (env) {
  5827. return *env;
  5828. }
  5829. auto iters = Detail::warmup<Clock>();
  5830. auto resolution = Detail::estimate_clock_resolution<Clock>(iters);
  5831. auto cost = Detail::estimate_clock_cost<Clock>(resolution.mean);
  5832. env = new Environment<FloatDuration<Clock>>{ resolution, cost };
  5833. return *env;
  5834. }
  5835. } // namespace Detail
  5836. } // namespace Benchmark
  5837. } // namespace Catch
  5838. // end catch_estimate_clock.hpp
  5839. // start catch_analyse.hpp
  5840. // Run and analyse one benchmark
  5841. // start catch_sample_analysis.hpp
  5842. // Benchmark results
  5843. #include <algorithm>
  5844. #include <vector>
  5845. #include <string>
  5846. #include <iterator>
  5847. namespace Catch {
  5848. namespace Benchmark {
  5849. template <typename Duration>
  5850. struct SampleAnalysis {
  5851. std::vector<Duration> samples;
  5852. Estimate<Duration> mean;
  5853. Estimate<Duration> standard_deviation;
  5854. OutlierClassification outliers;
  5855. double outlier_variance;
  5856. template <typename Duration2>
  5857. operator SampleAnalysis<Duration2>() const {
  5858. std::vector<Duration2> samples2;
  5859. samples2.reserve(samples.size());
  5860. std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration d) { return Duration2(d); });
  5861. return {
  5862. std::move(samples2),
  5863. mean,
  5864. standard_deviation,
  5865. outliers,
  5866. outlier_variance,
  5867. };
  5868. }
  5869. };
  5870. } // namespace Benchmark
  5871. } // namespace Catch
  5872. // end catch_sample_analysis.hpp
  5873. #include <algorithm>
  5874. #include <iterator>
  5875. #include <vector>
  5876. namespace Catch {
  5877. namespace Benchmark {
  5878. namespace Detail {
  5879. template <typename Duration, typename Iterator>
  5880. SampleAnalysis<Duration> analyse(const IConfig &cfg, Environment<Duration>, Iterator first, Iterator last) {
  5881. if (!cfg.benchmarkNoAnalysis()) {
  5882. std::vector<double> samples;
  5883. samples.reserve(last - first);
  5884. std::transform(first, last, std::back_inserter(samples), [](Duration d) { return d.count(); });
  5885. auto analysis = Catch::Benchmark::Detail::analyse_samples(cfg.benchmarkConfidenceInterval(), cfg.benchmarkResamples(), samples.begin(), samples.end());
  5886. auto outliers = Catch::Benchmark::Detail::classify_outliers(samples.begin(), samples.end());
  5887. auto wrap_estimate = [](Estimate<double> e) {
  5888. return Estimate<Duration> {
  5889. Duration(e.point),
  5890. Duration(e.lower_bound),
  5891. Duration(e.upper_bound),
  5892. e.confidence_interval,
  5893. };
  5894. };
  5895. std::vector<Duration> samples2;
  5896. samples2.reserve(samples.size());
  5897. std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](double d) { return Duration(d); });
  5898. return {
  5899. std::move(samples2),
  5900. wrap_estimate(analysis.mean),
  5901. wrap_estimate(analysis.standard_deviation),
  5902. outliers,
  5903. analysis.outlier_variance,
  5904. };
  5905. } else {
  5906. std::vector<Duration> samples;
  5907. samples.reserve(last - first);
  5908. Duration mean = Duration(0);
  5909. int i = 0;
  5910. for (auto it = first; it < last; ++it, ++i) {
  5911. samples.push_back(Duration(*it));
  5912. mean += Duration(*it);
  5913. }
  5914. mean /= i;
  5915. return {
  5916. std::move(samples),
  5917. Estimate<Duration>{mean, mean, mean, 0.0},
  5918. Estimate<Duration>{Duration(0), Duration(0), Duration(0), 0.0},
  5919. OutlierClassification{},
  5920. 0.0
  5921. };
  5922. }
  5923. }
  5924. } // namespace Detail
  5925. } // namespace Benchmark
  5926. } // namespace Catch
  5927. // end catch_analyse.hpp
  5928. #include <algorithm>
  5929. #include <functional>
  5930. #include <string>
  5931. #include <vector>
  5932. #include <cmath>
  5933. namespace Catch {
  5934. namespace Benchmark {
  5935. struct Benchmark {
  5936. Benchmark(std::string &&name)
  5937. : name(std::move(name)) {}
  5938. template <class FUN>
  5939. Benchmark(std::string &&name, FUN &&func)
  5940. : fun(std::move(func)), name(std::move(name)) {}
  5941. template <typename Clock>
  5942. ExecutionPlan<FloatDuration<Clock>> prepare(const IConfig &cfg, Environment<FloatDuration<Clock>> env) const {
  5943. auto min_time = env.clock_resolution.mean * Detail::minimum_ticks;
  5944. auto run_time = std::max(min_time, std::chrono::duration_cast<decltype(min_time)>(cfg.benchmarkWarmupTime()));
  5945. auto&& test = Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(run_time), 1, fun);
  5946. int new_iters = static_cast<int>(std::ceil(min_time * test.iterations / test.elapsed));
  5947. return { new_iters, test.elapsed / test.iterations * new_iters * cfg.benchmarkSamples(), fun, std::chrono::duration_cast<FloatDuration<Clock>>(cfg.benchmarkWarmupTime()), Detail::warmup_iterations };
  5948. }
  5949. template <typename Clock = default_clock>
  5950. void run() {
  5951. IConfigPtr cfg = getCurrentContext().getConfig();
  5952. auto env = Detail::measure_environment<Clock>();
  5953. getResultCapture().benchmarkPreparing(name);
  5954. CATCH_TRY{
  5955. auto plan = user_code([&] {
  5956. return prepare<Clock>(*cfg, env);
  5957. });
  5958. BenchmarkInfo info {
  5959. name,
  5960. plan.estimated_duration.count(),
  5961. plan.iterations_per_sample,
  5962. cfg->benchmarkSamples(),
  5963. cfg->benchmarkResamples(),
  5964. env.clock_resolution.mean.count(),
  5965. env.clock_cost.mean.count()
  5966. };
  5967. getResultCapture().benchmarkStarting(info);
  5968. auto samples = user_code([&] {
  5969. return plan.template run<Clock>(*cfg, env);
  5970. });
  5971. auto analysis = Detail::analyse(*cfg, env, samples.begin(), samples.end());
  5972. BenchmarkStats<FloatDuration<Clock>> stats{ info, analysis.samples, analysis.mean, analysis.standard_deviation, analysis.outliers, analysis.outlier_variance };
  5973. getResultCapture().benchmarkEnded(stats);
  5974. } CATCH_CATCH_ALL{
  5975. if (translateActiveException() != Detail::benchmarkErrorMsg) // benchmark errors have been reported, otherwise rethrow.
  5976. std::rethrow_exception(std::current_exception());
  5977. }
  5978. }
  5979. // sets lambda to be used in fun *and* executes benchmark!
  5980. template <typename Fun,
  5981. typename std::enable_if<!Detail::is_related<Fun, Benchmark>::value, int>::type = 0>
  5982. Benchmark & operator=(Fun func) {
  5983. fun = Detail::BenchmarkFunction(func);
  5984. run();
  5985. return *this;
  5986. }
  5987. explicit operator bool() {
  5988. return true;
  5989. }
  5990. private:
  5991. Detail::BenchmarkFunction fun;
  5992. std::string name;
  5993. };
  5994. }
  5995. } // namespace Catch
  5996. #define INTERNAL_CATCH_GET_1_ARG(arg1, arg2, ...) arg1
  5997. #define INTERNAL_CATCH_GET_2_ARG(arg1, arg2, ...) arg2
  5998. #define INTERNAL_CATCH_BENCHMARK(BenchmarkName, name, benchmarkIndex)\
  5999. if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \
  6000. BenchmarkName = [&](int benchmarkIndex)
  6001. #define INTERNAL_CATCH_BENCHMARK_ADVANCED(BenchmarkName, name)\
  6002. if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \
  6003. BenchmarkName = [&]
  6004. // end catch_benchmark.hpp
  6005. // start catch_constructor.hpp
  6006. // Constructor and destructor helpers
  6007. #include <type_traits>
  6008. namespace Catch {
  6009. namespace Benchmark {
  6010. namespace Detail {
  6011. template <typename T, bool Destruct>
  6012. struct ObjectStorage
  6013. {
  6014. using TStorage = typename std::aligned_storage<sizeof(T), std::alignment_of<T>::value>::type;
  6015. ObjectStorage() : data() {}
  6016. ObjectStorage(const ObjectStorage& other)
  6017. {
  6018. new(&data) T(other.stored_object());
  6019. }
  6020. ObjectStorage(ObjectStorage&& other)
  6021. {
  6022. new(&data) T(std::move(other.stored_object()));
  6023. }
  6024. ~ObjectStorage() { destruct_on_exit<T>(); }
  6025. template <typename... Args>
  6026. void construct(Args&&... args)
  6027. {
  6028. new (&data) T(std::forward<Args>(args)...);
  6029. }
  6030. template <bool AllowManualDestruction = !Destruct>
  6031. typename std::enable_if<AllowManualDestruction>::type destruct()
  6032. {
  6033. stored_object().~T();
  6034. }
  6035. private:
  6036. // If this is a constructor benchmark, destruct the underlying object
  6037. template <typename U>
  6038. void destruct_on_exit(typename std::enable_if<Destruct, U>::type* = 0) { destruct<true>(); }
  6039. // Otherwise, don't
  6040. template <typename U>
  6041. void destruct_on_exit(typename std::enable_if<!Destruct, U>::type* = 0) { }
  6042. T& stored_object() {
  6043. return *static_cast<T*>(static_cast<void*>(&data));
  6044. }
  6045. T const& stored_object() const {
  6046. return *static_cast<T*>(static_cast<void*>(&data));
  6047. }
  6048. TStorage data;
  6049. };
  6050. }
  6051. template <typename T>
  6052. using storage_for = Detail::ObjectStorage<T, true>;
  6053. template <typename T>
  6054. using destructable_object = Detail::ObjectStorage<T, false>;
  6055. }
  6056. }
  6057. // end catch_constructor.hpp
  6058. // end catch_benchmarking_all.hpp
  6059. #endif
  6060. #endif // ! CATCH_CONFIG_IMPL_ONLY
  6061. #ifdef CATCH_IMPL
  6062. // start catch_impl.hpp
  6063. #ifdef __clang__
  6064. #pragma clang diagnostic push
  6065. #pragma clang diagnostic ignored "-Wweak-vtables"
  6066. #endif
  6067. // Keep these here for external reporters
  6068. // start catch_test_case_tracker.h
  6069. #include <string>
  6070. #include <vector>
  6071. #include <memory>
  6072. namespace Catch {
  6073. namespace TestCaseTracking {
  6074. struct NameAndLocation {
  6075. std::string name;
  6076. SourceLineInfo location;
  6077. NameAndLocation( std::string const& _name, SourceLineInfo const& _location );
  6078. friend bool operator==(NameAndLocation const& lhs, NameAndLocation const& rhs) {
  6079. return lhs.name == rhs.name
  6080. && lhs.location == rhs.location;
  6081. }
  6082. };
  6083. class ITracker;
  6084. using ITrackerPtr = std::shared_ptr<ITracker>;
  6085. class ITracker {
  6086. NameAndLocation m_nameAndLocation;
  6087. public:
  6088. ITracker(NameAndLocation const& nameAndLoc) :
  6089. m_nameAndLocation(nameAndLoc)
  6090. {}
  6091. // static queries
  6092. NameAndLocation const& nameAndLocation() const {
  6093. return m_nameAndLocation;
  6094. }
  6095. virtual ~ITracker();
  6096. // dynamic queries
  6097. virtual bool isComplete() const = 0; // Successfully completed or failed
  6098. virtual bool isSuccessfullyCompleted() const = 0;
  6099. virtual bool isOpen() const = 0; // Started but not complete
  6100. virtual bool hasChildren() const = 0;
  6101. virtual bool hasStarted() const = 0;
  6102. virtual ITracker& parent() = 0;
  6103. // actions
  6104. virtual void close() = 0; // Successfully complete
  6105. virtual void fail() = 0;
  6106. virtual void markAsNeedingAnotherRun() = 0;
  6107. virtual void addChild( ITrackerPtr const& child ) = 0;
  6108. virtual ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) = 0;
  6109. virtual void openChild() = 0;
  6110. // Debug/ checking
  6111. virtual bool isSectionTracker() const = 0;
  6112. virtual bool isGeneratorTracker() const = 0;
  6113. };
  6114. class TrackerContext {
  6115. enum RunState {
  6116. NotStarted,
  6117. Executing,
  6118. CompletedCycle
  6119. };
  6120. ITrackerPtr m_rootTracker;
  6121. ITracker* m_currentTracker = nullptr;
  6122. RunState m_runState = NotStarted;
  6123. public:
  6124. ITracker& startRun();
  6125. void endRun();
  6126. void startCycle();
  6127. void completeCycle();
  6128. bool completedCycle() const;
  6129. ITracker& currentTracker();
  6130. void setCurrentTracker( ITracker* tracker );
  6131. };
  6132. class TrackerBase : public ITracker {
  6133. protected:
  6134. enum CycleState {
  6135. NotStarted,
  6136. Executing,
  6137. ExecutingChildren,
  6138. NeedsAnotherRun,
  6139. CompletedSuccessfully,
  6140. Failed
  6141. };
  6142. using Children = std::vector<ITrackerPtr>;
  6143. TrackerContext& m_ctx;
  6144. ITracker* m_parent;
  6145. Children m_children;
  6146. CycleState m_runState = NotStarted;
  6147. public:
  6148. TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  6149. bool isComplete() const override;
  6150. bool isSuccessfullyCompleted() const override;
  6151. bool isOpen() const override;
  6152. bool hasChildren() const override;
  6153. bool hasStarted() const override {
  6154. return m_runState != NotStarted;
  6155. }
  6156. void addChild( ITrackerPtr const& child ) override;
  6157. ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) override;
  6158. ITracker& parent() override;
  6159. void openChild() override;
  6160. bool isSectionTracker() const override;
  6161. bool isGeneratorTracker() const override;
  6162. void open();
  6163. void close() override;
  6164. void fail() override;
  6165. void markAsNeedingAnotherRun() override;
  6166. private:
  6167. void moveToParent();
  6168. void moveToThis();
  6169. };
  6170. class SectionTracker : public TrackerBase {
  6171. std::vector<std::string> m_filters;
  6172. std::string m_trimmed_name;
  6173. public:
  6174. SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  6175. bool isSectionTracker() const override;
  6176. bool isComplete() const override;
  6177. static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation );
  6178. void tryOpen();
  6179. void addInitialFilters( std::vector<std::string> const& filters );
  6180. void addNextFilters( std::vector<std::string> const& filters );
  6181. //! Returns filters active in this tracker
  6182. std::vector<std::string> const& getFilters() const;
  6183. //! Returns whitespace-trimmed name of the tracked section
  6184. std::string const& trimmedName() const;
  6185. };
  6186. } // namespace TestCaseTracking
  6187. using TestCaseTracking::ITracker;
  6188. using TestCaseTracking::TrackerContext;
  6189. using TestCaseTracking::SectionTracker;
  6190. } // namespace Catch
  6191. // end catch_test_case_tracker.h
  6192. // start catch_leak_detector.h
  6193. namespace Catch {
  6194. struct LeakDetector {
  6195. LeakDetector();
  6196. ~LeakDetector();
  6197. };
  6198. }
  6199. // end catch_leak_detector.h
  6200. // Cpp files will be included in the single-header file here
  6201. // start catch_stats.cpp
  6202. // Statistical analysis tools
  6203. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  6204. #include <cassert>
  6205. #include <random>
  6206. #if defined(CATCH_CONFIG_USE_ASYNC)
  6207. #include <future>
  6208. #endif
  6209. namespace {
  6210. double erf_inv(double x) {
  6211. // Code accompanying the article "Approximating the erfinv function" in GPU Computing Gems, Volume 2
  6212. double w, p;
  6213. w = -log((1.0 - x) * (1.0 + x));
  6214. if (w < 6.250000) {
  6215. w = w - 3.125000;
  6216. p = -3.6444120640178196996e-21;
  6217. p = -1.685059138182016589e-19 + p * w;
  6218. p = 1.2858480715256400167e-18 + p * w;
  6219. p = 1.115787767802518096e-17 + p * w;
  6220. p = -1.333171662854620906e-16 + p * w;
  6221. p = 2.0972767875968561637e-17 + p * w;
  6222. p = 6.6376381343583238325e-15 + p * w;
  6223. p = -4.0545662729752068639e-14 + p * w;
  6224. p = -8.1519341976054721522e-14 + p * w;
  6225. p = 2.6335093153082322977e-12 + p * w;
  6226. p = -1.2975133253453532498e-11 + p * w;
  6227. p = -5.4154120542946279317e-11 + p * w;
  6228. p = 1.051212273321532285e-09 + p * w;
  6229. p = -4.1126339803469836976e-09 + p * w;
  6230. p = -2.9070369957882005086e-08 + p * w;
  6231. p = 4.2347877827932403518e-07 + p * w;
  6232. p = -1.3654692000834678645e-06 + p * w;
  6233. p = -1.3882523362786468719e-05 + p * w;
  6234. p = 0.0001867342080340571352 + p * w;
  6235. p = -0.00074070253416626697512 + p * w;
  6236. p = -0.0060336708714301490533 + p * w;
  6237. p = 0.24015818242558961693 + p * w;
  6238. p = 1.6536545626831027356 + p * w;
  6239. } else if (w < 16.000000) {
  6240. w = sqrt(w) - 3.250000;
  6241. p = 2.2137376921775787049e-09;
  6242. p = 9.0756561938885390979e-08 + p * w;
  6243. p = -2.7517406297064545428e-07 + p * w;
  6244. p = 1.8239629214389227755e-08 + p * w;
  6245. p = 1.5027403968909827627e-06 + p * w;
  6246. p = -4.013867526981545969e-06 + p * w;
  6247. p = 2.9234449089955446044e-06 + p * w;
  6248. p = 1.2475304481671778723e-05 + p * w;
  6249. p = -4.7318229009055733981e-05 + p * w;
  6250. p = 6.8284851459573175448e-05 + p * w;
  6251. p = 2.4031110387097893999e-05 + p * w;
  6252. p = -0.0003550375203628474796 + p * w;
  6253. p = 0.00095328937973738049703 + p * w;
  6254. p = -0.0016882755560235047313 + p * w;
  6255. p = 0.0024914420961078508066 + p * w;
  6256. p = -0.0037512085075692412107 + p * w;
  6257. p = 0.005370914553590063617 + p * w;
  6258. p = 1.0052589676941592334 + p * w;
  6259. p = 3.0838856104922207635 + p * w;
  6260. } else {
  6261. w = sqrt(w) - 5.000000;
  6262. p = -2.7109920616438573243e-11;
  6263. p = -2.5556418169965252055e-10 + p * w;
  6264. p = 1.5076572693500548083e-09 + p * w;
  6265. p = -3.7894654401267369937e-09 + p * w;
  6266. p = 7.6157012080783393804e-09 + p * w;
  6267. p = -1.4960026627149240478e-08 + p * w;
  6268. p = 2.9147953450901080826e-08 + p * w;
  6269. p = -6.7711997758452339498e-08 + p * w;
  6270. p = 2.2900482228026654717e-07 + p * w;
  6271. p = -9.9298272942317002539e-07 + p * w;
  6272. p = 4.5260625972231537039e-06 + p * w;
  6273. p = -1.9681778105531670567e-05 + p * w;
  6274. p = 7.5995277030017761139e-05 + p * w;
  6275. p = -0.00021503011930044477347 + p * w;
  6276. p = -0.00013871931833623122026 + p * w;
  6277. p = 1.0103004648645343977 + p * w;
  6278. p = 4.8499064014085844221 + p * w;
  6279. }
  6280. return p * x;
  6281. }
  6282. double standard_deviation(std::vector<double>::iterator first, std::vector<double>::iterator last) {
  6283. auto m = Catch::Benchmark::Detail::mean(first, last);
  6284. double variance = std::accumulate(first, last, 0., [m](double a, double b) {
  6285. double diff = b - m;
  6286. return a + diff * diff;
  6287. }) / (last - first);
  6288. return std::sqrt(variance);
  6289. }
  6290. }
  6291. namespace Catch {
  6292. namespace Benchmark {
  6293. namespace Detail {
  6294. double weighted_average_quantile(int k, int q, std::vector<double>::iterator first, std::vector<double>::iterator last) {
  6295. auto count = last - first;
  6296. double idx = (count - 1) * k / static_cast<double>(q);
  6297. int j = static_cast<int>(idx);
  6298. double g = idx - j;
  6299. std::nth_element(first, first + j, last);
  6300. auto xj = first[j];
  6301. if (g == 0) return xj;
  6302. auto xj1 = *std::min_element(first + (j + 1), last);
  6303. return xj + g * (xj1 - xj);
  6304. }
  6305. double erfc_inv(double x) {
  6306. return erf_inv(1.0 - x);
  6307. }
  6308. double normal_quantile(double p) {
  6309. static const double ROOT_TWO = std::sqrt(2.0);
  6310. double result = 0.0;
  6311. assert(p >= 0 && p <= 1);
  6312. if (p < 0 || p > 1) {
  6313. return result;
  6314. }
  6315. result = -erfc_inv(2.0 * p);
  6316. // result *= normal distribution standard deviation (1.0) * sqrt(2)
  6317. result *= /*sd * */ ROOT_TWO;
  6318. // result += normal disttribution mean (0)
  6319. return result;
  6320. }
  6321. double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n) {
  6322. double sb = stddev.point;
  6323. double mn = mean.point / n;
  6324. double mg_min = mn / 2.;
  6325. double sg = (std::min)(mg_min / 4., sb / std::sqrt(n));
  6326. double sg2 = sg * sg;
  6327. double sb2 = sb * sb;
  6328. auto c_max = [n, mn, sb2, sg2](double x) -> double {
  6329. double k = mn - x;
  6330. double d = k * k;
  6331. double nd = n * d;
  6332. double k0 = -n * nd;
  6333. double k1 = sb2 - n * sg2 + nd;
  6334. double det = k1 * k1 - 4 * sg2 * k0;
  6335. return (int)(-2. * k0 / (k1 + std::sqrt(det)));
  6336. };
  6337. auto var_out = [n, sb2, sg2](double c) {
  6338. double nc = n - c;
  6339. return (nc / n) * (sb2 - nc * sg2);
  6340. };
  6341. return (std::min)(var_out(1), var_out((std::min)(c_max(0.), c_max(mg_min)))) / sb2;
  6342. }
  6343. bootstrap_analysis analyse_samples(double confidence_level, int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last) {
  6344. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION
  6345. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  6346. static std::random_device entropy;
  6347. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
  6348. auto n = static_cast<int>(last - first); // seriously, one can't use integral types without hell in C++
  6349. auto mean = &Detail::mean<std::vector<double>::iterator>;
  6350. auto stddev = &standard_deviation;
  6351. #if defined(CATCH_CONFIG_USE_ASYNC)
  6352. auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
  6353. auto seed = entropy();
  6354. return std::async(std::launch::async, [=] {
  6355. std::mt19937 rng(seed);
  6356. auto resampled = resample(rng, n_resamples, first, last, f);
  6357. return bootstrap(confidence_level, first, last, resampled, f);
  6358. });
  6359. };
  6360. auto mean_future = Estimate(mean);
  6361. auto stddev_future = Estimate(stddev);
  6362. auto mean_estimate = mean_future.get();
  6363. auto stddev_estimate = stddev_future.get();
  6364. #else
  6365. auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
  6366. auto seed = entropy();
  6367. std::mt19937 rng(seed);
  6368. auto resampled = resample(rng, n_resamples, first, last, f);
  6369. return bootstrap(confidence_level, first, last, resampled, f);
  6370. };
  6371. auto mean_estimate = Estimate(mean);
  6372. auto stddev_estimate = Estimate(stddev);
  6373. #endif // CATCH_USE_ASYNC
  6374. double outlier_variance = Detail::outlier_variance(mean_estimate, stddev_estimate, n);
  6375. return { mean_estimate, stddev_estimate, outlier_variance };
  6376. }
  6377. } // namespace Detail
  6378. } // namespace Benchmark
  6379. } // namespace Catch
  6380. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  6381. // end catch_stats.cpp
  6382. // start catch_approx.cpp
  6383. #include <cmath>
  6384. #include <limits>
  6385. namespace {
  6386. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  6387. // But without the subtraction to allow for INFINITY in comparison
  6388. bool marginComparison(double lhs, double rhs, double margin) {
  6389. return (lhs + margin >= rhs) && (rhs + margin >= lhs);
  6390. }
  6391. }
  6392. namespace Catch {
  6393. namespace Detail {
  6394. Approx::Approx ( double value )
  6395. : m_epsilon( std::numeric_limits<float>::epsilon()*100 ),
  6396. m_margin( 0.0 ),
  6397. m_scale( 0.0 ),
  6398. m_value( value )
  6399. {}
  6400. Approx Approx::custom() {
  6401. return Approx( 0 );
  6402. }
  6403. Approx Approx::operator-() const {
  6404. auto temp(*this);
  6405. temp.m_value = -temp.m_value;
  6406. return temp;
  6407. }
  6408. std::string Approx::toString() const {
  6409. ReusableStringStream rss;
  6410. rss << "Approx( " << ::Catch::Detail::stringify( m_value ) << " )";
  6411. return rss.str();
  6412. }
  6413. bool Approx::equalityComparisonImpl(const double other) const {
  6414. // First try with fixed margin, then compute margin based on epsilon, scale and Approx's value
  6415. // Thanks to Richard Harris for his help refining the scaled margin value
  6416. return marginComparison(m_value, other, m_margin)
  6417. || marginComparison(m_value, other, m_epsilon * (m_scale + std::fabs(std::isinf(m_value)? 0 : m_value)));
  6418. }
  6419. void Approx::setMargin(double newMargin) {
  6420. CATCH_ENFORCE(newMargin >= 0,
  6421. "Invalid Approx::margin: " << newMargin << '.'
  6422. << " Approx::Margin has to be non-negative.");
  6423. m_margin = newMargin;
  6424. }
  6425. void Approx::setEpsilon(double newEpsilon) {
  6426. CATCH_ENFORCE(newEpsilon >= 0 && newEpsilon <= 1.0,
  6427. "Invalid Approx::epsilon: " << newEpsilon << '.'
  6428. << " Approx::epsilon has to be in [0, 1]");
  6429. m_epsilon = newEpsilon;
  6430. }
  6431. } // end namespace Detail
  6432. namespace literals {
  6433. Detail::Approx operator "" _a(long double val) {
  6434. return Detail::Approx(val);
  6435. }
  6436. Detail::Approx operator "" _a(unsigned long long val) {
  6437. return Detail::Approx(val);
  6438. }
  6439. } // end namespace literals
  6440. std::string StringMaker<Catch::Detail::Approx>::convert(Catch::Detail::Approx const& value) {
  6441. return value.toString();
  6442. }
  6443. } // end namespace Catch
  6444. // end catch_approx.cpp
  6445. // start catch_assertionhandler.cpp
  6446. // start catch_debugger.h
  6447. namespace Catch {
  6448. bool isDebuggerActive();
  6449. }
  6450. #ifdef CATCH_PLATFORM_MAC
  6451. #if defined(__i386__) || defined(__x86_64__)
  6452. #define CATCH_TRAP() __asm__("int $3\n" : : ) /* NOLINT */
  6453. #elif defined(__aarch64__)
  6454. #define CATCH_TRAP() __asm__(".inst 0xd4200000")
  6455. #endif
  6456. #elif defined(CATCH_PLATFORM_IPHONE)
  6457. // use inline assembler
  6458. #if defined(__i386__) || defined(__x86_64__)
  6459. #define CATCH_TRAP() __asm__("int $3")
  6460. #elif defined(__aarch64__)
  6461. #define CATCH_TRAP() __asm__(".inst 0xd4200000")
  6462. #elif defined(__arm__) && !defined(__thumb__)
  6463. #define CATCH_TRAP() __asm__(".inst 0xe7f001f0")
  6464. #elif defined(__arm__) && defined(__thumb__)
  6465. #define CATCH_TRAP() __asm__(".inst 0xde01")
  6466. #endif
  6467. #elif defined(CATCH_PLATFORM_LINUX)
  6468. // If we can use inline assembler, do it because this allows us to break
  6469. // directly at the location of the failing check instead of breaking inside
  6470. // raise() called from it, i.e. one stack frame below.
  6471. #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64))
  6472. #define CATCH_TRAP() asm volatile ("int $3") /* NOLINT */
  6473. #else // Fall back to the generic way.
  6474. #include <signal.h>
  6475. #define CATCH_TRAP() raise(SIGTRAP)
  6476. #endif
  6477. #elif defined(_MSC_VER)
  6478. #define CATCH_TRAP() __debugbreak()
  6479. #elif defined(__MINGW32__)
  6480. extern "C" __declspec(dllimport) void __stdcall DebugBreak();
  6481. #define CATCH_TRAP() DebugBreak()
  6482. #endif
  6483. #ifndef CATCH_BREAK_INTO_DEBUGGER
  6484. #ifdef CATCH_TRAP
  6485. #define CATCH_BREAK_INTO_DEBUGGER() []{ if( Catch::isDebuggerActive() ) { CATCH_TRAP(); } }()
  6486. #else
  6487. #define CATCH_BREAK_INTO_DEBUGGER() []{}()
  6488. #endif
  6489. #endif
  6490. // end catch_debugger.h
  6491. // start catch_run_context.h
  6492. // start catch_fatal_condition.h
  6493. #include <cassert>
  6494. namespace Catch {
  6495. // Wrapper for platform-specific fatal error (signals/SEH) handlers
  6496. //
  6497. // Tries to be cooperative with other handlers, and not step over
  6498. // other handlers. This means that unknown structured exceptions
  6499. // are passed on, previous signal handlers are called, and so on.
  6500. //
  6501. // Can only be instantiated once, and assumes that once a signal
  6502. // is caught, the binary will end up terminating. Thus, there
  6503. class FatalConditionHandler {
  6504. bool m_started = false;
  6505. // Install/disengage implementation for specific platform.
  6506. // Should be if-defed to work on current platform, can assume
  6507. // engage-disengage 1:1 pairing.
  6508. void engage_platform();
  6509. void disengage_platform();
  6510. public:
  6511. // Should also have platform-specific implementations as needed
  6512. FatalConditionHandler();
  6513. ~FatalConditionHandler();
  6514. void engage() {
  6515. assert(!m_started && "Handler cannot be installed twice.");
  6516. m_started = true;
  6517. engage_platform();
  6518. }
  6519. void disengage() {
  6520. assert(m_started && "Handler cannot be uninstalled without being installed first");
  6521. m_started = false;
  6522. disengage_platform();
  6523. }
  6524. };
  6525. //! Simple RAII guard for (dis)engaging the FatalConditionHandler
  6526. class FatalConditionHandlerGuard {
  6527. FatalConditionHandler* m_handler;
  6528. public:
  6529. FatalConditionHandlerGuard(FatalConditionHandler* handler):
  6530. m_handler(handler) {
  6531. m_handler->engage();
  6532. }
  6533. ~FatalConditionHandlerGuard() {
  6534. m_handler->disengage();
  6535. }
  6536. };
  6537. } // end namespace Catch
  6538. // end catch_fatal_condition.h
  6539. #include <string>
  6540. namespace Catch {
  6541. struct IMutableContext;
  6542. ///////////////////////////////////////////////////////////////////////////
  6543. class RunContext : public IResultCapture, public IRunner {
  6544. public:
  6545. RunContext( RunContext const& ) = delete;
  6546. RunContext& operator =( RunContext const& ) = delete;
  6547. explicit RunContext( IConfigPtr const& _config, IStreamingReporterPtr&& reporter );
  6548. ~RunContext() override;
  6549. void testGroupStarting( std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount );
  6550. void testGroupEnded( std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount );
  6551. Totals runTest(TestCase const& testCase);
  6552. IConfigPtr config() const;
  6553. IStreamingReporter& reporter() const;
  6554. public: // IResultCapture
  6555. // Assertion handlers
  6556. void handleExpr
  6557. ( AssertionInfo const& info,
  6558. ITransientExpression const& expr,
  6559. AssertionReaction& reaction ) override;
  6560. void handleMessage
  6561. ( AssertionInfo const& info,
  6562. ResultWas::OfType resultType,
  6563. StringRef const& message,
  6564. AssertionReaction& reaction ) override;
  6565. void handleUnexpectedExceptionNotThrown
  6566. ( AssertionInfo const& info,
  6567. AssertionReaction& reaction ) override;
  6568. void handleUnexpectedInflightException
  6569. ( AssertionInfo const& info,
  6570. std::string const& message,
  6571. AssertionReaction& reaction ) override;
  6572. void handleIncomplete
  6573. ( AssertionInfo const& info ) override;
  6574. void handleNonExpr
  6575. ( AssertionInfo const &info,
  6576. ResultWas::OfType resultType,
  6577. AssertionReaction &reaction ) override;
  6578. bool sectionStarted( SectionInfo const& sectionInfo, Counts& assertions ) override;
  6579. void sectionEnded( SectionEndInfo const& endInfo ) override;
  6580. void sectionEndedEarly( SectionEndInfo const& endInfo ) override;
  6581. auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker& override;
  6582. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  6583. void benchmarkPreparing( std::string const& name ) override;
  6584. void benchmarkStarting( BenchmarkInfo const& info ) override;
  6585. void benchmarkEnded( BenchmarkStats<> const& stats ) override;
  6586. void benchmarkFailed( std::string const& error ) override;
  6587. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  6588. void pushScopedMessage( MessageInfo const& message ) override;
  6589. void popScopedMessage( MessageInfo const& message ) override;
  6590. void emplaceUnscopedMessage( MessageBuilder const& builder ) override;
  6591. std::string getCurrentTestName() const override;
  6592. const AssertionResult* getLastResult() const override;
  6593. void exceptionEarlyReported() override;
  6594. void handleFatalErrorCondition( StringRef message ) override;
  6595. bool lastAssertionPassed() override;
  6596. void assertionPassed() override;
  6597. public:
  6598. // !TBD We need to do this another way!
  6599. bool aborting() const final;
  6600. private:
  6601. void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr );
  6602. void invokeActiveTestCase();
  6603. void resetAssertionInfo();
  6604. bool testForMissingAssertions( Counts& assertions );
  6605. void assertionEnded( AssertionResult const& result );
  6606. void reportExpr
  6607. ( AssertionInfo const &info,
  6608. ResultWas::OfType resultType,
  6609. ITransientExpression const *expr,
  6610. bool negated );
  6611. void populateReaction( AssertionReaction& reaction );
  6612. private:
  6613. void handleUnfinishedSections();
  6614. TestRunInfo m_runInfo;
  6615. IMutableContext& m_context;
  6616. TestCase const* m_activeTestCase = nullptr;
  6617. ITracker* m_testCaseTracker = nullptr;
  6618. Option<AssertionResult> m_lastResult;
  6619. IConfigPtr m_config;
  6620. Totals m_totals;
  6621. IStreamingReporterPtr m_reporter;
  6622. std::vector<MessageInfo> m_messages;
  6623. std::vector<ScopedMessage> m_messageScopes; /* Keeps owners of so-called unscoped messages. */
  6624. AssertionInfo m_lastAssertionInfo;
  6625. std::vector<SectionEndInfo> m_unfinishedSections;
  6626. std::vector<ITracker*> m_activeSections;
  6627. TrackerContext m_trackerContext;
  6628. FatalConditionHandler m_fatalConditionhandler;
  6629. bool m_lastAssertionPassed = false;
  6630. bool m_shouldReportUnexpected = true;
  6631. bool m_includeSuccessfulResults;
  6632. };
  6633. void seedRng(IConfig const& config);
  6634. unsigned int rngSeed();
  6635. } // end namespace Catch
  6636. // end catch_run_context.h
  6637. namespace Catch {
  6638. namespace {
  6639. auto operator <<( std::ostream& os, ITransientExpression const& expr ) -> std::ostream& {
  6640. expr.streamReconstructedExpression( os );
  6641. return os;
  6642. }
  6643. }
  6644. LazyExpression::LazyExpression( bool isNegated )
  6645. : m_isNegated( isNegated )
  6646. {}
  6647. LazyExpression::LazyExpression( LazyExpression const& other ) : m_isNegated( other.m_isNegated ) {}
  6648. LazyExpression::operator bool() const {
  6649. return m_transientExpression != nullptr;
  6650. }
  6651. auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream& {
  6652. if( lazyExpr.m_isNegated )
  6653. os << "!";
  6654. if( lazyExpr ) {
  6655. if( lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression() )
  6656. os << "(" << *lazyExpr.m_transientExpression << ")";
  6657. else
  6658. os << *lazyExpr.m_transientExpression;
  6659. }
  6660. else {
  6661. os << "{** error - unchecked empty expression requested **}";
  6662. }
  6663. return os;
  6664. }
  6665. AssertionHandler::AssertionHandler
  6666. ( StringRef const& macroName,
  6667. SourceLineInfo const& lineInfo,
  6668. StringRef capturedExpression,
  6669. ResultDisposition::Flags resultDisposition )
  6670. : m_assertionInfo{ macroName, lineInfo, capturedExpression, resultDisposition },
  6671. m_resultCapture( getResultCapture() )
  6672. {}
  6673. void AssertionHandler::handleExpr( ITransientExpression const& expr ) {
  6674. m_resultCapture.handleExpr( m_assertionInfo, expr, m_reaction );
  6675. }
  6676. void AssertionHandler::handleMessage(ResultWas::OfType resultType, StringRef const& message) {
  6677. m_resultCapture.handleMessage( m_assertionInfo, resultType, message, m_reaction );
  6678. }
  6679. auto AssertionHandler::allowThrows() const -> bool {
  6680. return getCurrentContext().getConfig()->allowThrows();
  6681. }
  6682. void AssertionHandler::complete() {
  6683. setCompleted();
  6684. if( m_reaction.shouldDebugBreak ) {
  6685. // If you find your debugger stopping you here then go one level up on the
  6686. // call-stack for the code that caused it (typically a failed assertion)
  6687. // (To go back to the test and change execution, jump over the throw, next)
  6688. CATCH_BREAK_INTO_DEBUGGER();
  6689. }
  6690. if (m_reaction.shouldThrow) {
  6691. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  6692. throw Catch::TestFailureException();
  6693. #else
  6694. CATCH_ERROR( "Test failure requires aborting test!" );
  6695. #endif
  6696. }
  6697. }
  6698. void AssertionHandler::setCompleted() {
  6699. m_completed = true;
  6700. }
  6701. void AssertionHandler::handleUnexpectedInflightException() {
  6702. m_resultCapture.handleUnexpectedInflightException( m_assertionInfo, Catch::translateActiveException(), m_reaction );
  6703. }
  6704. void AssertionHandler::handleExceptionThrownAsExpected() {
  6705. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  6706. }
  6707. void AssertionHandler::handleExceptionNotThrownAsExpected() {
  6708. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  6709. }
  6710. void AssertionHandler::handleUnexpectedExceptionNotThrown() {
  6711. m_resultCapture.handleUnexpectedExceptionNotThrown( m_assertionInfo, m_reaction );
  6712. }
  6713. void AssertionHandler::handleThrowingCallSkipped() {
  6714. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  6715. }
  6716. // This is the overload that takes a string and infers the Equals matcher from it
  6717. // The more general overload, that takes any string matcher, is in catch_capture_matchers.cpp
  6718. void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString ) {
  6719. handleExceptionMatchExpr( handler, Matchers::Equals( str ), matcherString );
  6720. }
  6721. } // namespace Catch
  6722. // end catch_assertionhandler.cpp
  6723. // start catch_assertionresult.cpp
  6724. namespace Catch {
  6725. AssertionResultData::AssertionResultData(ResultWas::OfType _resultType, LazyExpression const & _lazyExpression):
  6726. lazyExpression(_lazyExpression),
  6727. resultType(_resultType) {}
  6728. std::string AssertionResultData::reconstructExpression() const {
  6729. if( reconstructedExpression.empty() ) {
  6730. if( lazyExpression ) {
  6731. ReusableStringStream rss;
  6732. rss << lazyExpression;
  6733. reconstructedExpression = rss.str();
  6734. }
  6735. }
  6736. return reconstructedExpression;
  6737. }
  6738. AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data )
  6739. : m_info( info ),
  6740. m_resultData( data )
  6741. {}
  6742. // Result was a success
  6743. bool AssertionResult::succeeded() const {
  6744. return Catch::isOk( m_resultData.resultType );
  6745. }
  6746. // Result was a success, or failure is suppressed
  6747. bool AssertionResult::isOk() const {
  6748. return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition );
  6749. }
  6750. ResultWas::OfType AssertionResult::getResultType() const {
  6751. return m_resultData.resultType;
  6752. }
  6753. bool AssertionResult::hasExpression() const {
  6754. return !m_info.capturedExpression.empty();
  6755. }
  6756. bool AssertionResult::hasMessage() const {
  6757. return !m_resultData.message.empty();
  6758. }
  6759. std::string AssertionResult::getExpression() const {
  6760. // Possibly overallocating by 3 characters should be basically free
  6761. std::string expr; expr.reserve(m_info.capturedExpression.size() + 3);
  6762. if (isFalseTest(m_info.resultDisposition)) {
  6763. expr += "!(";
  6764. }
  6765. expr += m_info.capturedExpression;
  6766. if (isFalseTest(m_info.resultDisposition)) {
  6767. expr += ')';
  6768. }
  6769. return expr;
  6770. }
  6771. std::string AssertionResult::getExpressionInMacro() const {
  6772. std::string expr;
  6773. if( m_info.macroName.empty() )
  6774. expr = static_cast<std::string>(m_info.capturedExpression);
  6775. else {
  6776. expr.reserve( m_info.macroName.size() + m_info.capturedExpression.size() + 4 );
  6777. expr += m_info.macroName;
  6778. expr += "( ";
  6779. expr += m_info.capturedExpression;
  6780. expr += " )";
  6781. }
  6782. return expr;
  6783. }
  6784. bool AssertionResult::hasExpandedExpression() const {
  6785. return hasExpression() && getExpandedExpression() != getExpression();
  6786. }
  6787. std::string AssertionResult::getExpandedExpression() const {
  6788. std::string expr = m_resultData.reconstructExpression();
  6789. return expr.empty()
  6790. ? getExpression()
  6791. : expr;
  6792. }
  6793. std::string AssertionResult::getMessage() const {
  6794. return m_resultData.message;
  6795. }
  6796. SourceLineInfo AssertionResult::getSourceInfo() const {
  6797. return m_info.lineInfo;
  6798. }
  6799. StringRef AssertionResult::getTestMacroName() const {
  6800. return m_info.macroName;
  6801. }
  6802. } // end namespace Catch
  6803. // end catch_assertionresult.cpp
  6804. // start catch_capture_matchers.cpp
  6805. namespace Catch {
  6806. using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
  6807. // This is the general overload that takes a any string matcher
  6808. // There is another overload, in catch_assertionhandler.h/.cpp, that only takes a string and infers
  6809. // the Equals matcher (so the header does not mention matchers)
  6810. void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString ) {
  6811. std::string exceptionMessage = Catch::translateActiveException();
  6812. MatchExpr<std::string, StringMatcher const&> expr( exceptionMessage, matcher, matcherString );
  6813. handler.handleExpr( expr );
  6814. }
  6815. } // namespace Catch
  6816. // end catch_capture_matchers.cpp
  6817. // start catch_commandline.cpp
  6818. // start catch_commandline.h
  6819. // start catch_clara.h
  6820. // Use Catch's value for console width (store Clara's off to the side, if present)
  6821. #ifdef CLARA_CONFIG_CONSOLE_WIDTH
  6822. #define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  6823. #undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  6824. #endif
  6825. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH-1
  6826. #ifdef __clang__
  6827. #pragma clang diagnostic push
  6828. #pragma clang diagnostic ignored "-Wweak-vtables"
  6829. #pragma clang diagnostic ignored "-Wexit-time-destructors"
  6830. #pragma clang diagnostic ignored "-Wshadow"
  6831. #endif
  6832. // start clara.hpp
  6833. // Copyright 2017 Two Blue Cubes Ltd. All rights reserved.
  6834. //
  6835. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  6836. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6837. //
  6838. // See https://github.com/philsquared/Clara for more details
  6839. // Clara v1.1.5
  6840. #ifndef CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  6841. #define CATCH_CLARA_CONFIG_CONSOLE_WIDTH 80
  6842. #endif
  6843. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  6844. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  6845. #endif
  6846. #ifndef CLARA_CONFIG_OPTIONAL_TYPE
  6847. #ifdef __has_include
  6848. #if __has_include(<optional>) && __cplusplus >= 201703L
  6849. #include <optional>
  6850. #define CLARA_CONFIG_OPTIONAL_TYPE std::optional
  6851. #endif
  6852. #endif
  6853. #endif
  6854. // ----------- #included from clara_textflow.hpp -----------
  6855. // TextFlowCpp
  6856. //
  6857. // A single-header library for wrapping and laying out basic text, by Phil Nash
  6858. //
  6859. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  6860. // file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6861. //
  6862. // This project is hosted at https://github.com/philsquared/textflowcpp
  6863. #include <cassert>
  6864. #include <ostream>
  6865. #include <sstream>
  6866. #include <vector>
  6867. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  6868. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80
  6869. #endif
  6870. namespace Catch {
  6871. namespace clara {
  6872. namespace TextFlow {
  6873. inline auto isWhitespace(char c) -> bool {
  6874. static std::string chars = " \t\n\r";
  6875. return chars.find(c) != std::string::npos;
  6876. }
  6877. inline auto isBreakableBefore(char c) -> bool {
  6878. static std::string chars = "[({<|";
  6879. return chars.find(c) != std::string::npos;
  6880. }
  6881. inline auto isBreakableAfter(char c) -> bool {
  6882. static std::string chars = "])}>.,:;*+-=&/\\";
  6883. return chars.find(c) != std::string::npos;
  6884. }
  6885. class Columns;
  6886. class Column {
  6887. std::vector<std::string> m_strings;
  6888. size_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH;
  6889. size_t m_indent = 0;
  6890. size_t m_initialIndent = std::string::npos;
  6891. public:
  6892. class iterator {
  6893. friend Column;
  6894. Column const& m_column;
  6895. size_t m_stringIndex = 0;
  6896. size_t m_pos = 0;
  6897. size_t m_len = 0;
  6898. size_t m_end = 0;
  6899. bool m_suffix = false;
  6900. iterator(Column const& column, size_t stringIndex)
  6901. : m_column(column),
  6902. m_stringIndex(stringIndex) {}
  6903. auto line() const -> std::string const& { return m_column.m_strings[m_stringIndex]; }
  6904. auto isBoundary(size_t at) const -> bool {
  6905. assert(at > 0);
  6906. assert(at <= line().size());
  6907. return at == line().size() ||
  6908. (isWhitespace(line()[at]) && !isWhitespace(line()[at - 1])) ||
  6909. isBreakableBefore(line()[at]) ||
  6910. isBreakableAfter(line()[at - 1]);
  6911. }
  6912. void calcLength() {
  6913. assert(m_stringIndex < m_column.m_strings.size());
  6914. m_suffix = false;
  6915. auto width = m_column.m_width - indent();
  6916. m_end = m_pos;
  6917. if (line()[m_pos] == '\n') {
  6918. ++m_end;
  6919. }
  6920. while (m_end < line().size() && line()[m_end] != '\n')
  6921. ++m_end;
  6922. if (m_end < m_pos + width) {
  6923. m_len = m_end - m_pos;
  6924. } else {
  6925. size_t len = width;
  6926. while (len > 0 && !isBoundary(m_pos + len))
  6927. --len;
  6928. while (len > 0 && isWhitespace(line()[m_pos + len - 1]))
  6929. --len;
  6930. if (len > 0) {
  6931. m_len = len;
  6932. } else {
  6933. m_suffix = true;
  6934. m_len = width - 1;
  6935. }
  6936. }
  6937. }
  6938. auto indent() const -> size_t {
  6939. auto initial = m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos;
  6940. return initial == std::string::npos ? m_column.m_indent : initial;
  6941. }
  6942. auto addIndentAndSuffix(std::string const &plain) const -> std::string {
  6943. return std::string(indent(), ' ') + (m_suffix ? plain + "-" : plain);
  6944. }
  6945. public:
  6946. using difference_type = std::ptrdiff_t;
  6947. using value_type = std::string;
  6948. using pointer = value_type * ;
  6949. using reference = value_type & ;
  6950. using iterator_category = std::forward_iterator_tag;
  6951. explicit iterator(Column const& column) : m_column(column) {
  6952. assert(m_column.m_width > m_column.m_indent);
  6953. assert(m_column.m_initialIndent == std::string::npos || m_column.m_width > m_column.m_initialIndent);
  6954. calcLength();
  6955. if (m_len == 0)
  6956. m_stringIndex++; // Empty string
  6957. }
  6958. auto operator *() const -> std::string {
  6959. assert(m_stringIndex < m_column.m_strings.size());
  6960. assert(m_pos <= m_end);
  6961. return addIndentAndSuffix(line().substr(m_pos, m_len));
  6962. }
  6963. auto operator ++() -> iterator& {
  6964. m_pos += m_len;
  6965. if (m_pos < line().size() && line()[m_pos] == '\n')
  6966. m_pos += 1;
  6967. else
  6968. while (m_pos < line().size() && isWhitespace(line()[m_pos]))
  6969. ++m_pos;
  6970. if (m_pos == line().size()) {
  6971. m_pos = 0;
  6972. ++m_stringIndex;
  6973. }
  6974. if (m_stringIndex < m_column.m_strings.size())
  6975. calcLength();
  6976. return *this;
  6977. }
  6978. auto operator ++(int) -> iterator {
  6979. iterator prev(*this);
  6980. operator++();
  6981. return prev;
  6982. }
  6983. auto operator ==(iterator const& other) const -> bool {
  6984. return
  6985. m_pos == other.m_pos &&
  6986. m_stringIndex == other.m_stringIndex &&
  6987. &m_column == &other.m_column;
  6988. }
  6989. auto operator !=(iterator const& other) const -> bool {
  6990. return !operator==(other);
  6991. }
  6992. };
  6993. using const_iterator = iterator;
  6994. explicit Column(std::string const& text) { m_strings.push_back(text); }
  6995. auto width(size_t newWidth) -> Column& {
  6996. assert(newWidth > 0);
  6997. m_width = newWidth;
  6998. return *this;
  6999. }
  7000. auto indent(size_t newIndent) -> Column& {
  7001. m_indent = newIndent;
  7002. return *this;
  7003. }
  7004. auto initialIndent(size_t newIndent) -> Column& {
  7005. m_initialIndent = newIndent;
  7006. return *this;
  7007. }
  7008. auto width() const -> size_t { return m_width; }
  7009. auto begin() const -> iterator { return iterator(*this); }
  7010. auto end() const -> iterator { return { *this, m_strings.size() }; }
  7011. inline friend std::ostream& operator << (std::ostream& os, Column const& col) {
  7012. bool first = true;
  7013. for (auto line : col) {
  7014. if (first)
  7015. first = false;
  7016. else
  7017. os << "\n";
  7018. os << line;
  7019. }
  7020. return os;
  7021. }
  7022. auto operator + (Column const& other)->Columns;
  7023. auto toString() const -> std::string {
  7024. std::ostringstream oss;
  7025. oss << *this;
  7026. return oss.str();
  7027. }
  7028. };
  7029. class Spacer : public Column {
  7030. public:
  7031. explicit Spacer(size_t spaceWidth) : Column("") {
  7032. width(spaceWidth);
  7033. }
  7034. };
  7035. class Columns {
  7036. std::vector<Column> m_columns;
  7037. public:
  7038. class iterator {
  7039. friend Columns;
  7040. struct EndTag {};
  7041. std::vector<Column> const& m_columns;
  7042. std::vector<Column::iterator> m_iterators;
  7043. size_t m_activeIterators;
  7044. iterator(Columns const& columns, EndTag)
  7045. : m_columns(columns.m_columns),
  7046. m_activeIterators(0) {
  7047. m_iterators.reserve(m_columns.size());
  7048. for (auto const& col : m_columns)
  7049. m_iterators.push_back(col.end());
  7050. }
  7051. public:
  7052. using difference_type = std::ptrdiff_t;
  7053. using value_type = std::string;
  7054. using pointer = value_type * ;
  7055. using reference = value_type & ;
  7056. using iterator_category = std::forward_iterator_tag;
  7057. explicit iterator(Columns const& columns)
  7058. : m_columns(columns.m_columns),
  7059. m_activeIterators(m_columns.size()) {
  7060. m_iterators.reserve(m_columns.size());
  7061. for (auto const& col : m_columns)
  7062. m_iterators.push_back(col.begin());
  7063. }
  7064. auto operator ==(iterator const& other) const -> bool {
  7065. return m_iterators == other.m_iterators;
  7066. }
  7067. auto operator !=(iterator const& other) const -> bool {
  7068. return m_iterators != other.m_iterators;
  7069. }
  7070. auto operator *() const -> std::string {
  7071. std::string row, padding;
  7072. for (size_t i = 0; i < m_columns.size(); ++i) {
  7073. auto width = m_columns[i].width();
  7074. if (m_iterators[i] != m_columns[i].end()) {
  7075. std::string col = *m_iterators[i];
  7076. row += padding + col;
  7077. if (col.size() < width)
  7078. padding = std::string(width - col.size(), ' ');
  7079. else
  7080. padding = "";
  7081. } else {
  7082. padding += std::string(width, ' ');
  7083. }
  7084. }
  7085. return row;
  7086. }
  7087. auto operator ++() -> iterator& {
  7088. for (size_t i = 0; i < m_columns.size(); ++i) {
  7089. if (m_iterators[i] != m_columns[i].end())
  7090. ++m_iterators[i];
  7091. }
  7092. return *this;
  7093. }
  7094. auto operator ++(int) -> iterator {
  7095. iterator prev(*this);
  7096. operator++();
  7097. return prev;
  7098. }
  7099. };
  7100. using const_iterator = iterator;
  7101. auto begin() const -> iterator { return iterator(*this); }
  7102. auto end() const -> iterator { return { *this, iterator::EndTag() }; }
  7103. auto operator += (Column const& col) -> Columns& {
  7104. m_columns.push_back(col);
  7105. return *this;
  7106. }
  7107. auto operator + (Column const& col) -> Columns {
  7108. Columns combined = *this;
  7109. combined += col;
  7110. return combined;
  7111. }
  7112. inline friend std::ostream& operator << (std::ostream& os, Columns const& cols) {
  7113. bool first = true;
  7114. for (auto line : cols) {
  7115. if (first)
  7116. first = false;
  7117. else
  7118. os << "\n";
  7119. os << line;
  7120. }
  7121. return os;
  7122. }
  7123. auto toString() const -> std::string {
  7124. std::ostringstream oss;
  7125. oss << *this;
  7126. return oss.str();
  7127. }
  7128. };
  7129. inline auto Column::operator + (Column const& other) -> Columns {
  7130. Columns cols;
  7131. cols += *this;
  7132. cols += other;
  7133. return cols;
  7134. }
  7135. }
  7136. }
  7137. }
  7138. // ----------- end of #include from clara_textflow.hpp -----------
  7139. // ........... back in clara.hpp
  7140. #include <cctype>
  7141. #include <string>
  7142. #include <memory>
  7143. #include <set>
  7144. #include <algorithm>
  7145. #if !defined(CATCH_PLATFORM_WINDOWS) && ( defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) )
  7146. #define CATCH_PLATFORM_WINDOWS
  7147. #endif
  7148. namespace Catch { namespace clara {
  7149. namespace detail {
  7150. // Traits for extracting arg and return type of lambdas (for single argument lambdas)
  7151. template<typename L>
  7152. struct UnaryLambdaTraits : UnaryLambdaTraits<decltype( &L::operator() )> {};
  7153. template<typename ClassT, typename ReturnT, typename... Args>
  7154. struct UnaryLambdaTraits<ReturnT( ClassT::* )( Args... ) const> {
  7155. static const bool isValid = false;
  7156. };
  7157. template<typename ClassT, typename ReturnT, typename ArgT>
  7158. struct UnaryLambdaTraits<ReturnT( ClassT::* )( ArgT ) const> {
  7159. static const bool isValid = true;
  7160. using ArgType = typename std::remove_const<typename std::remove_reference<ArgT>::type>::type;
  7161. using ReturnType = ReturnT;
  7162. };
  7163. class TokenStream;
  7164. // Transport for raw args (copied from main args, or supplied via init list for testing)
  7165. class Args {
  7166. friend TokenStream;
  7167. std::string m_exeName;
  7168. std::vector<std::string> m_args;
  7169. public:
  7170. Args( int argc, char const* const* argv )
  7171. : m_exeName(argv[0]),
  7172. m_args(argv + 1, argv + argc) {}
  7173. Args( std::initializer_list<std::string> args )
  7174. : m_exeName( *args.begin() ),
  7175. m_args( args.begin()+1, args.end() )
  7176. {}
  7177. auto exeName() const -> std::string {
  7178. return m_exeName;
  7179. }
  7180. };
  7181. // Wraps a token coming from a token stream. These may not directly correspond to strings as a single string
  7182. // may encode an option + its argument if the : or = form is used
  7183. enum class TokenType {
  7184. Option, Argument
  7185. };
  7186. struct Token {
  7187. TokenType type;
  7188. std::string token;
  7189. };
  7190. inline auto isOptPrefix( char c ) -> bool {
  7191. return c == '-'
  7192. #ifdef CATCH_PLATFORM_WINDOWS
  7193. || c == '/'
  7194. #endif
  7195. ;
  7196. }
  7197. // Abstracts iterators into args as a stream of tokens, with option arguments uniformly handled
  7198. class TokenStream {
  7199. using Iterator = std::vector<std::string>::const_iterator;
  7200. Iterator it;
  7201. Iterator itEnd;
  7202. std::vector<Token> m_tokenBuffer;
  7203. void loadBuffer() {
  7204. m_tokenBuffer.resize( 0 );
  7205. // Skip any empty strings
  7206. while( it != itEnd && it->empty() )
  7207. ++it;
  7208. if( it != itEnd ) {
  7209. auto const &next = *it;
  7210. if( isOptPrefix( next[0] ) ) {
  7211. auto delimiterPos = next.find_first_of( " :=" );
  7212. if( delimiterPos != std::string::npos ) {
  7213. m_tokenBuffer.push_back( { TokenType::Option, next.substr( 0, delimiterPos ) } );
  7214. m_tokenBuffer.push_back( { TokenType::Argument, next.substr( delimiterPos + 1 ) } );
  7215. } else {
  7216. if( next[1] != '-' && next.size() > 2 ) {
  7217. std::string opt = "- ";
  7218. for( size_t i = 1; i < next.size(); ++i ) {
  7219. opt[1] = next[i];
  7220. m_tokenBuffer.push_back( { TokenType::Option, opt } );
  7221. }
  7222. } else {
  7223. m_tokenBuffer.push_back( { TokenType::Option, next } );
  7224. }
  7225. }
  7226. } else {
  7227. m_tokenBuffer.push_back( { TokenType::Argument, next } );
  7228. }
  7229. }
  7230. }
  7231. public:
  7232. explicit TokenStream( Args const &args ) : TokenStream( args.m_args.begin(), args.m_args.end() ) {}
  7233. TokenStream( Iterator it, Iterator itEnd ) : it( it ), itEnd( itEnd ) {
  7234. loadBuffer();
  7235. }
  7236. explicit operator bool() const {
  7237. return !m_tokenBuffer.empty() || it != itEnd;
  7238. }
  7239. auto count() const -> size_t { return m_tokenBuffer.size() + (itEnd - it); }
  7240. auto operator*() const -> Token {
  7241. assert( !m_tokenBuffer.empty() );
  7242. return m_tokenBuffer.front();
  7243. }
  7244. auto operator->() const -> Token const * {
  7245. assert( !m_tokenBuffer.empty() );
  7246. return &m_tokenBuffer.front();
  7247. }
  7248. auto operator++() -> TokenStream & {
  7249. if( m_tokenBuffer.size() >= 2 ) {
  7250. m_tokenBuffer.erase( m_tokenBuffer.begin() );
  7251. } else {
  7252. if( it != itEnd )
  7253. ++it;
  7254. loadBuffer();
  7255. }
  7256. return *this;
  7257. }
  7258. };
  7259. class ResultBase {
  7260. public:
  7261. enum Type {
  7262. Ok, LogicError, RuntimeError
  7263. };
  7264. protected:
  7265. ResultBase( Type type ) : m_type( type ) {}
  7266. virtual ~ResultBase() = default;
  7267. virtual void enforceOk() const = 0;
  7268. Type m_type;
  7269. };
  7270. template<typename T>
  7271. class ResultValueBase : public ResultBase {
  7272. public:
  7273. auto value() const -> T const & {
  7274. enforceOk();
  7275. return m_value;
  7276. }
  7277. protected:
  7278. ResultValueBase( Type type ) : ResultBase( type ) {}
  7279. ResultValueBase( ResultValueBase const &other ) : ResultBase( other ) {
  7280. if( m_type == ResultBase::Ok )
  7281. new( &m_value ) T( other.m_value );
  7282. }
  7283. ResultValueBase( Type, T const &value ) : ResultBase( Ok ) {
  7284. new( &m_value ) T( value );
  7285. }
  7286. auto operator=( ResultValueBase const &other ) -> ResultValueBase & {
  7287. if( m_type == ResultBase::Ok )
  7288. m_value.~T();
  7289. ResultBase::operator=(other);
  7290. if( m_type == ResultBase::Ok )
  7291. new( &m_value ) T( other.m_value );
  7292. return *this;
  7293. }
  7294. ~ResultValueBase() override {
  7295. if( m_type == Ok )
  7296. m_value.~T();
  7297. }
  7298. union {
  7299. T m_value;
  7300. };
  7301. };
  7302. template<>
  7303. class ResultValueBase<void> : public ResultBase {
  7304. protected:
  7305. using ResultBase::ResultBase;
  7306. };
  7307. template<typename T = void>
  7308. class BasicResult : public ResultValueBase<T> {
  7309. public:
  7310. template<typename U>
  7311. explicit BasicResult( BasicResult<U> const &other )
  7312. : ResultValueBase<T>( other.type() ),
  7313. m_errorMessage( other.errorMessage() )
  7314. {
  7315. assert( type() != ResultBase::Ok );
  7316. }
  7317. template<typename U>
  7318. static auto ok( U const &value ) -> BasicResult { return { ResultBase::Ok, value }; }
  7319. static auto ok() -> BasicResult { return { ResultBase::Ok }; }
  7320. static auto logicError( std::string const &message ) -> BasicResult { return { ResultBase::LogicError, message }; }
  7321. static auto runtimeError( std::string const &message ) -> BasicResult { return { ResultBase::RuntimeError, message }; }
  7322. explicit operator bool() const { return m_type == ResultBase::Ok; }
  7323. auto type() const -> ResultBase::Type { return m_type; }
  7324. auto errorMessage() const -> std::string { return m_errorMessage; }
  7325. protected:
  7326. void enforceOk() const override {
  7327. // Errors shouldn't reach this point, but if they do
  7328. // the actual error message will be in m_errorMessage
  7329. assert( m_type != ResultBase::LogicError );
  7330. assert( m_type != ResultBase::RuntimeError );
  7331. if( m_type != ResultBase::Ok )
  7332. std::abort();
  7333. }
  7334. std::string m_errorMessage; // Only populated if resultType is an error
  7335. BasicResult( ResultBase::Type type, std::string const &message )
  7336. : ResultValueBase<T>(type),
  7337. m_errorMessage(message)
  7338. {
  7339. assert( m_type != ResultBase::Ok );
  7340. }
  7341. using ResultValueBase<T>::ResultValueBase;
  7342. using ResultBase::m_type;
  7343. };
  7344. enum class ParseResultType {
  7345. Matched, NoMatch, ShortCircuitAll, ShortCircuitSame
  7346. };
  7347. class ParseState {
  7348. public:
  7349. ParseState( ParseResultType type, TokenStream const &remainingTokens )
  7350. : m_type(type),
  7351. m_remainingTokens( remainingTokens )
  7352. {}
  7353. auto type() const -> ParseResultType { return m_type; }
  7354. auto remainingTokens() const -> TokenStream { return m_remainingTokens; }
  7355. private:
  7356. ParseResultType m_type;
  7357. TokenStream m_remainingTokens;
  7358. };
  7359. using Result = BasicResult<void>;
  7360. using ParserResult = BasicResult<ParseResultType>;
  7361. using InternalParseResult = BasicResult<ParseState>;
  7362. struct HelpColumns {
  7363. std::string left;
  7364. std::string right;
  7365. };
  7366. template<typename T>
  7367. inline auto convertInto( std::string const &source, T& target ) -> ParserResult {
  7368. std::stringstream ss;
  7369. ss << source;
  7370. ss >> target;
  7371. if( ss.fail() )
  7372. return ParserResult::runtimeError( "Unable to convert '" + source + "' to destination type" );
  7373. else
  7374. return ParserResult::ok( ParseResultType::Matched );
  7375. }
  7376. inline auto convertInto( std::string const &source, std::string& target ) -> ParserResult {
  7377. target = source;
  7378. return ParserResult::ok( ParseResultType::Matched );
  7379. }
  7380. inline auto convertInto( std::string const &source, bool &target ) -> ParserResult {
  7381. std::string srcLC = source;
  7382. std::transform( srcLC.begin(), srcLC.end(), srcLC.begin(), []( unsigned char c ) { return static_cast<char>( std::tolower(c) ); } );
  7383. if (srcLC == "y" || srcLC == "1" || srcLC == "true" || srcLC == "yes" || srcLC == "on")
  7384. target = true;
  7385. else if (srcLC == "n" || srcLC == "0" || srcLC == "false" || srcLC == "no" || srcLC == "off")
  7386. target = false;
  7387. else
  7388. return ParserResult::runtimeError( "Expected a boolean value but did not recognise: '" + source + "'" );
  7389. return ParserResult::ok( ParseResultType::Matched );
  7390. }
  7391. #ifdef CLARA_CONFIG_OPTIONAL_TYPE
  7392. template<typename T>
  7393. inline auto convertInto( std::string const &source, CLARA_CONFIG_OPTIONAL_TYPE<T>& target ) -> ParserResult {
  7394. T temp;
  7395. auto result = convertInto( source, temp );
  7396. if( result )
  7397. target = std::move(temp);
  7398. return result;
  7399. }
  7400. #endif // CLARA_CONFIG_OPTIONAL_TYPE
  7401. struct NonCopyable {
  7402. NonCopyable() = default;
  7403. NonCopyable( NonCopyable const & ) = delete;
  7404. NonCopyable( NonCopyable && ) = delete;
  7405. NonCopyable &operator=( NonCopyable const & ) = delete;
  7406. NonCopyable &operator=( NonCopyable && ) = delete;
  7407. };
  7408. struct BoundRef : NonCopyable {
  7409. virtual ~BoundRef() = default;
  7410. virtual auto isContainer() const -> bool { return false; }
  7411. virtual auto isFlag() const -> bool { return false; }
  7412. };
  7413. struct BoundValueRefBase : BoundRef {
  7414. virtual auto setValue( std::string const &arg ) -> ParserResult = 0;
  7415. };
  7416. struct BoundFlagRefBase : BoundRef {
  7417. virtual auto setFlag( bool flag ) -> ParserResult = 0;
  7418. virtual auto isFlag() const -> bool { return true; }
  7419. };
  7420. template<typename T>
  7421. struct BoundValueRef : BoundValueRefBase {
  7422. T &m_ref;
  7423. explicit BoundValueRef( T &ref ) : m_ref( ref ) {}
  7424. auto setValue( std::string const &arg ) -> ParserResult override {
  7425. return convertInto( arg, m_ref );
  7426. }
  7427. };
  7428. template<typename T>
  7429. struct BoundValueRef<std::vector<T>> : BoundValueRefBase {
  7430. std::vector<T> &m_ref;
  7431. explicit BoundValueRef( std::vector<T> &ref ) : m_ref( ref ) {}
  7432. auto isContainer() const -> bool override { return true; }
  7433. auto setValue( std::string const &arg ) -> ParserResult override {
  7434. T temp;
  7435. auto result = convertInto( arg, temp );
  7436. if( result )
  7437. m_ref.push_back( temp );
  7438. return result;
  7439. }
  7440. };
  7441. struct BoundFlagRef : BoundFlagRefBase {
  7442. bool &m_ref;
  7443. explicit BoundFlagRef( bool &ref ) : m_ref( ref ) {}
  7444. auto setFlag( bool flag ) -> ParserResult override {
  7445. m_ref = flag;
  7446. return ParserResult::ok( ParseResultType::Matched );
  7447. }
  7448. };
  7449. template<typename ReturnType>
  7450. struct LambdaInvoker {
  7451. static_assert( std::is_same<ReturnType, ParserResult>::value, "Lambda must return void or clara::ParserResult" );
  7452. template<typename L, typename ArgType>
  7453. static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
  7454. return lambda( arg );
  7455. }
  7456. };
  7457. template<>
  7458. struct LambdaInvoker<void> {
  7459. template<typename L, typename ArgType>
  7460. static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
  7461. lambda( arg );
  7462. return ParserResult::ok( ParseResultType::Matched );
  7463. }
  7464. };
  7465. template<typename ArgType, typename L>
  7466. inline auto invokeLambda( L const &lambda, std::string const &arg ) -> ParserResult {
  7467. ArgType temp{};
  7468. auto result = convertInto( arg, temp );
  7469. return !result
  7470. ? result
  7471. : LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( lambda, temp );
  7472. }
  7473. template<typename L>
  7474. struct BoundLambda : BoundValueRefBase {
  7475. L m_lambda;
  7476. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  7477. explicit BoundLambda( L const &lambda ) : m_lambda( lambda ) {}
  7478. auto setValue( std::string const &arg ) -> ParserResult override {
  7479. return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>( m_lambda, arg );
  7480. }
  7481. };
  7482. template<typename L>
  7483. struct BoundFlagLambda : BoundFlagRefBase {
  7484. L m_lambda;
  7485. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  7486. static_assert( std::is_same<typename UnaryLambdaTraits<L>::ArgType, bool>::value, "flags must be boolean" );
  7487. explicit BoundFlagLambda( L const &lambda ) : m_lambda( lambda ) {}
  7488. auto setFlag( bool flag ) -> ParserResult override {
  7489. return LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( m_lambda, flag );
  7490. }
  7491. };
  7492. enum class Optionality { Optional, Required };
  7493. struct Parser;
  7494. class ParserBase {
  7495. public:
  7496. virtual ~ParserBase() = default;
  7497. virtual auto validate() const -> Result { return Result::ok(); }
  7498. virtual auto parse( std::string const& exeName, TokenStream const &tokens) const -> InternalParseResult = 0;
  7499. virtual auto cardinality() const -> size_t { return 1; }
  7500. auto parse( Args const &args ) const -> InternalParseResult {
  7501. return parse( args.exeName(), TokenStream( args ) );
  7502. }
  7503. };
  7504. template<typename DerivedT>
  7505. class ComposableParserImpl : public ParserBase {
  7506. public:
  7507. template<typename T>
  7508. auto operator|( T const &other ) const -> Parser;
  7509. template<typename T>
  7510. auto operator+( T const &other ) const -> Parser;
  7511. };
  7512. // Common code and state for Args and Opts
  7513. template<typename DerivedT>
  7514. class ParserRefImpl : public ComposableParserImpl<DerivedT> {
  7515. protected:
  7516. Optionality m_optionality = Optionality::Optional;
  7517. std::shared_ptr<BoundRef> m_ref;
  7518. std::string m_hint;
  7519. std::string m_description;
  7520. explicit ParserRefImpl( std::shared_ptr<BoundRef> const &ref ) : m_ref( ref ) {}
  7521. public:
  7522. template<typename T>
  7523. ParserRefImpl( T &ref, std::string const &hint )
  7524. : m_ref( std::make_shared<BoundValueRef<T>>( ref ) ),
  7525. m_hint( hint )
  7526. {}
  7527. template<typename LambdaT>
  7528. ParserRefImpl( LambdaT const &ref, std::string const &hint )
  7529. : m_ref( std::make_shared<BoundLambda<LambdaT>>( ref ) ),
  7530. m_hint(hint)
  7531. {}
  7532. auto operator()( std::string const &description ) -> DerivedT & {
  7533. m_description = description;
  7534. return static_cast<DerivedT &>( *this );
  7535. }
  7536. auto optional() -> DerivedT & {
  7537. m_optionality = Optionality::Optional;
  7538. return static_cast<DerivedT &>( *this );
  7539. };
  7540. auto required() -> DerivedT & {
  7541. m_optionality = Optionality::Required;
  7542. return static_cast<DerivedT &>( *this );
  7543. };
  7544. auto isOptional() const -> bool {
  7545. return m_optionality == Optionality::Optional;
  7546. }
  7547. auto cardinality() const -> size_t override {
  7548. if( m_ref->isContainer() )
  7549. return 0;
  7550. else
  7551. return 1;
  7552. }
  7553. auto hint() const -> std::string { return m_hint; }
  7554. };
  7555. class ExeName : public ComposableParserImpl<ExeName> {
  7556. std::shared_ptr<std::string> m_name;
  7557. std::shared_ptr<BoundValueRefBase> m_ref;
  7558. template<typename LambdaT>
  7559. static auto makeRef(LambdaT const &lambda) -> std::shared_ptr<BoundValueRefBase> {
  7560. return std::make_shared<BoundLambda<LambdaT>>( lambda) ;
  7561. }
  7562. public:
  7563. ExeName() : m_name( std::make_shared<std::string>( "<executable>" ) ) {}
  7564. explicit ExeName( std::string &ref ) : ExeName() {
  7565. m_ref = std::make_shared<BoundValueRef<std::string>>( ref );
  7566. }
  7567. template<typename LambdaT>
  7568. explicit ExeName( LambdaT const& lambda ) : ExeName() {
  7569. m_ref = std::make_shared<BoundLambda<LambdaT>>( lambda );
  7570. }
  7571. // The exe name is not parsed out of the normal tokens, but is handled specially
  7572. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  7573. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
  7574. }
  7575. auto name() const -> std::string { return *m_name; }
  7576. auto set( std::string const& newName ) -> ParserResult {
  7577. auto lastSlash = newName.find_last_of( "\\/" );
  7578. auto filename = ( lastSlash == std::string::npos )
  7579. ? newName
  7580. : newName.substr( lastSlash+1 );
  7581. *m_name = filename;
  7582. if( m_ref )
  7583. return m_ref->setValue( filename );
  7584. else
  7585. return ParserResult::ok( ParseResultType::Matched );
  7586. }
  7587. };
  7588. class Arg : public ParserRefImpl<Arg> {
  7589. public:
  7590. using ParserRefImpl::ParserRefImpl;
  7591. auto parse( std::string const &, TokenStream const &tokens ) const -> InternalParseResult override {
  7592. auto validationResult = validate();
  7593. if( !validationResult )
  7594. return InternalParseResult( validationResult );
  7595. auto remainingTokens = tokens;
  7596. auto const &token = *remainingTokens;
  7597. if( token.type != TokenType::Argument )
  7598. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
  7599. assert( !m_ref->isFlag() );
  7600. auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
  7601. auto result = valueRef->setValue( remainingTokens->token );
  7602. if( !result )
  7603. return InternalParseResult( result );
  7604. else
  7605. return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
  7606. }
  7607. };
  7608. inline auto normaliseOpt( std::string const &optName ) -> std::string {
  7609. #ifdef CATCH_PLATFORM_WINDOWS
  7610. if( optName[0] == '/' )
  7611. return "-" + optName.substr( 1 );
  7612. else
  7613. #endif
  7614. return optName;
  7615. }
  7616. class Opt : public ParserRefImpl<Opt> {
  7617. protected:
  7618. std::vector<std::string> m_optNames;
  7619. public:
  7620. template<typename LambdaT>
  7621. explicit Opt( LambdaT const &ref ) : ParserRefImpl( std::make_shared<BoundFlagLambda<LambdaT>>( ref ) ) {}
  7622. explicit Opt( bool &ref ) : ParserRefImpl( std::make_shared<BoundFlagRef>( ref ) ) {}
  7623. template<typename LambdaT>
  7624. Opt( LambdaT const &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  7625. template<typename T>
  7626. Opt( T &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  7627. auto operator[]( std::string const &optName ) -> Opt & {
  7628. m_optNames.push_back( optName );
  7629. return *this;
  7630. }
  7631. auto getHelpColumns() const -> std::vector<HelpColumns> {
  7632. std::ostringstream oss;
  7633. bool first = true;
  7634. for( auto const &opt : m_optNames ) {
  7635. if (first)
  7636. first = false;
  7637. else
  7638. oss << ", ";
  7639. oss << opt;
  7640. }
  7641. if( !m_hint.empty() )
  7642. oss << " <" << m_hint << ">";
  7643. return { { oss.str(), m_description } };
  7644. }
  7645. auto isMatch( std::string const &optToken ) const -> bool {
  7646. auto normalisedToken = normaliseOpt( optToken );
  7647. for( auto const &name : m_optNames ) {
  7648. if( normaliseOpt( name ) == normalisedToken )
  7649. return true;
  7650. }
  7651. return false;
  7652. }
  7653. using ParserBase::parse;
  7654. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  7655. auto validationResult = validate();
  7656. if( !validationResult )
  7657. return InternalParseResult( validationResult );
  7658. auto remainingTokens = tokens;
  7659. if( remainingTokens && remainingTokens->type == TokenType::Option ) {
  7660. auto const &token = *remainingTokens;
  7661. if( isMatch(token.token ) ) {
  7662. if( m_ref->isFlag() ) {
  7663. auto flagRef = static_cast<detail::BoundFlagRefBase*>( m_ref.get() );
  7664. auto result = flagRef->setFlag( true );
  7665. if( !result )
  7666. return InternalParseResult( result );
  7667. if( result.value() == ParseResultType::ShortCircuitAll )
  7668. return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
  7669. } else {
  7670. auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
  7671. ++remainingTokens;
  7672. if( !remainingTokens )
  7673. return InternalParseResult::runtimeError( "Expected argument following " + token.token );
  7674. auto const &argToken = *remainingTokens;
  7675. if( argToken.type != TokenType::Argument )
  7676. return InternalParseResult::runtimeError( "Expected argument following " + token.token );
  7677. auto result = valueRef->setValue( argToken.token );
  7678. if( !result )
  7679. return InternalParseResult( result );
  7680. if( result.value() == ParseResultType::ShortCircuitAll )
  7681. return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
  7682. }
  7683. return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
  7684. }
  7685. }
  7686. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
  7687. }
  7688. auto validate() const -> Result override {
  7689. if( m_optNames.empty() )
  7690. return Result::logicError( "No options supplied to Opt" );
  7691. for( auto const &name : m_optNames ) {
  7692. if( name.empty() )
  7693. return Result::logicError( "Option name cannot be empty" );
  7694. #ifdef CATCH_PLATFORM_WINDOWS
  7695. if( name[0] != '-' && name[0] != '/' )
  7696. return Result::logicError( "Option name must begin with '-' or '/'" );
  7697. #else
  7698. if( name[0] != '-' )
  7699. return Result::logicError( "Option name must begin with '-'" );
  7700. #endif
  7701. }
  7702. return ParserRefImpl::validate();
  7703. }
  7704. };
  7705. struct Help : Opt {
  7706. Help( bool &showHelpFlag )
  7707. : Opt([&]( bool flag ) {
  7708. showHelpFlag = flag;
  7709. return ParserResult::ok( ParseResultType::ShortCircuitAll );
  7710. })
  7711. {
  7712. static_cast<Opt &>( *this )
  7713. ("display usage information")
  7714. ["-?"]["-h"]["--help"]
  7715. .optional();
  7716. }
  7717. };
  7718. struct Parser : ParserBase {
  7719. mutable ExeName m_exeName;
  7720. std::vector<Opt> m_options;
  7721. std::vector<Arg> m_args;
  7722. auto operator|=( ExeName const &exeName ) -> Parser & {
  7723. m_exeName = exeName;
  7724. return *this;
  7725. }
  7726. auto operator|=( Arg const &arg ) -> Parser & {
  7727. m_args.push_back(arg);
  7728. return *this;
  7729. }
  7730. auto operator|=( Opt const &opt ) -> Parser & {
  7731. m_options.push_back(opt);
  7732. return *this;
  7733. }
  7734. auto operator|=( Parser const &other ) -> Parser & {
  7735. m_options.insert(m_options.end(), other.m_options.begin(), other.m_options.end());
  7736. m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end());
  7737. return *this;
  7738. }
  7739. template<typename T>
  7740. auto operator|( T const &other ) const -> Parser {
  7741. return Parser( *this ) |= other;
  7742. }
  7743. // Forward deprecated interface with '+' instead of '|'
  7744. template<typename T>
  7745. auto operator+=( T const &other ) -> Parser & { return operator|=( other ); }
  7746. template<typename T>
  7747. auto operator+( T const &other ) const -> Parser { return operator|( other ); }
  7748. auto getHelpColumns() const -> std::vector<HelpColumns> {
  7749. std::vector<HelpColumns> cols;
  7750. for (auto const &o : m_options) {
  7751. auto childCols = o.getHelpColumns();
  7752. cols.insert( cols.end(), childCols.begin(), childCols.end() );
  7753. }
  7754. return cols;
  7755. }
  7756. void writeToStream( std::ostream &os ) const {
  7757. if (!m_exeName.name().empty()) {
  7758. os << "usage:\n" << " " << m_exeName.name() << " ";
  7759. bool required = true, first = true;
  7760. for( auto const &arg : m_args ) {
  7761. if (first)
  7762. first = false;
  7763. else
  7764. os << " ";
  7765. if( arg.isOptional() && required ) {
  7766. os << "[";
  7767. required = false;
  7768. }
  7769. os << "<" << arg.hint() << ">";
  7770. if( arg.cardinality() == 0 )
  7771. os << " ... ";
  7772. }
  7773. if( !required )
  7774. os << "]";
  7775. if( !m_options.empty() )
  7776. os << " options";
  7777. os << "\n\nwhere options are:" << std::endl;
  7778. }
  7779. auto rows = getHelpColumns();
  7780. size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH;
  7781. size_t optWidth = 0;
  7782. for( auto const &cols : rows )
  7783. optWidth = (std::max)(optWidth, cols.left.size() + 2);
  7784. optWidth = (std::min)(optWidth, consoleWidth/2);
  7785. for( auto const &cols : rows ) {
  7786. auto row =
  7787. TextFlow::Column( cols.left ).width( optWidth ).indent( 2 ) +
  7788. TextFlow::Spacer(4) +
  7789. TextFlow::Column( cols.right ).width( consoleWidth - 7 - optWidth );
  7790. os << row << std::endl;
  7791. }
  7792. }
  7793. friend auto operator<<( std::ostream &os, Parser const &parser ) -> std::ostream& {
  7794. parser.writeToStream( os );
  7795. return os;
  7796. }
  7797. auto validate() const -> Result override {
  7798. for( auto const &opt : m_options ) {
  7799. auto result = opt.validate();
  7800. if( !result )
  7801. return result;
  7802. }
  7803. for( auto const &arg : m_args ) {
  7804. auto result = arg.validate();
  7805. if( !result )
  7806. return result;
  7807. }
  7808. return Result::ok();
  7809. }
  7810. using ParserBase::parse;
  7811. auto parse( std::string const& exeName, TokenStream const &tokens ) const -> InternalParseResult override {
  7812. struct ParserInfo {
  7813. ParserBase const* parser = nullptr;
  7814. size_t count = 0;
  7815. };
  7816. const size_t totalParsers = m_options.size() + m_args.size();
  7817. assert( totalParsers < 512 );
  7818. // ParserInfo parseInfos[totalParsers]; // <-- this is what we really want to do
  7819. ParserInfo parseInfos[512];
  7820. {
  7821. size_t i = 0;
  7822. for (auto const &opt : m_options) parseInfos[i++].parser = &opt;
  7823. for (auto const &arg : m_args) parseInfos[i++].parser = &arg;
  7824. }
  7825. m_exeName.set( exeName );
  7826. auto result = InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
  7827. while( result.value().remainingTokens() ) {
  7828. bool tokenParsed = false;
  7829. for( size_t i = 0; i < totalParsers; ++i ) {
  7830. auto& parseInfo = parseInfos[i];
  7831. if( parseInfo.parser->cardinality() == 0 || parseInfo.count < parseInfo.parser->cardinality() ) {
  7832. result = parseInfo.parser->parse(exeName, result.value().remainingTokens());
  7833. if (!result)
  7834. return result;
  7835. if (result.value().type() != ParseResultType::NoMatch) {
  7836. tokenParsed = true;
  7837. ++parseInfo.count;
  7838. break;
  7839. }
  7840. }
  7841. }
  7842. if( result.value().type() == ParseResultType::ShortCircuitAll )
  7843. return result;
  7844. if( !tokenParsed )
  7845. return InternalParseResult::runtimeError( "Unrecognised token: " + result.value().remainingTokens()->token );
  7846. }
  7847. // !TBD Check missing required options
  7848. return result;
  7849. }
  7850. };
  7851. template<typename DerivedT>
  7852. template<typename T>
  7853. auto ComposableParserImpl<DerivedT>::operator|( T const &other ) const -> Parser {
  7854. return Parser() | static_cast<DerivedT const &>( *this ) | other;
  7855. }
  7856. } // namespace detail
  7857. // A Combined parser
  7858. using detail::Parser;
  7859. // A parser for options
  7860. using detail::Opt;
  7861. // A parser for arguments
  7862. using detail::Arg;
  7863. // Wrapper for argc, argv from main()
  7864. using detail::Args;
  7865. // Specifies the name of the executable
  7866. using detail::ExeName;
  7867. // Convenience wrapper for option parser that specifies the help option
  7868. using detail::Help;
  7869. // enum of result types from a parse
  7870. using detail::ParseResultType;
  7871. // Result type for parser operation
  7872. using detail::ParserResult;
  7873. }} // namespace Catch::clara
  7874. // end clara.hpp
  7875. #ifdef __clang__
  7876. #pragma clang diagnostic pop
  7877. #endif
  7878. // Restore Clara's value for console width, if present
  7879. #ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  7880. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  7881. #undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  7882. #endif
  7883. // end catch_clara.h
  7884. namespace Catch {
  7885. clara::Parser makeCommandLineParser( ConfigData& config );
  7886. } // end namespace Catch
  7887. // end catch_commandline.h
  7888. #include <fstream>
  7889. #include <ctime>
  7890. namespace Catch {
  7891. clara::Parser makeCommandLineParser( ConfigData& config ) {
  7892. using namespace clara;
  7893. auto const setWarning = [&]( std::string const& warning ) {
  7894. auto warningSet = [&]() {
  7895. if( warning == "NoAssertions" )
  7896. return WarnAbout::NoAssertions;
  7897. if ( warning == "NoTests" )
  7898. return WarnAbout::NoTests;
  7899. return WarnAbout::Nothing;
  7900. }();
  7901. if (warningSet == WarnAbout::Nothing)
  7902. return ParserResult::runtimeError( "Unrecognised warning: '" + warning + "'" );
  7903. config.warnings = static_cast<WarnAbout::What>( config.warnings | warningSet );
  7904. return ParserResult::ok( ParseResultType::Matched );
  7905. };
  7906. auto const loadTestNamesFromFile = [&]( std::string const& filename ) {
  7907. std::ifstream f( filename.c_str() );
  7908. if( !f.is_open() )
  7909. return ParserResult::runtimeError( "Unable to load input file: '" + filename + "'" );
  7910. std::string line;
  7911. while( std::getline( f, line ) ) {
  7912. line = trim(line);
  7913. if( !line.empty() && !startsWith( line, '#' ) ) {
  7914. if( !startsWith( line, '"' ) )
  7915. line = '"' + line + '"';
  7916. config.testsOrTags.push_back( line );
  7917. config.testsOrTags.emplace_back( "," );
  7918. }
  7919. }
  7920. //Remove comma in the end
  7921. if(!config.testsOrTags.empty())
  7922. config.testsOrTags.erase( config.testsOrTags.end()-1 );
  7923. return ParserResult::ok( ParseResultType::Matched );
  7924. };
  7925. auto const setTestOrder = [&]( std::string const& order ) {
  7926. if( startsWith( "declared", order ) )
  7927. config.runOrder = RunTests::InDeclarationOrder;
  7928. else if( startsWith( "lexical", order ) )
  7929. config.runOrder = RunTests::InLexicographicalOrder;
  7930. else if( startsWith( "random", order ) )
  7931. config.runOrder = RunTests::InRandomOrder;
  7932. else
  7933. return clara::ParserResult::runtimeError( "Unrecognised ordering: '" + order + "'" );
  7934. return ParserResult::ok( ParseResultType::Matched );
  7935. };
  7936. auto const setRngSeed = [&]( std::string const& seed ) {
  7937. if( seed != "time" )
  7938. return clara::detail::convertInto( seed, config.rngSeed );
  7939. config.rngSeed = static_cast<unsigned int>( std::time(nullptr) );
  7940. return ParserResult::ok( ParseResultType::Matched );
  7941. };
  7942. auto const setColourUsage = [&]( std::string const& useColour ) {
  7943. auto mode = toLower( useColour );
  7944. if( mode == "yes" )
  7945. config.useColour = UseColour::Yes;
  7946. else if( mode == "no" )
  7947. config.useColour = UseColour::No;
  7948. else if( mode == "auto" )
  7949. config.useColour = UseColour::Auto;
  7950. else
  7951. return ParserResult::runtimeError( "colour mode must be one of: auto, yes or no. '" + useColour + "' not recognised" );
  7952. return ParserResult::ok( ParseResultType::Matched );
  7953. };
  7954. auto const setWaitForKeypress = [&]( std::string const& keypress ) {
  7955. auto keypressLc = toLower( keypress );
  7956. if (keypressLc == "never")
  7957. config.waitForKeypress = WaitForKeypress::Never;
  7958. else if( keypressLc == "start" )
  7959. config.waitForKeypress = WaitForKeypress::BeforeStart;
  7960. else if( keypressLc == "exit" )
  7961. config.waitForKeypress = WaitForKeypress::BeforeExit;
  7962. else if( keypressLc == "both" )
  7963. config.waitForKeypress = WaitForKeypress::BeforeStartAndExit;
  7964. else
  7965. return ParserResult::runtimeError( "keypress argument must be one of: never, start, exit or both. '" + keypress + "' not recognised" );
  7966. return ParserResult::ok( ParseResultType::Matched );
  7967. };
  7968. auto const setVerbosity = [&]( std::string const& verbosity ) {
  7969. auto lcVerbosity = toLower( verbosity );
  7970. if( lcVerbosity == "quiet" )
  7971. config.verbosity = Verbosity::Quiet;
  7972. else if( lcVerbosity == "normal" )
  7973. config.verbosity = Verbosity::Normal;
  7974. else if( lcVerbosity == "high" )
  7975. config.verbosity = Verbosity::High;
  7976. else
  7977. return ParserResult::runtimeError( "Unrecognised verbosity, '" + verbosity + "'" );
  7978. return ParserResult::ok( ParseResultType::Matched );
  7979. };
  7980. auto const setReporter = [&]( std::string const& reporter ) {
  7981. IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
  7982. auto lcReporter = toLower( reporter );
  7983. auto result = factories.find( lcReporter );
  7984. if( factories.end() != result )
  7985. config.reporterName = lcReporter;
  7986. else
  7987. return ParserResult::runtimeError( "Unrecognized reporter, '" + reporter + "'. Check available with --list-reporters" );
  7988. return ParserResult::ok( ParseResultType::Matched );
  7989. };
  7990. auto cli
  7991. = ExeName( config.processName )
  7992. | Help( config.showHelp )
  7993. | Opt( config.listTests )
  7994. ["-l"]["--list-tests"]
  7995. ( "list all/matching test cases" )
  7996. | Opt( config.listTags )
  7997. ["-t"]["--list-tags"]
  7998. ( "list all/matching tags" )
  7999. | Opt( config.showSuccessfulTests )
  8000. ["-s"]["--success"]
  8001. ( "include successful tests in output" )
  8002. | Opt( config.shouldDebugBreak )
  8003. ["-b"]["--break"]
  8004. ( "break into debugger on failure" )
  8005. | Opt( config.noThrow )
  8006. ["-e"]["--nothrow"]
  8007. ( "skip exception tests" )
  8008. | Opt( config.showInvisibles )
  8009. ["-i"]["--invisibles"]
  8010. ( "show invisibles (tabs, newlines)" )
  8011. | Opt( config.outputFilename, "filename" )
  8012. ["-o"]["--out"]
  8013. ( "output filename" )
  8014. | Opt( setReporter, "name" )
  8015. ["-r"]["--reporter"]
  8016. ( "reporter to use (defaults to console)" )
  8017. | Opt( config.name, "name" )
  8018. ["-n"]["--name"]
  8019. ( "suite name" )
  8020. | Opt( [&]( bool ){ config.abortAfter = 1; } )
  8021. ["-a"]["--abort"]
  8022. ( "abort at first failure" )
  8023. | Opt( [&]( int x ){ config.abortAfter = x; }, "no. failures" )
  8024. ["-x"]["--abortx"]
  8025. ( "abort after x failures" )
  8026. | Opt( setWarning, "warning name" )
  8027. ["-w"]["--warn"]
  8028. ( "enable warnings" )
  8029. | Opt( [&]( bool flag ) { config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never; }, "yes|no" )
  8030. ["-d"]["--durations"]
  8031. ( "show test durations" )
  8032. | Opt( config.minDuration, "seconds" )
  8033. ["-D"]["--min-duration"]
  8034. ( "show test durations for tests taking at least the given number of seconds" )
  8035. | Opt( loadTestNamesFromFile, "filename" )
  8036. ["-f"]["--input-file"]
  8037. ( "load test names to run from a file" )
  8038. | Opt( config.filenamesAsTags )
  8039. ["-#"]["--filenames-as-tags"]
  8040. ( "adds a tag for the filename" )
  8041. | Opt( config.sectionsToRun, "section name" )
  8042. ["-c"]["--section"]
  8043. ( "specify section to run" )
  8044. | Opt( setVerbosity, "quiet|normal|high" )
  8045. ["-v"]["--verbosity"]
  8046. ( "set output verbosity" )
  8047. | Opt( config.listTestNamesOnly )
  8048. ["--list-test-names-only"]
  8049. ( "list all/matching test cases names only" )
  8050. | Opt( config.listReporters )
  8051. ["--list-reporters"]
  8052. ( "list all reporters" )
  8053. | Opt( setTestOrder, "decl|lex|rand" )
  8054. ["--order"]
  8055. ( "test case order (defaults to decl)" )
  8056. | Opt( setRngSeed, "'time'|number" )
  8057. ["--rng-seed"]
  8058. ( "set a specific seed for random numbers" )
  8059. | Opt( setColourUsage, "yes|no" )
  8060. ["--use-colour"]
  8061. ( "should output be colourised" )
  8062. | Opt( config.libIdentify )
  8063. ["--libidentify"]
  8064. ( "report name and version according to libidentify standard" )
  8065. | Opt( setWaitForKeypress, "never|start|exit|both" )
  8066. ["--wait-for-keypress"]
  8067. ( "waits for a keypress before exiting" )
  8068. | Opt( config.benchmarkSamples, "samples" )
  8069. ["--benchmark-samples"]
  8070. ( "number of samples to collect (default: 100)" )
  8071. | Opt( config.benchmarkResamples, "resamples" )
  8072. ["--benchmark-resamples"]
  8073. ( "number of resamples for the bootstrap (default: 100000)" )
  8074. | Opt( config.benchmarkConfidenceInterval, "confidence interval" )
  8075. ["--benchmark-confidence-interval"]
  8076. ( "confidence interval for the bootstrap (between 0 and 1, default: 0.95)" )
  8077. | Opt( config.benchmarkNoAnalysis )
  8078. ["--benchmark-no-analysis"]
  8079. ( "perform only measurements; do not perform any analysis" )
  8080. | Opt( config.benchmarkWarmupTime, "benchmarkWarmupTime" )
  8081. ["--benchmark-warmup-time"]
  8082. ( "amount of time in milliseconds spent on warming up each test (default: 100)" )
  8083. | Arg( config.testsOrTags, "test name|pattern|tags" )
  8084. ( "which test or tests to use" );
  8085. return cli;
  8086. }
  8087. } // end namespace Catch
  8088. // end catch_commandline.cpp
  8089. // start catch_common.cpp
  8090. #include <cstring>
  8091. #include <ostream>
  8092. namespace Catch {
  8093. bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const noexcept {
  8094. return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0);
  8095. }
  8096. bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const noexcept {
  8097. // We can assume that the same file will usually have the same pointer.
  8098. // Thus, if the pointers are the same, there is no point in calling the strcmp
  8099. return line < other.line || ( line == other.line && file != other.file && (std::strcmp(file, other.file) < 0));
  8100. }
  8101. std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) {
  8102. #ifndef __GNUG__
  8103. os << info.file << '(' << info.line << ')';
  8104. #else
  8105. os << info.file << ':' << info.line;
  8106. #endif
  8107. return os;
  8108. }
  8109. std::string StreamEndStop::operator+() const {
  8110. return std::string();
  8111. }
  8112. NonCopyable::NonCopyable() = default;
  8113. NonCopyable::~NonCopyable() = default;
  8114. }
  8115. // end catch_common.cpp
  8116. // start catch_config.cpp
  8117. namespace Catch {
  8118. Config::Config( ConfigData const& data )
  8119. : m_data( data ),
  8120. m_stream( openStream() )
  8121. {
  8122. // We need to trim filter specs to avoid trouble with superfluous
  8123. // whitespace (esp. important for bdd macros, as those are manually
  8124. // aligned with whitespace).
  8125. for (auto& elem : m_data.testsOrTags) {
  8126. elem = trim(elem);
  8127. }
  8128. for (auto& elem : m_data.sectionsToRun) {
  8129. elem = trim(elem);
  8130. }
  8131. TestSpecParser parser(ITagAliasRegistry::get());
  8132. if (!m_data.testsOrTags.empty()) {
  8133. m_hasTestFilters = true;
  8134. for (auto const& testOrTags : m_data.testsOrTags) {
  8135. parser.parse(testOrTags);
  8136. }
  8137. }
  8138. m_testSpec = parser.testSpec();
  8139. }
  8140. std::string const& Config::getFilename() const {
  8141. return m_data.outputFilename ;
  8142. }
  8143. bool Config::listTests() const { return m_data.listTests; }
  8144. bool Config::listTestNamesOnly() const { return m_data.listTestNamesOnly; }
  8145. bool Config::listTags() const { return m_data.listTags; }
  8146. bool Config::listReporters() const { return m_data.listReporters; }
  8147. std::string Config::getProcessName() const { return m_data.processName; }
  8148. std::string const& Config::getReporterName() const { return m_data.reporterName; }
  8149. std::vector<std::string> const& Config::getTestsOrTags() const { return m_data.testsOrTags; }
  8150. std::vector<std::string> const& Config::getSectionsToRun() const { return m_data.sectionsToRun; }
  8151. TestSpec const& Config::testSpec() const { return m_testSpec; }
  8152. bool Config::hasTestFilters() const { return m_hasTestFilters; }
  8153. bool Config::showHelp() const { return m_data.showHelp; }
  8154. // IConfig interface
  8155. bool Config::allowThrows() const { return !m_data.noThrow; }
  8156. std::ostream& Config::stream() const { return m_stream->stream(); }
  8157. std::string Config::name() const { return m_data.name.empty() ? m_data.processName : m_data.name; }
  8158. bool Config::includeSuccessfulResults() const { return m_data.showSuccessfulTests; }
  8159. bool Config::warnAboutMissingAssertions() const { return !!(m_data.warnings & WarnAbout::NoAssertions); }
  8160. bool Config::warnAboutNoTests() const { return !!(m_data.warnings & WarnAbout::NoTests); }
  8161. ShowDurations::OrNot Config::showDurations() const { return m_data.showDurations; }
  8162. double Config::minDuration() const { return m_data.minDuration; }
  8163. RunTests::InWhatOrder Config::runOrder() const { return m_data.runOrder; }
  8164. unsigned int Config::rngSeed() const { return m_data.rngSeed; }
  8165. UseColour::YesOrNo Config::useColour() const { return m_data.useColour; }
  8166. bool Config::shouldDebugBreak() const { return m_data.shouldDebugBreak; }
  8167. int Config::abortAfter() const { return m_data.abortAfter; }
  8168. bool Config::showInvisibles() const { return m_data.showInvisibles; }
  8169. Verbosity Config::verbosity() const { return m_data.verbosity; }
  8170. bool Config::benchmarkNoAnalysis() const { return m_data.benchmarkNoAnalysis; }
  8171. int Config::benchmarkSamples() const { return m_data.benchmarkSamples; }
  8172. double Config::benchmarkConfidenceInterval() const { return m_data.benchmarkConfidenceInterval; }
  8173. unsigned int Config::benchmarkResamples() const { return m_data.benchmarkResamples; }
  8174. std::chrono::milliseconds Config::benchmarkWarmupTime() const { return std::chrono::milliseconds(m_data.benchmarkWarmupTime); }
  8175. IStream const* Config::openStream() {
  8176. return Catch::makeStream(m_data.outputFilename);
  8177. }
  8178. } // end namespace Catch
  8179. // end catch_config.cpp
  8180. // start catch_console_colour.cpp
  8181. #if defined(__clang__)
  8182. # pragma clang diagnostic push
  8183. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  8184. #endif
  8185. // start catch_errno_guard.h
  8186. namespace Catch {
  8187. class ErrnoGuard {
  8188. public:
  8189. ErrnoGuard();
  8190. ~ErrnoGuard();
  8191. private:
  8192. int m_oldErrno;
  8193. };
  8194. }
  8195. // end catch_errno_guard.h
  8196. // start catch_windows_h_proxy.h
  8197. #if defined(CATCH_PLATFORM_WINDOWS)
  8198. #if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX)
  8199. # define CATCH_DEFINED_NOMINMAX
  8200. # define NOMINMAX
  8201. #endif
  8202. #if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN)
  8203. # define CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  8204. # define WIN32_LEAN_AND_MEAN
  8205. #endif
  8206. #ifdef __AFXDLL
  8207. #include <AfxWin.h>
  8208. #else
  8209. #include <windows.h>
  8210. #endif
  8211. #ifdef CATCH_DEFINED_NOMINMAX
  8212. # undef NOMINMAX
  8213. #endif
  8214. #ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  8215. # undef WIN32_LEAN_AND_MEAN
  8216. #endif
  8217. #endif // defined(CATCH_PLATFORM_WINDOWS)
  8218. // end catch_windows_h_proxy.h
  8219. #include <sstream>
  8220. namespace Catch {
  8221. namespace {
  8222. struct IColourImpl {
  8223. virtual ~IColourImpl() = default;
  8224. virtual void use( Colour::Code _colourCode ) = 0;
  8225. };
  8226. struct NoColourImpl : IColourImpl {
  8227. void use( Colour::Code ) override {}
  8228. static IColourImpl* instance() {
  8229. static NoColourImpl s_instance;
  8230. return &s_instance;
  8231. }
  8232. };
  8233. } // anon namespace
  8234. } // namespace Catch
  8235. #if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI )
  8236. # ifdef CATCH_PLATFORM_WINDOWS
  8237. # define CATCH_CONFIG_COLOUR_WINDOWS
  8238. # else
  8239. # define CATCH_CONFIG_COLOUR_ANSI
  8240. # endif
  8241. #endif
  8242. #if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) /////////////////////////////////////////
  8243. namespace Catch {
  8244. namespace {
  8245. class Win32ColourImpl : public IColourImpl {
  8246. public:
  8247. Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) )
  8248. {
  8249. CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
  8250. GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo );
  8251. originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY );
  8252. originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY );
  8253. }
  8254. void use( Colour::Code _colourCode ) override {
  8255. switch( _colourCode ) {
  8256. case Colour::None: return setTextAttribute( originalForegroundAttributes );
  8257. case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  8258. case Colour::Red: return setTextAttribute( FOREGROUND_RED );
  8259. case Colour::Green: return setTextAttribute( FOREGROUND_GREEN );
  8260. case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE );
  8261. case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN );
  8262. case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN );
  8263. case Colour::Grey: return setTextAttribute( 0 );
  8264. case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY );
  8265. case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED );
  8266. case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN );
  8267. case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  8268. case Colour::BrightYellow: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN );
  8269. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  8270. default:
  8271. CATCH_ERROR( "Unknown colour requested" );
  8272. }
  8273. }
  8274. private:
  8275. void setTextAttribute( WORD _textAttribute ) {
  8276. SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes );
  8277. }
  8278. HANDLE stdoutHandle;
  8279. WORD originalForegroundAttributes;
  8280. WORD originalBackgroundAttributes;
  8281. };
  8282. IColourImpl* platformColourInstance() {
  8283. static Win32ColourImpl s_instance;
  8284. IConfigPtr config = getCurrentContext().getConfig();
  8285. UseColour::YesOrNo colourMode = config
  8286. ? config->useColour()
  8287. : UseColour::Auto;
  8288. if( colourMode == UseColour::Auto )
  8289. colourMode = UseColour::Yes;
  8290. return colourMode == UseColour::Yes
  8291. ? &s_instance
  8292. : NoColourImpl::instance();
  8293. }
  8294. } // end anon namespace
  8295. } // end namespace Catch
  8296. #elif defined( CATCH_CONFIG_COLOUR_ANSI ) //////////////////////////////////////
  8297. #include <unistd.h>
  8298. namespace Catch {
  8299. namespace {
  8300. // use POSIX/ ANSI console terminal codes
  8301. // Thanks to Adam Strzelecki for original contribution
  8302. // (http://github.com/nanoant)
  8303. // https://github.com/philsquared/Catch/pull/131
  8304. class PosixColourImpl : public IColourImpl {
  8305. public:
  8306. void use( Colour::Code _colourCode ) override {
  8307. switch( _colourCode ) {
  8308. case Colour::None:
  8309. case Colour::White: return setColour( "[0m" );
  8310. case Colour::Red: return setColour( "[0;31m" );
  8311. case Colour::Green: return setColour( "[0;32m" );
  8312. case Colour::Blue: return setColour( "[0;34m" );
  8313. case Colour::Cyan: return setColour( "[0;36m" );
  8314. case Colour::Yellow: return setColour( "[0;33m" );
  8315. case Colour::Grey: return setColour( "[1;30m" );
  8316. case Colour::LightGrey: return setColour( "[0;37m" );
  8317. case Colour::BrightRed: return setColour( "[1;31m" );
  8318. case Colour::BrightGreen: return setColour( "[1;32m" );
  8319. case Colour::BrightWhite: return setColour( "[1;37m" );
  8320. case Colour::BrightYellow: return setColour( "[1;33m" );
  8321. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  8322. default: CATCH_INTERNAL_ERROR( "Unknown colour requested" );
  8323. }
  8324. }
  8325. static IColourImpl* instance() {
  8326. static PosixColourImpl s_instance;
  8327. return &s_instance;
  8328. }
  8329. private:
  8330. void setColour( const char* _escapeCode ) {
  8331. getCurrentContext().getConfig()->stream()
  8332. << '\033' << _escapeCode;
  8333. }
  8334. };
  8335. bool useColourOnPlatform() {
  8336. return
  8337. #if defined(CATCH_PLATFORM_MAC) || defined(CATCH_PLATFORM_IPHONE)
  8338. !isDebuggerActive() &&
  8339. #endif
  8340. #if !(defined(__DJGPP__) && defined(__STRICT_ANSI__))
  8341. isatty(STDOUT_FILENO)
  8342. #else
  8343. false
  8344. #endif
  8345. ;
  8346. }
  8347. IColourImpl* platformColourInstance() {
  8348. ErrnoGuard guard;
  8349. IConfigPtr config = getCurrentContext().getConfig();
  8350. UseColour::YesOrNo colourMode = config
  8351. ? config->useColour()
  8352. : UseColour::Auto;
  8353. if( colourMode == UseColour::Auto )
  8354. colourMode = useColourOnPlatform()
  8355. ? UseColour::Yes
  8356. : UseColour::No;
  8357. return colourMode == UseColour::Yes
  8358. ? PosixColourImpl::instance()
  8359. : NoColourImpl::instance();
  8360. }
  8361. } // end anon namespace
  8362. } // end namespace Catch
  8363. #else // not Windows or ANSI ///////////////////////////////////////////////
  8364. namespace Catch {
  8365. static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); }
  8366. } // end namespace Catch
  8367. #endif // Windows/ ANSI/ None
  8368. namespace Catch {
  8369. Colour::Colour( Code _colourCode ) { use( _colourCode ); }
  8370. Colour::Colour( Colour&& other ) noexcept {
  8371. m_moved = other.m_moved;
  8372. other.m_moved = true;
  8373. }
  8374. Colour& Colour::operator=( Colour&& other ) noexcept {
  8375. m_moved = other.m_moved;
  8376. other.m_moved = true;
  8377. return *this;
  8378. }
  8379. Colour::~Colour(){ if( !m_moved ) use( None ); }
  8380. void Colour::use( Code _colourCode ) {
  8381. static IColourImpl* impl = platformColourInstance();
  8382. // Strictly speaking, this cannot possibly happen.
  8383. // However, under some conditions it does happen (see #1626),
  8384. // and this change is small enough that we can let practicality
  8385. // triumph over purity in this case.
  8386. if (impl != nullptr) {
  8387. impl->use( _colourCode );
  8388. }
  8389. }
  8390. std::ostream& operator << ( std::ostream& os, Colour const& ) {
  8391. return os;
  8392. }
  8393. } // end namespace Catch
  8394. #if defined(__clang__)
  8395. # pragma clang diagnostic pop
  8396. #endif
  8397. // end catch_console_colour.cpp
  8398. // start catch_context.cpp
  8399. namespace Catch {
  8400. class Context : public IMutableContext, NonCopyable {
  8401. public: // IContext
  8402. IResultCapture* getResultCapture() override {
  8403. return m_resultCapture;
  8404. }
  8405. IRunner* getRunner() override {
  8406. return m_runner;
  8407. }
  8408. IConfigPtr const& getConfig() const override {
  8409. return m_config;
  8410. }
  8411. ~Context() override;
  8412. public: // IMutableContext
  8413. void setResultCapture( IResultCapture* resultCapture ) override {
  8414. m_resultCapture = resultCapture;
  8415. }
  8416. void setRunner( IRunner* runner ) override {
  8417. m_runner = runner;
  8418. }
  8419. void setConfig( IConfigPtr const& config ) override {
  8420. m_config = config;
  8421. }
  8422. friend IMutableContext& getCurrentMutableContext();
  8423. private:
  8424. IConfigPtr m_config;
  8425. IRunner* m_runner = nullptr;
  8426. IResultCapture* m_resultCapture = nullptr;
  8427. };
  8428. IMutableContext *IMutableContext::currentContext = nullptr;
  8429. void IMutableContext::createContext()
  8430. {
  8431. currentContext = new Context();
  8432. }
  8433. void cleanUpContext() {
  8434. delete IMutableContext::currentContext;
  8435. IMutableContext::currentContext = nullptr;
  8436. }
  8437. IContext::~IContext() = default;
  8438. IMutableContext::~IMutableContext() = default;
  8439. Context::~Context() = default;
  8440. SimplePcg32& rng() {
  8441. static SimplePcg32 s_rng;
  8442. return s_rng;
  8443. }
  8444. }
  8445. // end catch_context.cpp
  8446. // start catch_debug_console.cpp
  8447. // start catch_debug_console.h
  8448. #include <string>
  8449. namespace Catch {
  8450. void writeToDebugConsole( std::string const& text );
  8451. }
  8452. // end catch_debug_console.h
  8453. #if defined(CATCH_CONFIG_ANDROID_LOGWRITE)
  8454. #include <android/log.h>
  8455. namespace Catch {
  8456. void writeToDebugConsole( std::string const& text ) {
  8457. __android_log_write( ANDROID_LOG_DEBUG, "Catch", text.c_str() );
  8458. }
  8459. }
  8460. #elif defined(CATCH_PLATFORM_WINDOWS)
  8461. namespace Catch {
  8462. void writeToDebugConsole( std::string const& text ) {
  8463. ::OutputDebugStringA( text.c_str() );
  8464. }
  8465. }
  8466. #else
  8467. namespace Catch {
  8468. void writeToDebugConsole( std::string const& text ) {
  8469. // !TBD: Need a version for Mac/ XCode and other IDEs
  8470. Catch::cout() << text;
  8471. }
  8472. }
  8473. #endif // Platform
  8474. // end catch_debug_console.cpp
  8475. // start catch_debugger.cpp
  8476. #if defined(CATCH_PLATFORM_MAC) || defined(CATCH_PLATFORM_IPHONE)
  8477. # include <cassert>
  8478. # include <sys/types.h>
  8479. # include <unistd.h>
  8480. # include <cstddef>
  8481. # include <ostream>
  8482. #ifdef __apple_build_version__
  8483. // These headers will only compile with AppleClang (XCode)
  8484. // For other compilers (Clang, GCC, ... ) we need to exclude them
  8485. # include <sys/sysctl.h>
  8486. #endif
  8487. namespace Catch {
  8488. #ifdef __apple_build_version__
  8489. // The following function is taken directly from the following technical note:
  8490. // https://developer.apple.com/library/archive/qa/qa1361/_index.html
  8491. // Returns true if the current process is being debugged (either
  8492. // running under the debugger or has a debugger attached post facto).
  8493. bool isDebuggerActive(){
  8494. int mib[4];
  8495. struct kinfo_proc info;
  8496. std::size_t size;
  8497. // Initialize the flags so that, if sysctl fails for some bizarre
  8498. // reason, we get a predictable result.
  8499. info.kp_proc.p_flag = 0;
  8500. // Initialize mib, which tells sysctl the info we want, in this case
  8501. // we're looking for information about a specific process ID.
  8502. mib[0] = CTL_KERN;
  8503. mib[1] = KERN_PROC;
  8504. mib[2] = KERN_PROC_PID;
  8505. mib[3] = getpid();
  8506. // Call sysctl.
  8507. size = sizeof(info);
  8508. if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0) != 0 ) {
  8509. Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl;
  8510. return false;
  8511. }
  8512. // We're being debugged if the P_TRACED flag is set.
  8513. return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
  8514. }
  8515. #else
  8516. bool isDebuggerActive() {
  8517. // We need to find another way to determine this for non-appleclang compilers on macOS
  8518. return false;
  8519. }
  8520. #endif
  8521. } // namespace Catch
  8522. #elif defined(CATCH_PLATFORM_LINUX)
  8523. #include <fstream>
  8524. #include <string>
  8525. namespace Catch{
  8526. // The standard POSIX way of detecting a debugger is to attempt to
  8527. // ptrace() the process, but this needs to be done from a child and not
  8528. // this process itself to still allow attaching to this process later
  8529. // if wanted, so is rather heavy. Under Linux we have the PID of the
  8530. // "debugger" (which doesn't need to be gdb, of course, it could also
  8531. // be strace, for example) in /proc/$PID/status, so just get it from
  8532. // there instead.
  8533. bool isDebuggerActive(){
  8534. // Libstdc++ has a bug, where std::ifstream sets errno to 0
  8535. // This way our users can properly assert over errno values
  8536. ErrnoGuard guard;
  8537. std::ifstream in("/proc/self/status");
  8538. for( std::string line; std::getline(in, line); ) {
  8539. static const int PREFIX_LEN = 11;
  8540. if( line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0 ) {
  8541. // We're traced if the PID is not 0 and no other PID starts
  8542. // with 0 digit, so it's enough to check for just a single
  8543. // character.
  8544. return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0';
  8545. }
  8546. }
  8547. return false;
  8548. }
  8549. } // namespace Catch
  8550. #elif defined(_MSC_VER)
  8551. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  8552. namespace Catch {
  8553. bool isDebuggerActive() {
  8554. return IsDebuggerPresent() != 0;
  8555. }
  8556. }
  8557. #elif defined(__MINGW32__)
  8558. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  8559. namespace Catch {
  8560. bool isDebuggerActive() {
  8561. return IsDebuggerPresent() != 0;
  8562. }
  8563. }
  8564. #else
  8565. namespace Catch {
  8566. bool isDebuggerActive() { return false; }
  8567. }
  8568. #endif // Platform
  8569. // end catch_debugger.cpp
  8570. // start catch_decomposer.cpp
  8571. namespace Catch {
  8572. ITransientExpression::~ITransientExpression() = default;
  8573. void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs ) {
  8574. if( lhs.size() + rhs.size() < 40 &&
  8575. lhs.find('\n') == std::string::npos &&
  8576. rhs.find('\n') == std::string::npos )
  8577. os << lhs << " " << op << " " << rhs;
  8578. else
  8579. os << lhs << "\n" << op << "\n" << rhs;
  8580. }
  8581. }
  8582. // end catch_decomposer.cpp
  8583. // start catch_enforce.cpp
  8584. #include <stdexcept>
  8585. namespace Catch {
  8586. #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS_CUSTOM_HANDLER)
  8587. [[noreturn]]
  8588. void throw_exception(std::exception const& e) {
  8589. Catch::cerr() << "Catch will terminate because it needed to throw an exception.\n"
  8590. << "The message was: " << e.what() << '\n';
  8591. std::terminate();
  8592. }
  8593. #endif
  8594. [[noreturn]]
  8595. void throw_logic_error(std::string const& msg) {
  8596. throw_exception(std::logic_error(msg));
  8597. }
  8598. [[noreturn]]
  8599. void throw_domain_error(std::string const& msg) {
  8600. throw_exception(std::domain_error(msg));
  8601. }
  8602. [[noreturn]]
  8603. void throw_runtime_error(std::string const& msg) {
  8604. throw_exception(std::runtime_error(msg));
  8605. }
  8606. } // namespace Catch;
  8607. // end catch_enforce.cpp
  8608. // start catch_enum_values_registry.cpp
  8609. // start catch_enum_values_registry.h
  8610. #include <vector>
  8611. #include <memory>
  8612. namespace Catch {
  8613. namespace Detail {
  8614. std::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int> const& values );
  8615. class EnumValuesRegistry : public IMutableEnumValuesRegistry {
  8616. std::vector<std::unique_ptr<EnumInfo>> m_enumInfos;
  8617. EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::vector<int> const& values) override;
  8618. };
  8619. std::vector<StringRef> parseEnums( StringRef enums );
  8620. } // Detail
  8621. } // Catch
  8622. // end catch_enum_values_registry.h
  8623. #include <map>
  8624. #include <cassert>
  8625. namespace Catch {
  8626. IMutableEnumValuesRegistry::~IMutableEnumValuesRegistry() {}
  8627. namespace Detail {
  8628. namespace {
  8629. // Extracts the actual name part of an enum instance
  8630. // In other words, it returns the Blue part of Bikeshed::Colour::Blue
  8631. StringRef extractInstanceName(StringRef enumInstance) {
  8632. // Find last occurrence of ":"
  8633. size_t name_start = enumInstance.size();
  8634. while (name_start > 0 && enumInstance[name_start - 1] != ':') {
  8635. --name_start;
  8636. }
  8637. return enumInstance.substr(name_start, enumInstance.size() - name_start);
  8638. }
  8639. }
  8640. std::vector<StringRef> parseEnums( StringRef enums ) {
  8641. auto enumValues = splitStringRef( enums, ',' );
  8642. std::vector<StringRef> parsed;
  8643. parsed.reserve( enumValues.size() );
  8644. for( auto const& enumValue : enumValues ) {
  8645. parsed.push_back(trim(extractInstanceName(enumValue)));
  8646. }
  8647. return parsed;
  8648. }
  8649. EnumInfo::~EnumInfo() {}
  8650. StringRef EnumInfo::lookup( int value ) const {
  8651. for( auto const& valueToName : m_values ) {
  8652. if( valueToName.first == value )
  8653. return valueToName.second;
  8654. }
  8655. return "{** unexpected enum value **}"_sr;
  8656. }
  8657. std::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ) {
  8658. std::unique_ptr<EnumInfo> enumInfo( new EnumInfo );
  8659. enumInfo->m_name = enumName;
  8660. enumInfo->m_values.reserve( values.size() );
  8661. const auto valueNames = Catch::Detail::parseEnums( allValueNames );
  8662. assert( valueNames.size() == values.size() );
  8663. std::size_t i = 0;
  8664. for( auto value : values )
  8665. enumInfo->m_values.emplace_back(value, valueNames[i++]);
  8666. return enumInfo;
  8667. }
  8668. EnumInfo const& EnumValuesRegistry::registerEnum( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ) {
  8669. m_enumInfos.push_back(makeEnumInfo(enumName, allValueNames, values));
  8670. return *m_enumInfos.back();
  8671. }
  8672. } // Detail
  8673. } // Catch
  8674. // end catch_enum_values_registry.cpp
  8675. // start catch_errno_guard.cpp
  8676. #include <cerrno>
  8677. namespace Catch {
  8678. ErrnoGuard::ErrnoGuard():m_oldErrno(errno){}
  8679. ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; }
  8680. }
  8681. // end catch_errno_guard.cpp
  8682. // start catch_exception_translator_registry.cpp
  8683. // start catch_exception_translator_registry.h
  8684. #include <vector>
  8685. #include <string>
  8686. #include <memory>
  8687. namespace Catch {
  8688. class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry {
  8689. public:
  8690. ~ExceptionTranslatorRegistry();
  8691. virtual void registerTranslator( const IExceptionTranslator* translator );
  8692. std::string translateActiveException() const override;
  8693. std::string tryTranslators() const;
  8694. private:
  8695. std::vector<std::unique_ptr<IExceptionTranslator const>> m_translators;
  8696. };
  8697. }
  8698. // end catch_exception_translator_registry.h
  8699. #ifdef __OBJC__
  8700. #import "Foundation/Foundation.h"
  8701. #endif
  8702. namespace Catch {
  8703. ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {
  8704. }
  8705. void ExceptionTranslatorRegistry::registerTranslator( const IExceptionTranslator* translator ) {
  8706. m_translators.push_back( std::unique_ptr<const IExceptionTranslator>( translator ) );
  8707. }
  8708. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  8709. std::string ExceptionTranslatorRegistry::translateActiveException() const {
  8710. try {
  8711. #ifdef __OBJC__
  8712. // In Objective-C try objective-c exceptions first
  8713. @try {
  8714. return tryTranslators();
  8715. }
  8716. @catch (NSException *exception) {
  8717. return Catch::Detail::stringify( [exception description] );
  8718. }
  8719. #else
  8720. // Compiling a mixed mode project with MSVC means that CLR
  8721. // exceptions will be caught in (...) as well. However, these
  8722. // do not fill-in std::current_exception and thus lead to crash
  8723. // when attempting rethrow.
  8724. // /EHa switch also causes structured exceptions to be caught
  8725. // here, but they fill-in current_exception properly, so
  8726. // at worst the output should be a little weird, instead of
  8727. // causing a crash.
  8728. if (std::current_exception() == nullptr) {
  8729. return "Non C++ exception. Possibly a CLR exception.";
  8730. }
  8731. return tryTranslators();
  8732. #endif
  8733. }
  8734. catch( TestFailureException& ) {
  8735. std::rethrow_exception(std::current_exception());
  8736. }
  8737. catch( std::exception& ex ) {
  8738. return ex.what();
  8739. }
  8740. catch( std::string& msg ) {
  8741. return msg;
  8742. }
  8743. catch( const char* msg ) {
  8744. return msg;
  8745. }
  8746. catch(...) {
  8747. return "Unknown exception";
  8748. }
  8749. }
  8750. std::string ExceptionTranslatorRegistry::tryTranslators() const {
  8751. if (m_translators.empty()) {
  8752. std::rethrow_exception(std::current_exception());
  8753. } else {
  8754. return m_translators[0]->translate(m_translators.begin() + 1, m_translators.end());
  8755. }
  8756. }
  8757. #else // ^^ Exceptions are enabled // Exceptions are disabled vv
  8758. std::string ExceptionTranslatorRegistry::translateActiveException() const {
  8759. CATCH_INTERNAL_ERROR("Attempted to translate active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
  8760. }
  8761. std::string ExceptionTranslatorRegistry::tryTranslators() const {
  8762. CATCH_INTERNAL_ERROR("Attempted to use exception translators under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
  8763. }
  8764. #endif
  8765. }
  8766. // end catch_exception_translator_registry.cpp
  8767. // start catch_fatal_condition.cpp
  8768. #include <algorithm>
  8769. #if !defined( CATCH_CONFIG_WINDOWS_SEH ) && !defined( CATCH_CONFIG_POSIX_SIGNALS )
  8770. namespace Catch {
  8771. // If neither SEH nor signal handling is required, the handler impls
  8772. // do not have to do anything, and can be empty.
  8773. void FatalConditionHandler::engage_platform() {}
  8774. void FatalConditionHandler::disengage_platform() {}
  8775. FatalConditionHandler::FatalConditionHandler() = default;
  8776. FatalConditionHandler::~FatalConditionHandler() = default;
  8777. } // end namespace Catch
  8778. #endif // !CATCH_CONFIG_WINDOWS_SEH && !CATCH_CONFIG_POSIX_SIGNALS
  8779. #if defined( CATCH_CONFIG_WINDOWS_SEH ) && defined( CATCH_CONFIG_POSIX_SIGNALS )
  8780. #error "Inconsistent configuration: Windows' SEH handling and POSIX signals cannot be enabled at the same time"
  8781. #endif // CATCH_CONFIG_WINDOWS_SEH && CATCH_CONFIG_POSIX_SIGNALS
  8782. #if defined( CATCH_CONFIG_WINDOWS_SEH ) || defined( CATCH_CONFIG_POSIX_SIGNALS )
  8783. namespace {
  8784. //! Signals fatal error message to the run context
  8785. void reportFatal( char const * const message ) {
  8786. Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition( message );
  8787. }
  8788. //! Minimal size Catch2 needs for its own fatal error handling.
  8789. //! Picked anecdotally, so it might not be sufficient on all
  8790. //! platforms, and for all configurations.
  8791. constexpr std::size_t minStackSizeForErrors = 32 * 1024;
  8792. } // end unnamed namespace
  8793. #endif // CATCH_CONFIG_WINDOWS_SEH || CATCH_CONFIG_POSIX_SIGNALS
  8794. #if defined( CATCH_CONFIG_WINDOWS_SEH )
  8795. namespace Catch {
  8796. struct SignalDefs { DWORD id; const char* name; };
  8797. // There is no 1-1 mapping between signals and windows exceptions.
  8798. // Windows can easily distinguish between SO and SigSegV,
  8799. // but SigInt, SigTerm, etc are handled differently.
  8800. static SignalDefs signalDefs[] = {
  8801. { static_cast<DWORD>(EXCEPTION_ILLEGAL_INSTRUCTION), "SIGILL - Illegal instruction signal" },
  8802. { static_cast<DWORD>(EXCEPTION_STACK_OVERFLOW), "SIGSEGV - Stack overflow" },
  8803. { static_cast<DWORD>(EXCEPTION_ACCESS_VIOLATION), "SIGSEGV - Segmentation violation signal" },
  8804. { static_cast<DWORD>(EXCEPTION_INT_DIVIDE_BY_ZERO), "Divide by zero error" },
  8805. };
  8806. static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {
  8807. for (auto const& def : signalDefs) {
  8808. if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) {
  8809. reportFatal(def.name);
  8810. }
  8811. }
  8812. // If its not an exception we care about, pass it along.
  8813. // This stops us from eating debugger breaks etc.
  8814. return EXCEPTION_CONTINUE_SEARCH;
  8815. }
  8816. // Since we do not support multiple instantiations, we put these
  8817. // into global variables and rely on cleaning them up in outlined
  8818. // constructors/destructors
  8819. static PVOID exceptionHandlerHandle = nullptr;
  8820. // For MSVC, we reserve part of the stack memory for handling
  8821. // memory overflow structured exception.
  8822. FatalConditionHandler::FatalConditionHandler() {
  8823. ULONG guaranteeSize = static_cast<ULONG>(minStackSizeForErrors);
  8824. if (!SetThreadStackGuarantee(&guaranteeSize)) {
  8825. // We do not want to fully error out, because needing
  8826. // the stack reserve should be rare enough anyway.
  8827. Catch::cerr()
  8828. << "Failed to reserve piece of stack."
  8829. << " Stack overflows will not be reported successfully.";
  8830. }
  8831. }
  8832. // We do not attempt to unset the stack guarantee, because
  8833. // Windows does not support lowering the stack size guarantee.
  8834. FatalConditionHandler::~FatalConditionHandler() = default;
  8835. void FatalConditionHandler::engage_platform() {
  8836. // Register as first handler in current chain
  8837. exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);
  8838. if (!exceptionHandlerHandle) {
  8839. CATCH_RUNTIME_ERROR("Could not register vectored exception handler");
  8840. }
  8841. }
  8842. void FatalConditionHandler::disengage_platform() {
  8843. if (!RemoveVectoredExceptionHandler(exceptionHandlerHandle)) {
  8844. CATCH_RUNTIME_ERROR("Could not unregister vectored exception handler");
  8845. }
  8846. exceptionHandlerHandle = nullptr;
  8847. }
  8848. } // end namespace Catch
  8849. #endif // CATCH_CONFIG_WINDOWS_SEH
  8850. #if defined( CATCH_CONFIG_POSIX_SIGNALS )
  8851. #include <signal.h>
  8852. namespace Catch {
  8853. struct SignalDefs {
  8854. int id;
  8855. const char* name;
  8856. };
  8857. static SignalDefs signalDefs[] = {
  8858. { SIGINT, "SIGINT - Terminal interrupt signal" },
  8859. { SIGILL, "SIGILL - Illegal instruction signal" },
  8860. { SIGFPE, "SIGFPE - Floating point error signal" },
  8861. { SIGSEGV, "SIGSEGV - Segmentation violation signal" },
  8862. { SIGTERM, "SIGTERM - Termination request signal" },
  8863. { SIGABRT, "SIGABRT - Abort (abnormal termination) signal" }
  8864. };
  8865. // Older GCCs trigger -Wmissing-field-initializers for T foo = {}
  8866. // which is zero initialization, but not explicit. We want to avoid
  8867. // that.
  8868. #if defined(__GNUC__)
  8869. # pragma GCC diagnostic push
  8870. # pragma GCC diagnostic ignored "-Wmissing-field-initializers"
  8871. #endif
  8872. static char* altStackMem = nullptr;
  8873. static std::size_t altStackSize = 0;
  8874. static stack_t oldSigStack{};
  8875. static struct sigaction oldSigActions[sizeof(signalDefs) / sizeof(SignalDefs)]{};
  8876. static void restorePreviousSignalHandlers() {
  8877. // We set signal handlers back to the previous ones. Hopefully
  8878. // nobody overwrote them in the meantime, and doesn't expect
  8879. // their signal handlers to live past ours given that they
  8880. // installed them after ours..
  8881. for (std::size_t i = 0; i < sizeof(signalDefs) / sizeof(SignalDefs); ++i) {
  8882. sigaction(signalDefs[i].id, &oldSigActions[i], nullptr);
  8883. }
  8884. // Return the old stack
  8885. sigaltstack(&oldSigStack, nullptr);
  8886. }
  8887. static void handleSignal( int sig ) {
  8888. char const * name = "<unknown signal>";
  8889. for (auto const& def : signalDefs) {
  8890. if (sig == def.id) {
  8891. name = def.name;
  8892. break;
  8893. }
  8894. }
  8895. // We need to restore previous signal handlers and let them do
  8896. // their thing, so that the users can have the debugger break
  8897. // when a signal is raised, and so on.
  8898. restorePreviousSignalHandlers();
  8899. reportFatal( name );
  8900. raise( sig );
  8901. }
  8902. FatalConditionHandler::FatalConditionHandler() {
  8903. assert(!altStackMem && "Cannot initialize POSIX signal handler when one already exists");
  8904. if (altStackSize == 0) {
  8905. altStackSize = std::max(static_cast<size_t>(SIGSTKSZ), minStackSizeForErrors);
  8906. }
  8907. altStackMem = new char[altStackSize]();
  8908. }
  8909. FatalConditionHandler::~FatalConditionHandler() {
  8910. delete[] altStackMem;
  8911. // We signal that another instance can be constructed by zeroing
  8912. // out the pointer.
  8913. altStackMem = nullptr;
  8914. }
  8915. void FatalConditionHandler::engage_platform() {
  8916. stack_t sigStack;
  8917. sigStack.ss_sp = altStackMem;
  8918. sigStack.ss_size = altStackSize;
  8919. sigStack.ss_flags = 0;
  8920. sigaltstack(&sigStack, &oldSigStack);
  8921. struct sigaction sa = { };
  8922. sa.sa_handler = handleSignal;
  8923. sa.sa_flags = SA_ONSTACK;
  8924. for (std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i) {
  8925. sigaction(signalDefs[i].id, &sa, &oldSigActions[i]);
  8926. }
  8927. }
  8928. #if defined(__GNUC__)
  8929. # pragma GCC diagnostic pop
  8930. #endif
  8931. void FatalConditionHandler::disengage_platform() {
  8932. restorePreviousSignalHandlers();
  8933. }
  8934. } // end namespace Catch
  8935. #endif // CATCH_CONFIG_POSIX_SIGNALS
  8936. // end catch_fatal_condition.cpp
  8937. // start catch_generators.cpp
  8938. #include <limits>
  8939. #include <set>
  8940. namespace Catch {
  8941. IGeneratorTracker::~IGeneratorTracker() {}
  8942. const char* GeneratorException::what() const noexcept {
  8943. return m_msg;
  8944. }
  8945. namespace Generators {
  8946. GeneratorUntypedBase::~GeneratorUntypedBase() {}
  8947. auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
  8948. return getResultCapture().acquireGeneratorTracker( generatorName, lineInfo );
  8949. }
  8950. } // namespace Generators
  8951. } // namespace Catch
  8952. // end catch_generators.cpp
  8953. // start catch_interfaces_capture.cpp
  8954. namespace Catch {
  8955. IResultCapture::~IResultCapture() = default;
  8956. }
  8957. // end catch_interfaces_capture.cpp
  8958. // start catch_interfaces_config.cpp
  8959. namespace Catch {
  8960. IConfig::~IConfig() = default;
  8961. }
  8962. // end catch_interfaces_config.cpp
  8963. // start catch_interfaces_exception.cpp
  8964. namespace Catch {
  8965. IExceptionTranslator::~IExceptionTranslator() = default;
  8966. IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() = default;
  8967. }
  8968. // end catch_interfaces_exception.cpp
  8969. // start catch_interfaces_registry_hub.cpp
  8970. namespace Catch {
  8971. IRegistryHub::~IRegistryHub() = default;
  8972. IMutableRegistryHub::~IMutableRegistryHub() = default;
  8973. }
  8974. // end catch_interfaces_registry_hub.cpp
  8975. // start catch_interfaces_reporter.cpp
  8976. // start catch_reporter_listening.h
  8977. namespace Catch {
  8978. class ListeningReporter : public IStreamingReporter {
  8979. using Reporters = std::vector<IStreamingReporterPtr>;
  8980. Reporters m_listeners;
  8981. IStreamingReporterPtr m_reporter = nullptr;
  8982. ReporterPreferences m_preferences;
  8983. public:
  8984. ListeningReporter();
  8985. void addListener( IStreamingReporterPtr&& listener );
  8986. void addReporter( IStreamingReporterPtr&& reporter );
  8987. public: // IStreamingReporter
  8988. ReporterPreferences getPreferences() const override;
  8989. void noMatchingTestCases( std::string const& spec ) override;
  8990. void reportInvalidArguments(std::string const&arg) override;
  8991. static std::set<Verbosity> getSupportedVerbosities();
  8992. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  8993. void benchmarkPreparing(std::string const& name) override;
  8994. void benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) override;
  8995. void benchmarkEnded( BenchmarkStats<> const& benchmarkStats ) override;
  8996. void benchmarkFailed(std::string const&) override;
  8997. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  8998. void testRunStarting( TestRunInfo const& testRunInfo ) override;
  8999. void testGroupStarting( GroupInfo const& groupInfo ) override;
  9000. void testCaseStarting( TestCaseInfo const& testInfo ) override;
  9001. void sectionStarting( SectionInfo const& sectionInfo ) override;
  9002. void assertionStarting( AssertionInfo const& assertionInfo ) override;
  9003. // The return value indicates if the messages buffer should be cleared:
  9004. bool assertionEnded( AssertionStats const& assertionStats ) override;
  9005. void sectionEnded( SectionStats const& sectionStats ) override;
  9006. void testCaseEnded( TestCaseStats const& testCaseStats ) override;
  9007. void testGroupEnded( TestGroupStats const& testGroupStats ) override;
  9008. void testRunEnded( TestRunStats const& testRunStats ) override;
  9009. void skipTest( TestCaseInfo const& testInfo ) override;
  9010. bool isMulti() const override;
  9011. };
  9012. } // end namespace Catch
  9013. // end catch_reporter_listening.h
  9014. namespace Catch {
  9015. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig )
  9016. : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {}
  9017. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream )
  9018. : m_stream( &_stream ), m_fullConfig( _fullConfig ) {}
  9019. std::ostream& ReporterConfig::stream() const { return *m_stream; }
  9020. IConfigPtr ReporterConfig::fullConfig() const { return m_fullConfig; }
  9021. TestRunInfo::TestRunInfo( std::string const& _name ) : name( _name ) {}
  9022. GroupInfo::GroupInfo( std::string const& _name,
  9023. std::size_t _groupIndex,
  9024. std::size_t _groupsCount )
  9025. : name( _name ),
  9026. groupIndex( _groupIndex ),
  9027. groupsCounts( _groupsCount )
  9028. {}
  9029. AssertionStats::AssertionStats( AssertionResult const& _assertionResult,
  9030. std::vector<MessageInfo> const& _infoMessages,
  9031. Totals const& _totals )
  9032. : assertionResult( _assertionResult ),
  9033. infoMessages( _infoMessages ),
  9034. totals( _totals )
  9035. {
  9036. assertionResult.m_resultData.lazyExpression.m_transientExpression = _assertionResult.m_resultData.lazyExpression.m_transientExpression;
  9037. if( assertionResult.hasMessage() ) {
  9038. // Copy message into messages list.
  9039. // !TBD This should have been done earlier, somewhere
  9040. MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() );
  9041. builder << assertionResult.getMessage();
  9042. builder.m_info.message = builder.m_stream.str();
  9043. infoMessages.push_back( builder.m_info );
  9044. }
  9045. }
  9046. AssertionStats::~AssertionStats() = default;
  9047. SectionStats::SectionStats( SectionInfo const& _sectionInfo,
  9048. Counts const& _assertions,
  9049. double _durationInSeconds,
  9050. bool _missingAssertions )
  9051. : sectionInfo( _sectionInfo ),
  9052. assertions( _assertions ),
  9053. durationInSeconds( _durationInSeconds ),
  9054. missingAssertions( _missingAssertions )
  9055. {}
  9056. SectionStats::~SectionStats() = default;
  9057. TestCaseStats::TestCaseStats( TestCaseInfo const& _testInfo,
  9058. Totals const& _totals,
  9059. std::string const& _stdOut,
  9060. std::string const& _stdErr,
  9061. bool _aborting )
  9062. : testInfo( _testInfo ),
  9063. totals( _totals ),
  9064. stdOut( _stdOut ),
  9065. stdErr( _stdErr ),
  9066. aborting( _aborting )
  9067. {}
  9068. TestCaseStats::~TestCaseStats() = default;
  9069. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo,
  9070. Totals const& _totals,
  9071. bool _aborting )
  9072. : groupInfo( _groupInfo ),
  9073. totals( _totals ),
  9074. aborting( _aborting )
  9075. {}
  9076. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo )
  9077. : groupInfo( _groupInfo ),
  9078. aborting( false )
  9079. {}
  9080. TestGroupStats::~TestGroupStats() = default;
  9081. TestRunStats::TestRunStats( TestRunInfo const& _runInfo,
  9082. Totals const& _totals,
  9083. bool _aborting )
  9084. : runInfo( _runInfo ),
  9085. totals( _totals ),
  9086. aborting( _aborting )
  9087. {}
  9088. TestRunStats::~TestRunStats() = default;
  9089. void IStreamingReporter::fatalErrorEncountered( StringRef ) {}
  9090. bool IStreamingReporter::isMulti() const { return false; }
  9091. IReporterFactory::~IReporterFactory() = default;
  9092. IReporterRegistry::~IReporterRegistry() = default;
  9093. } // end namespace Catch
  9094. // end catch_interfaces_reporter.cpp
  9095. // start catch_interfaces_runner.cpp
  9096. namespace Catch {
  9097. IRunner::~IRunner() = default;
  9098. }
  9099. // end catch_interfaces_runner.cpp
  9100. // start catch_interfaces_testcase.cpp
  9101. namespace Catch {
  9102. ITestInvoker::~ITestInvoker() = default;
  9103. ITestCaseRegistry::~ITestCaseRegistry() = default;
  9104. }
  9105. // end catch_interfaces_testcase.cpp
  9106. // start catch_leak_detector.cpp
  9107. #ifdef CATCH_CONFIG_WINDOWS_CRTDBG
  9108. #include <crtdbg.h>
  9109. namespace Catch {
  9110. LeakDetector::LeakDetector() {
  9111. int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
  9112. flag |= _CRTDBG_LEAK_CHECK_DF;
  9113. flag |= _CRTDBG_ALLOC_MEM_DF;
  9114. _CrtSetDbgFlag(flag);
  9115. _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
  9116. _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
  9117. // Change this to leaking allocation's number to break there
  9118. _CrtSetBreakAlloc(-1);
  9119. }
  9120. }
  9121. #else
  9122. Catch::LeakDetector::LeakDetector() {}
  9123. #endif
  9124. Catch::LeakDetector::~LeakDetector() {
  9125. Catch::cleanUp();
  9126. }
  9127. // end catch_leak_detector.cpp
  9128. // start catch_list.cpp
  9129. // start catch_list.h
  9130. #include <set>
  9131. namespace Catch {
  9132. std::size_t listTests( Config const& config );
  9133. std::size_t listTestsNamesOnly( Config const& config );
  9134. struct TagInfo {
  9135. void add( std::string const& spelling );
  9136. std::string all() const;
  9137. std::set<std::string> spellings;
  9138. std::size_t count = 0;
  9139. };
  9140. std::size_t listTags( Config const& config );
  9141. std::size_t listReporters();
  9142. Option<std::size_t> list( std::shared_ptr<Config> const& config );
  9143. } // end namespace Catch
  9144. // end catch_list.h
  9145. // start catch_text.h
  9146. namespace Catch {
  9147. using namespace clara::TextFlow;
  9148. }
  9149. // end catch_text.h
  9150. #include <limits>
  9151. #include <algorithm>
  9152. #include <iomanip>
  9153. namespace Catch {
  9154. std::size_t listTests( Config const& config ) {
  9155. TestSpec const& testSpec = config.testSpec();
  9156. if( config.hasTestFilters() )
  9157. Catch::cout() << "Matching test cases:\n";
  9158. else {
  9159. Catch::cout() << "All available test cases:\n";
  9160. }
  9161. auto matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  9162. for( auto const& testCaseInfo : matchedTestCases ) {
  9163. Colour::Code colour = testCaseInfo.isHidden()
  9164. ? Colour::SecondaryText
  9165. : Colour::None;
  9166. Colour colourGuard( colour );
  9167. Catch::cout() << Column( testCaseInfo.name ).initialIndent( 2 ).indent( 4 ) << "\n";
  9168. if( config.verbosity() >= Verbosity::High ) {
  9169. Catch::cout() << Column( Catch::Detail::stringify( testCaseInfo.lineInfo ) ).indent(4) << std::endl;
  9170. std::string description = testCaseInfo.description;
  9171. if( description.empty() )
  9172. description = "(NO DESCRIPTION)";
  9173. Catch::cout() << Column( description ).indent(4) << std::endl;
  9174. }
  9175. if( !testCaseInfo.tags.empty() )
  9176. Catch::cout() << Column( testCaseInfo.tagsAsString() ).indent( 6 ) << "\n";
  9177. }
  9178. if( !config.hasTestFilters() )
  9179. Catch::cout() << pluralise( matchedTestCases.size(), "test case" ) << '\n' << std::endl;
  9180. else
  9181. Catch::cout() << pluralise( matchedTestCases.size(), "matching test case" ) << '\n' << std::endl;
  9182. return matchedTestCases.size();
  9183. }
  9184. std::size_t listTestsNamesOnly( Config const& config ) {
  9185. TestSpec const& testSpec = config.testSpec();
  9186. std::size_t matchedTests = 0;
  9187. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  9188. for( auto const& testCaseInfo : matchedTestCases ) {
  9189. matchedTests++;
  9190. if( startsWith( testCaseInfo.name, '#' ) )
  9191. Catch::cout() << '"' << testCaseInfo.name << '"';
  9192. else
  9193. Catch::cout() << testCaseInfo.name;
  9194. if ( config.verbosity() >= Verbosity::High )
  9195. Catch::cout() << "\t@" << testCaseInfo.lineInfo;
  9196. Catch::cout() << std::endl;
  9197. }
  9198. return matchedTests;
  9199. }
  9200. void TagInfo::add( std::string const& spelling ) {
  9201. ++count;
  9202. spellings.insert( spelling );
  9203. }
  9204. std::string TagInfo::all() const {
  9205. size_t size = 0;
  9206. for (auto const& spelling : spellings) {
  9207. // Add 2 for the brackes
  9208. size += spelling.size() + 2;
  9209. }
  9210. std::string out; out.reserve(size);
  9211. for (auto const& spelling : spellings) {
  9212. out += '[';
  9213. out += spelling;
  9214. out += ']';
  9215. }
  9216. return out;
  9217. }
  9218. std::size_t listTags( Config const& config ) {
  9219. TestSpec const& testSpec = config.testSpec();
  9220. if( config.hasTestFilters() )
  9221. Catch::cout() << "Tags for matching test cases:\n";
  9222. else {
  9223. Catch::cout() << "All available tags:\n";
  9224. }
  9225. std::map<std::string, TagInfo> tagCounts;
  9226. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  9227. for( auto const& testCase : matchedTestCases ) {
  9228. for( auto const& tagName : testCase.getTestCaseInfo().tags ) {
  9229. std::string lcaseTagName = toLower( tagName );
  9230. auto countIt = tagCounts.find( lcaseTagName );
  9231. if( countIt == tagCounts.end() )
  9232. countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first;
  9233. countIt->second.add( tagName );
  9234. }
  9235. }
  9236. for( auto const& tagCount : tagCounts ) {
  9237. ReusableStringStream rss;
  9238. rss << " " << std::setw(2) << tagCount.second.count << " ";
  9239. auto str = rss.str();
  9240. auto wrapper = Column( tagCount.second.all() )
  9241. .initialIndent( 0 )
  9242. .indent( str.size() )
  9243. .width( CATCH_CONFIG_CONSOLE_WIDTH-10 );
  9244. Catch::cout() << str << wrapper << '\n';
  9245. }
  9246. Catch::cout() << pluralise( tagCounts.size(), "tag" ) << '\n' << std::endl;
  9247. return tagCounts.size();
  9248. }
  9249. std::size_t listReporters() {
  9250. Catch::cout() << "Available reporters:\n";
  9251. IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
  9252. std::size_t maxNameLen = 0;
  9253. for( auto const& factoryKvp : factories )
  9254. maxNameLen = (std::max)( maxNameLen, factoryKvp.first.size() );
  9255. for( auto const& factoryKvp : factories ) {
  9256. Catch::cout()
  9257. << Column( factoryKvp.first + ":" )
  9258. .indent(2)
  9259. .width( 5+maxNameLen )
  9260. + Column( factoryKvp.second->getDescription() )
  9261. .initialIndent(0)
  9262. .indent(2)
  9263. .width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 )
  9264. << "\n";
  9265. }
  9266. Catch::cout() << std::endl;
  9267. return factories.size();
  9268. }
  9269. Option<std::size_t> list( std::shared_ptr<Config> const& config ) {
  9270. Option<std::size_t> listedCount;
  9271. getCurrentMutableContext().setConfig( config );
  9272. if( config->listTests() )
  9273. listedCount = listedCount.valueOr(0) + listTests( *config );
  9274. if( config->listTestNamesOnly() )
  9275. listedCount = listedCount.valueOr(0) + listTestsNamesOnly( *config );
  9276. if( config->listTags() )
  9277. listedCount = listedCount.valueOr(0) + listTags( *config );
  9278. if( config->listReporters() )
  9279. listedCount = listedCount.valueOr(0) + listReporters();
  9280. return listedCount;
  9281. }
  9282. } // end namespace Catch
  9283. // end catch_list.cpp
  9284. // start catch_matchers.cpp
  9285. namespace Catch {
  9286. namespace Matchers {
  9287. namespace Impl {
  9288. std::string MatcherUntypedBase::toString() const {
  9289. if( m_cachedToString.empty() )
  9290. m_cachedToString = describe();
  9291. return m_cachedToString;
  9292. }
  9293. MatcherUntypedBase::~MatcherUntypedBase() = default;
  9294. } // namespace Impl
  9295. } // namespace Matchers
  9296. using namespace Matchers;
  9297. using Matchers::Impl::MatcherBase;
  9298. } // namespace Catch
  9299. // end catch_matchers.cpp
  9300. // start catch_matchers_exception.cpp
  9301. namespace Catch {
  9302. namespace Matchers {
  9303. namespace Exception {
  9304. bool ExceptionMessageMatcher::match(std::exception const& ex) const {
  9305. return ex.what() == m_message;
  9306. }
  9307. std::string ExceptionMessageMatcher::describe() const {
  9308. return "exception message matches \"" + m_message + "\"";
  9309. }
  9310. }
  9311. Exception::ExceptionMessageMatcher Message(std::string const& message) {
  9312. return Exception::ExceptionMessageMatcher(message);
  9313. }
  9314. // namespace Exception
  9315. } // namespace Matchers
  9316. } // namespace Catch
  9317. // end catch_matchers_exception.cpp
  9318. // start catch_matchers_floating.cpp
  9319. // start catch_polyfills.hpp
  9320. namespace Catch {
  9321. bool isnan(float f);
  9322. bool isnan(double d);
  9323. }
  9324. // end catch_polyfills.hpp
  9325. // start catch_to_string.hpp
  9326. #include <string>
  9327. namespace Catch {
  9328. template <typename T>
  9329. std::string to_string(T const& t) {
  9330. #if defined(CATCH_CONFIG_CPP11_TO_STRING)
  9331. return std::to_string(t);
  9332. #else
  9333. ReusableStringStream rss;
  9334. rss << t;
  9335. return rss.str();
  9336. #endif
  9337. }
  9338. } // end namespace Catch
  9339. // end catch_to_string.hpp
  9340. #include <algorithm>
  9341. #include <cmath>
  9342. #include <cstdlib>
  9343. #include <cstdint>
  9344. #include <cstring>
  9345. #include <sstream>
  9346. #include <type_traits>
  9347. #include <iomanip>
  9348. #include <limits>
  9349. namespace Catch {
  9350. namespace {
  9351. int32_t convert(float f) {
  9352. static_assert(sizeof(float) == sizeof(int32_t), "Important ULP matcher assumption violated");
  9353. int32_t i;
  9354. std::memcpy(&i, &f, sizeof(f));
  9355. return i;
  9356. }
  9357. int64_t convert(double d) {
  9358. static_assert(sizeof(double) == sizeof(int64_t), "Important ULP matcher assumption violated");
  9359. int64_t i;
  9360. std::memcpy(&i, &d, sizeof(d));
  9361. return i;
  9362. }
  9363. template <typename FP>
  9364. bool almostEqualUlps(FP lhs, FP rhs, uint64_t maxUlpDiff) {
  9365. // Comparison with NaN should always be false.
  9366. // This way we can rule it out before getting into the ugly details
  9367. if (Catch::isnan(lhs) || Catch::isnan(rhs)) {
  9368. return false;
  9369. }
  9370. auto lc = convert(lhs);
  9371. auto rc = convert(rhs);
  9372. if ((lc < 0) != (rc < 0)) {
  9373. // Potentially we can have +0 and -0
  9374. return lhs == rhs;
  9375. }
  9376. // static cast as a workaround for IBM XLC
  9377. auto ulpDiff = std::abs(static_cast<FP>(lc - rc));
  9378. return static_cast<uint64_t>(ulpDiff) <= maxUlpDiff;
  9379. }
  9380. #if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
  9381. float nextafter(float x, float y) {
  9382. return ::nextafterf(x, y);
  9383. }
  9384. double nextafter(double x, double y) {
  9385. return ::nextafter(x, y);
  9386. }
  9387. #endif // ^^^ CATCH_CONFIG_GLOBAL_NEXTAFTER ^^^
  9388. template <typename FP>
  9389. FP step(FP start, FP direction, uint64_t steps) {
  9390. for (uint64_t i = 0; i < steps; ++i) {
  9391. #if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
  9392. start = Catch::nextafter(start, direction);
  9393. #else
  9394. start = std::nextafter(start, direction);
  9395. #endif
  9396. }
  9397. return start;
  9398. }
  9399. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  9400. // But without the subtraction to allow for INFINITY in comparison
  9401. bool marginComparison(double lhs, double rhs, double margin) {
  9402. return (lhs + margin >= rhs) && (rhs + margin >= lhs);
  9403. }
  9404. template <typename FloatingPoint>
  9405. void write(std::ostream& out, FloatingPoint num) {
  9406. out << std::scientific
  9407. << std::setprecision(std::numeric_limits<FloatingPoint>::max_digits10 - 1)
  9408. << num;
  9409. }
  9410. } // end anonymous namespace
  9411. namespace Matchers {
  9412. namespace Floating {
  9413. enum class FloatingPointKind : uint8_t {
  9414. Float,
  9415. Double
  9416. };
  9417. WithinAbsMatcher::WithinAbsMatcher(double target, double margin)
  9418. :m_target{ target }, m_margin{ margin } {
  9419. CATCH_ENFORCE(margin >= 0, "Invalid margin: " << margin << '.'
  9420. << " Margin has to be non-negative.");
  9421. }
  9422. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  9423. // But without the subtraction to allow for INFINITY in comparison
  9424. bool WithinAbsMatcher::match(double const& matchee) const {
  9425. return (matchee + m_margin >= m_target) && (m_target + m_margin >= matchee);
  9426. }
  9427. std::string WithinAbsMatcher::describe() const {
  9428. return "is within " + ::Catch::Detail::stringify(m_margin) + " of " + ::Catch::Detail::stringify(m_target);
  9429. }
  9430. WithinUlpsMatcher::WithinUlpsMatcher(double target, uint64_t ulps, FloatingPointKind baseType)
  9431. :m_target{ target }, m_ulps{ ulps }, m_type{ baseType } {
  9432. CATCH_ENFORCE(m_type == FloatingPointKind::Double
  9433. || m_ulps < (std::numeric_limits<uint32_t>::max)(),
  9434. "Provided ULP is impossibly large for a float comparison.");
  9435. }
  9436. #if defined(__clang__)
  9437. #pragma clang diagnostic push
  9438. // Clang <3.5 reports on the default branch in the switch below
  9439. #pragma clang diagnostic ignored "-Wunreachable-code"
  9440. #endif
  9441. bool WithinUlpsMatcher::match(double const& matchee) const {
  9442. switch (m_type) {
  9443. case FloatingPointKind::Float:
  9444. return almostEqualUlps<float>(static_cast<float>(matchee), static_cast<float>(m_target), m_ulps);
  9445. case FloatingPointKind::Double:
  9446. return almostEqualUlps<double>(matchee, m_target, m_ulps);
  9447. default:
  9448. CATCH_INTERNAL_ERROR( "Unknown FloatingPointKind value" );
  9449. }
  9450. }
  9451. #if defined(__clang__)
  9452. #pragma clang diagnostic pop
  9453. #endif
  9454. std::string WithinUlpsMatcher::describe() const {
  9455. std::stringstream ret;
  9456. ret << "is within " << m_ulps << " ULPs of ";
  9457. if (m_type == FloatingPointKind::Float) {
  9458. write(ret, static_cast<float>(m_target));
  9459. ret << 'f';
  9460. } else {
  9461. write(ret, m_target);
  9462. }
  9463. ret << " ([";
  9464. if (m_type == FloatingPointKind::Double) {
  9465. write(ret, step(m_target, static_cast<double>(-INFINITY), m_ulps));
  9466. ret << ", ";
  9467. write(ret, step(m_target, static_cast<double>( INFINITY), m_ulps));
  9468. } else {
  9469. // We have to cast INFINITY to float because of MinGW, see #1782
  9470. write(ret, step(static_cast<float>(m_target), static_cast<float>(-INFINITY), m_ulps));
  9471. ret << ", ";
  9472. write(ret, step(static_cast<float>(m_target), static_cast<float>( INFINITY), m_ulps));
  9473. }
  9474. ret << "])";
  9475. return ret.str();
  9476. }
  9477. WithinRelMatcher::WithinRelMatcher(double target, double epsilon):
  9478. m_target(target),
  9479. m_epsilon(epsilon){
  9480. CATCH_ENFORCE(m_epsilon >= 0., "Relative comparison with epsilon < 0 does not make sense.");
  9481. CATCH_ENFORCE(m_epsilon < 1., "Relative comparison with epsilon >= 1 does not make sense.");
  9482. }
  9483. bool WithinRelMatcher::match(double const& matchee) const {
  9484. const auto relMargin = m_epsilon * (std::max)(std::fabs(matchee), std::fabs(m_target));
  9485. return marginComparison(matchee, m_target,
  9486. std::isinf(relMargin)? 0 : relMargin);
  9487. }
  9488. std::string WithinRelMatcher::describe() const {
  9489. Catch::ReusableStringStream sstr;
  9490. sstr << "and " << m_target << " are within " << m_epsilon * 100. << "% of each other";
  9491. return sstr.str();
  9492. }
  9493. }// namespace Floating
  9494. Floating::WithinUlpsMatcher WithinULP(double target, uint64_t maxUlpDiff) {
  9495. return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Double);
  9496. }
  9497. Floating::WithinUlpsMatcher WithinULP(float target, uint64_t maxUlpDiff) {
  9498. return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Float);
  9499. }
  9500. Floating::WithinAbsMatcher WithinAbs(double target, double margin) {
  9501. return Floating::WithinAbsMatcher(target, margin);
  9502. }
  9503. Floating::WithinRelMatcher WithinRel(double target, double eps) {
  9504. return Floating::WithinRelMatcher(target, eps);
  9505. }
  9506. Floating::WithinRelMatcher WithinRel(double target) {
  9507. return Floating::WithinRelMatcher(target, std::numeric_limits<double>::epsilon() * 100);
  9508. }
  9509. Floating::WithinRelMatcher WithinRel(float target, float eps) {
  9510. return Floating::WithinRelMatcher(target, eps);
  9511. }
  9512. Floating::WithinRelMatcher WithinRel(float target) {
  9513. return Floating::WithinRelMatcher(target, std::numeric_limits<float>::epsilon() * 100);
  9514. }
  9515. } // namespace Matchers
  9516. } // namespace Catch
  9517. // end catch_matchers_floating.cpp
  9518. // start catch_matchers_generic.cpp
  9519. std::string Catch::Matchers::Generic::Detail::finalizeDescription(const std::string& desc) {
  9520. if (desc.empty()) {
  9521. return "matches undescribed predicate";
  9522. } else {
  9523. return "matches predicate: \"" + desc + '"';
  9524. }
  9525. }
  9526. // end catch_matchers_generic.cpp
  9527. // start catch_matchers_string.cpp
  9528. #include <regex>
  9529. namespace Catch {
  9530. namespace Matchers {
  9531. namespace StdString {
  9532. CasedString::CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity )
  9533. : m_caseSensitivity( caseSensitivity ),
  9534. m_str( adjustString( str ) )
  9535. {}
  9536. std::string CasedString::adjustString( std::string const& str ) const {
  9537. return m_caseSensitivity == CaseSensitive::No
  9538. ? toLower( str )
  9539. : str;
  9540. }
  9541. std::string CasedString::caseSensitivitySuffix() const {
  9542. return m_caseSensitivity == CaseSensitive::No
  9543. ? " (case insensitive)"
  9544. : std::string();
  9545. }
  9546. StringMatcherBase::StringMatcherBase( std::string const& operation, CasedString const& comparator )
  9547. : m_comparator( comparator ),
  9548. m_operation( operation ) {
  9549. }
  9550. std::string StringMatcherBase::describe() const {
  9551. std::string description;
  9552. description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
  9553. m_comparator.caseSensitivitySuffix().size());
  9554. description += m_operation;
  9555. description += ": \"";
  9556. description += m_comparator.m_str;
  9557. description += "\"";
  9558. description += m_comparator.caseSensitivitySuffix();
  9559. return description;
  9560. }
  9561. EqualsMatcher::EqualsMatcher( CasedString const& comparator ) : StringMatcherBase( "equals", comparator ) {}
  9562. bool EqualsMatcher::match( std::string const& source ) const {
  9563. return m_comparator.adjustString( source ) == m_comparator.m_str;
  9564. }
  9565. ContainsMatcher::ContainsMatcher( CasedString const& comparator ) : StringMatcherBase( "contains", comparator ) {}
  9566. bool ContainsMatcher::match( std::string const& source ) const {
  9567. return contains( m_comparator.adjustString( source ), m_comparator.m_str );
  9568. }
  9569. StartsWithMatcher::StartsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "starts with", comparator ) {}
  9570. bool StartsWithMatcher::match( std::string const& source ) const {
  9571. return startsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  9572. }
  9573. EndsWithMatcher::EndsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "ends with", comparator ) {}
  9574. bool EndsWithMatcher::match( std::string const& source ) const {
  9575. return endsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  9576. }
  9577. RegexMatcher::RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity): m_regex(std::move(regex)), m_caseSensitivity(caseSensitivity) {}
  9578. bool RegexMatcher::match(std::string const& matchee) const {
  9579. auto flags = std::regex::ECMAScript; // ECMAScript is the default syntax option anyway
  9580. if (m_caseSensitivity == CaseSensitive::Choice::No) {
  9581. flags |= std::regex::icase;
  9582. }
  9583. auto reg = std::regex(m_regex, flags);
  9584. return std::regex_match(matchee, reg);
  9585. }
  9586. std::string RegexMatcher::describe() const {
  9587. return "matches " + ::Catch::Detail::stringify(m_regex) + ((m_caseSensitivity == CaseSensitive::Choice::Yes)? " case sensitively" : " case insensitively");
  9588. }
  9589. } // namespace StdString
  9590. StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  9591. return StdString::EqualsMatcher( StdString::CasedString( str, caseSensitivity) );
  9592. }
  9593. StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  9594. return StdString::ContainsMatcher( StdString::CasedString( str, caseSensitivity) );
  9595. }
  9596. StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  9597. return StdString::EndsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  9598. }
  9599. StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  9600. return StdString::StartsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  9601. }
  9602. StdString::RegexMatcher Matches(std::string const& regex, CaseSensitive::Choice caseSensitivity) {
  9603. return StdString::RegexMatcher(regex, caseSensitivity);
  9604. }
  9605. } // namespace Matchers
  9606. } // namespace Catch
  9607. // end catch_matchers_string.cpp
  9608. // start catch_message.cpp
  9609. // start catch_uncaught_exceptions.h
  9610. namespace Catch {
  9611. bool uncaught_exceptions();
  9612. } // end namespace Catch
  9613. // end catch_uncaught_exceptions.h
  9614. #include <cassert>
  9615. #include <stack>
  9616. namespace Catch {
  9617. MessageInfo::MessageInfo( StringRef const& _macroName,
  9618. SourceLineInfo const& _lineInfo,
  9619. ResultWas::OfType _type )
  9620. : macroName( _macroName ),
  9621. lineInfo( _lineInfo ),
  9622. type( _type ),
  9623. sequence( ++globalCount )
  9624. {}
  9625. bool MessageInfo::operator==( MessageInfo const& other ) const {
  9626. return sequence == other.sequence;
  9627. }
  9628. bool MessageInfo::operator<( MessageInfo const& other ) const {
  9629. return sequence < other.sequence;
  9630. }
  9631. // This may need protecting if threading support is added
  9632. unsigned int MessageInfo::globalCount = 0;
  9633. ////////////////////////////////////////////////////////////////////////////
  9634. Catch::MessageBuilder::MessageBuilder( StringRef const& macroName,
  9635. SourceLineInfo const& lineInfo,
  9636. ResultWas::OfType type )
  9637. :m_info(macroName, lineInfo, type) {}
  9638. ////////////////////////////////////////////////////////////////////////////
  9639. ScopedMessage::ScopedMessage( MessageBuilder const& builder )
  9640. : m_info( builder.m_info ), m_moved()
  9641. {
  9642. m_info.message = builder.m_stream.str();
  9643. getResultCapture().pushScopedMessage( m_info );
  9644. }
  9645. ScopedMessage::ScopedMessage( ScopedMessage&& old )
  9646. : m_info( old.m_info ), m_moved()
  9647. {
  9648. old.m_moved = true;
  9649. }
  9650. ScopedMessage::~ScopedMessage() {
  9651. if ( !uncaught_exceptions() && !m_moved ){
  9652. getResultCapture().popScopedMessage(m_info);
  9653. }
  9654. }
  9655. Capturer::Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names ) {
  9656. auto trimmed = [&] (size_t start, size_t end) {
  9657. while (names[start] == ',' || isspace(static_cast<unsigned char>(names[start]))) {
  9658. ++start;
  9659. }
  9660. while (names[end] == ',' || isspace(static_cast<unsigned char>(names[end]))) {
  9661. --end;
  9662. }
  9663. return names.substr(start, end - start + 1);
  9664. };
  9665. auto skipq = [&] (size_t start, char quote) {
  9666. for (auto i = start + 1; i < names.size() ; ++i) {
  9667. if (names[i] == quote)
  9668. return i;
  9669. if (names[i] == '\\')
  9670. ++i;
  9671. }
  9672. CATCH_INTERNAL_ERROR("CAPTURE parsing encountered unmatched quote");
  9673. };
  9674. size_t start = 0;
  9675. std::stack<char> openings;
  9676. for (size_t pos = 0; pos < names.size(); ++pos) {
  9677. char c = names[pos];
  9678. switch (c) {
  9679. case '[':
  9680. case '{':
  9681. case '(':
  9682. // It is basically impossible to disambiguate between
  9683. // comparison and start of template args in this context
  9684. // case '<':
  9685. openings.push(c);
  9686. break;
  9687. case ']':
  9688. case '}':
  9689. case ')':
  9690. // case '>':
  9691. openings.pop();
  9692. break;
  9693. case '"':
  9694. case '\'':
  9695. pos = skipq(pos, c);
  9696. break;
  9697. case ',':
  9698. if (start != pos && openings.empty()) {
  9699. m_messages.emplace_back(macroName, lineInfo, resultType);
  9700. m_messages.back().message = static_cast<std::string>(trimmed(start, pos));
  9701. m_messages.back().message += " := ";
  9702. start = pos;
  9703. }
  9704. }
  9705. }
  9706. assert(openings.empty() && "Mismatched openings");
  9707. m_messages.emplace_back(macroName, lineInfo, resultType);
  9708. m_messages.back().message = static_cast<std::string>(trimmed(start, names.size() - 1));
  9709. m_messages.back().message += " := ";
  9710. }
  9711. Capturer::~Capturer() {
  9712. if ( !uncaught_exceptions() ){
  9713. assert( m_captured == m_messages.size() );
  9714. for( size_t i = 0; i < m_captured; ++i )
  9715. m_resultCapture.popScopedMessage( m_messages[i] );
  9716. }
  9717. }
  9718. void Capturer::captureValue( size_t index, std::string const& value ) {
  9719. assert( index < m_messages.size() );
  9720. m_messages[index].message += value;
  9721. m_resultCapture.pushScopedMessage( m_messages[index] );
  9722. m_captured++;
  9723. }
  9724. } // end namespace Catch
  9725. // end catch_message.cpp
  9726. // start catch_output_redirect.cpp
  9727. // start catch_output_redirect.h
  9728. #ifndef TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  9729. #define TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  9730. #include <cstdio>
  9731. #include <iosfwd>
  9732. #include <string>
  9733. namespace Catch {
  9734. class RedirectedStream {
  9735. std::ostream& m_originalStream;
  9736. std::ostream& m_redirectionStream;
  9737. std::streambuf* m_prevBuf;
  9738. public:
  9739. RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream );
  9740. ~RedirectedStream();
  9741. };
  9742. class RedirectedStdOut {
  9743. ReusableStringStream m_rss;
  9744. RedirectedStream m_cout;
  9745. public:
  9746. RedirectedStdOut();
  9747. auto str() const -> std::string;
  9748. };
  9749. // StdErr has two constituent streams in C++, std::cerr and std::clog
  9750. // This means that we need to redirect 2 streams into 1 to keep proper
  9751. // order of writes
  9752. class RedirectedStdErr {
  9753. ReusableStringStream m_rss;
  9754. RedirectedStream m_cerr;
  9755. RedirectedStream m_clog;
  9756. public:
  9757. RedirectedStdErr();
  9758. auto str() const -> std::string;
  9759. };
  9760. class RedirectedStreams {
  9761. public:
  9762. RedirectedStreams(RedirectedStreams const&) = delete;
  9763. RedirectedStreams& operator=(RedirectedStreams const&) = delete;
  9764. RedirectedStreams(RedirectedStreams&&) = delete;
  9765. RedirectedStreams& operator=(RedirectedStreams&&) = delete;
  9766. RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr);
  9767. ~RedirectedStreams();
  9768. private:
  9769. std::string& m_redirectedCout;
  9770. std::string& m_redirectedCerr;
  9771. RedirectedStdOut m_redirectedStdOut;
  9772. RedirectedStdErr m_redirectedStdErr;
  9773. };
  9774. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  9775. // Windows's implementation of std::tmpfile is terrible (it tries
  9776. // to create a file inside system folder, thus requiring elevated
  9777. // privileges for the binary), so we have to use tmpnam(_s) and
  9778. // create the file ourselves there.
  9779. class TempFile {
  9780. public:
  9781. TempFile(TempFile const&) = delete;
  9782. TempFile& operator=(TempFile const&) = delete;
  9783. TempFile(TempFile&&) = delete;
  9784. TempFile& operator=(TempFile&&) = delete;
  9785. TempFile();
  9786. ~TempFile();
  9787. std::FILE* getFile();
  9788. std::string getContents();
  9789. private:
  9790. std::FILE* m_file = nullptr;
  9791. #if defined(_MSC_VER)
  9792. char m_buffer[L_tmpnam] = { 0 };
  9793. #endif
  9794. };
  9795. class OutputRedirect {
  9796. public:
  9797. OutputRedirect(OutputRedirect const&) = delete;
  9798. OutputRedirect& operator=(OutputRedirect const&) = delete;
  9799. OutputRedirect(OutputRedirect&&) = delete;
  9800. OutputRedirect& operator=(OutputRedirect&&) = delete;
  9801. OutputRedirect(std::string& stdout_dest, std::string& stderr_dest);
  9802. ~OutputRedirect();
  9803. private:
  9804. int m_originalStdout = -1;
  9805. int m_originalStderr = -1;
  9806. TempFile m_stdoutFile;
  9807. TempFile m_stderrFile;
  9808. std::string& m_stdoutDest;
  9809. std::string& m_stderrDest;
  9810. };
  9811. #endif
  9812. } // end namespace Catch
  9813. #endif // TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  9814. // end catch_output_redirect.h
  9815. #include <cstdio>
  9816. #include <cstring>
  9817. #include <fstream>
  9818. #include <sstream>
  9819. #include <stdexcept>
  9820. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  9821. #if defined(_MSC_VER)
  9822. #include <io.h> //_dup and _dup2
  9823. #define dup _dup
  9824. #define dup2 _dup2
  9825. #define fileno _fileno
  9826. #else
  9827. #include <unistd.h> // dup and dup2
  9828. #endif
  9829. #endif
  9830. namespace Catch {
  9831. RedirectedStream::RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream )
  9832. : m_originalStream( originalStream ),
  9833. m_redirectionStream( redirectionStream ),
  9834. m_prevBuf( m_originalStream.rdbuf() )
  9835. {
  9836. m_originalStream.rdbuf( m_redirectionStream.rdbuf() );
  9837. }
  9838. RedirectedStream::~RedirectedStream() {
  9839. m_originalStream.rdbuf( m_prevBuf );
  9840. }
  9841. RedirectedStdOut::RedirectedStdOut() : m_cout( Catch::cout(), m_rss.get() ) {}
  9842. auto RedirectedStdOut::str() const -> std::string { return m_rss.str(); }
  9843. RedirectedStdErr::RedirectedStdErr()
  9844. : m_cerr( Catch::cerr(), m_rss.get() ),
  9845. m_clog( Catch::clog(), m_rss.get() )
  9846. {}
  9847. auto RedirectedStdErr::str() const -> std::string { return m_rss.str(); }
  9848. RedirectedStreams::RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr)
  9849. : m_redirectedCout(redirectedCout),
  9850. m_redirectedCerr(redirectedCerr)
  9851. {}
  9852. RedirectedStreams::~RedirectedStreams() {
  9853. m_redirectedCout += m_redirectedStdOut.str();
  9854. m_redirectedCerr += m_redirectedStdErr.str();
  9855. }
  9856. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  9857. #if defined(_MSC_VER)
  9858. TempFile::TempFile() {
  9859. if (tmpnam_s(m_buffer)) {
  9860. CATCH_RUNTIME_ERROR("Could not get a temp filename");
  9861. }
  9862. if (fopen_s(&m_file, m_buffer, "w+")) {
  9863. char buffer[100];
  9864. if (strerror_s(buffer, errno)) {
  9865. CATCH_RUNTIME_ERROR("Could not translate errno to a string");
  9866. }
  9867. CATCH_RUNTIME_ERROR("Could not open the temp file: '" << m_buffer << "' because: " << buffer);
  9868. }
  9869. }
  9870. #else
  9871. TempFile::TempFile() {
  9872. m_file = std::tmpfile();
  9873. if (!m_file) {
  9874. CATCH_RUNTIME_ERROR("Could not create a temp file.");
  9875. }
  9876. }
  9877. #endif
  9878. TempFile::~TempFile() {
  9879. // TBD: What to do about errors here?
  9880. std::fclose(m_file);
  9881. // We manually create the file on Windows only, on Linux
  9882. // it will be autodeleted
  9883. #if defined(_MSC_VER)
  9884. std::remove(m_buffer);
  9885. #endif
  9886. }
  9887. FILE* TempFile::getFile() {
  9888. return m_file;
  9889. }
  9890. std::string TempFile::getContents() {
  9891. std::stringstream sstr;
  9892. char buffer[100] = {};
  9893. std::rewind(m_file);
  9894. while (std::fgets(buffer, sizeof(buffer), m_file)) {
  9895. sstr << buffer;
  9896. }
  9897. return sstr.str();
  9898. }
  9899. OutputRedirect::OutputRedirect(std::string& stdout_dest, std::string& stderr_dest) :
  9900. m_originalStdout(dup(1)),
  9901. m_originalStderr(dup(2)),
  9902. m_stdoutDest(stdout_dest),
  9903. m_stderrDest(stderr_dest) {
  9904. dup2(fileno(m_stdoutFile.getFile()), 1);
  9905. dup2(fileno(m_stderrFile.getFile()), 2);
  9906. }
  9907. OutputRedirect::~OutputRedirect() {
  9908. Catch::cout() << std::flush;
  9909. fflush(stdout);
  9910. // Since we support overriding these streams, we flush cerr
  9911. // even though std::cerr is unbuffered
  9912. Catch::cerr() << std::flush;
  9913. Catch::clog() << std::flush;
  9914. fflush(stderr);
  9915. dup2(m_originalStdout, 1);
  9916. dup2(m_originalStderr, 2);
  9917. m_stdoutDest += m_stdoutFile.getContents();
  9918. m_stderrDest += m_stderrFile.getContents();
  9919. }
  9920. #endif // CATCH_CONFIG_NEW_CAPTURE
  9921. } // namespace Catch
  9922. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  9923. #if defined(_MSC_VER)
  9924. #undef dup
  9925. #undef dup2
  9926. #undef fileno
  9927. #endif
  9928. #endif
  9929. // end catch_output_redirect.cpp
  9930. // start catch_polyfills.cpp
  9931. #include <cmath>
  9932. namespace Catch {
  9933. #if !defined(CATCH_CONFIG_POLYFILL_ISNAN)
  9934. bool isnan(float f) {
  9935. return std::isnan(f);
  9936. }
  9937. bool isnan(double d) {
  9938. return std::isnan(d);
  9939. }
  9940. #else
  9941. // For now we only use this for embarcadero
  9942. bool isnan(float f) {
  9943. return std::_isnan(f);
  9944. }
  9945. bool isnan(double d) {
  9946. return std::_isnan(d);
  9947. }
  9948. #endif
  9949. } // end namespace Catch
  9950. // end catch_polyfills.cpp
  9951. // start catch_random_number_generator.cpp
  9952. namespace Catch {
  9953. namespace {
  9954. #if defined(_MSC_VER)
  9955. #pragma warning(push)
  9956. #pragma warning(disable:4146) // we negate uint32 during the rotate
  9957. #endif
  9958. // Safe rotr implementation thanks to John Regehr
  9959. uint32_t rotate_right(uint32_t val, uint32_t count) {
  9960. const uint32_t mask = 31;
  9961. count &= mask;
  9962. return (val >> count) | (val << (-count & mask));
  9963. }
  9964. #if defined(_MSC_VER)
  9965. #pragma warning(pop)
  9966. #endif
  9967. }
  9968. SimplePcg32::SimplePcg32(result_type seed_) {
  9969. seed(seed_);
  9970. }
  9971. void SimplePcg32::seed(result_type seed_) {
  9972. m_state = 0;
  9973. (*this)();
  9974. m_state += seed_;
  9975. (*this)();
  9976. }
  9977. void SimplePcg32::discard(uint64_t skip) {
  9978. // We could implement this to run in O(log n) steps, but this
  9979. // should suffice for our use case.
  9980. for (uint64_t s = 0; s < skip; ++s) {
  9981. static_cast<void>((*this)());
  9982. }
  9983. }
  9984. SimplePcg32::result_type SimplePcg32::operator()() {
  9985. // prepare the output value
  9986. const uint32_t xorshifted = static_cast<uint32_t>(((m_state >> 18u) ^ m_state) >> 27u);
  9987. const auto output = rotate_right(xorshifted, m_state >> 59u);
  9988. // advance state
  9989. m_state = m_state * 6364136223846793005ULL + s_inc;
  9990. return output;
  9991. }
  9992. bool operator==(SimplePcg32 const& lhs, SimplePcg32 const& rhs) {
  9993. return lhs.m_state == rhs.m_state;
  9994. }
  9995. bool operator!=(SimplePcg32 const& lhs, SimplePcg32 const& rhs) {
  9996. return lhs.m_state != rhs.m_state;
  9997. }
  9998. }
  9999. // end catch_random_number_generator.cpp
  10000. // start catch_registry_hub.cpp
  10001. // start catch_test_case_registry_impl.h
  10002. #include <vector>
  10003. #include <set>
  10004. #include <algorithm>
  10005. #include <ios>
  10006. namespace Catch {
  10007. class TestCase;
  10008. struct IConfig;
  10009. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases );
  10010. bool isThrowSafe( TestCase const& testCase, IConfig const& config );
  10011. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
  10012. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions );
  10013. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
  10014. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
  10015. class TestRegistry : public ITestCaseRegistry {
  10016. public:
  10017. virtual ~TestRegistry() = default;
  10018. virtual void registerTest( TestCase const& testCase );
  10019. std::vector<TestCase> const& getAllTests() const override;
  10020. std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const override;
  10021. private:
  10022. std::vector<TestCase> m_functions;
  10023. mutable RunTests::InWhatOrder m_currentSortOrder = RunTests::InDeclarationOrder;
  10024. mutable std::vector<TestCase> m_sortedFunctions;
  10025. std::size_t m_unnamedCount = 0;
  10026. std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised
  10027. };
  10028. ///////////////////////////////////////////////////////////////////////////
  10029. class TestInvokerAsFunction : public ITestInvoker {
  10030. void(*m_testAsFunction)();
  10031. public:
  10032. TestInvokerAsFunction( void(*testAsFunction)() ) noexcept;
  10033. void invoke() const override;
  10034. };
  10035. std::string extractClassName( StringRef const& classOrQualifiedMethodName );
  10036. ///////////////////////////////////////////////////////////////////////////
  10037. } // end namespace Catch
  10038. // end catch_test_case_registry_impl.h
  10039. // start catch_reporter_registry.h
  10040. #include <map>
  10041. namespace Catch {
  10042. class ReporterRegistry : public IReporterRegistry {
  10043. public:
  10044. ~ReporterRegistry() override;
  10045. IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const override;
  10046. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory );
  10047. void registerListener( IReporterFactoryPtr const& factory );
  10048. FactoryMap const& getFactories() const override;
  10049. Listeners const& getListeners() const override;
  10050. private:
  10051. FactoryMap m_factories;
  10052. Listeners m_listeners;
  10053. };
  10054. }
  10055. // end catch_reporter_registry.h
  10056. // start catch_tag_alias_registry.h
  10057. // start catch_tag_alias.h
  10058. #include <string>
  10059. namespace Catch {
  10060. struct TagAlias {
  10061. TagAlias(std::string const& _tag, SourceLineInfo _lineInfo);
  10062. std::string tag;
  10063. SourceLineInfo lineInfo;
  10064. };
  10065. } // end namespace Catch
  10066. // end catch_tag_alias.h
  10067. #include <map>
  10068. namespace Catch {
  10069. class TagAliasRegistry : public ITagAliasRegistry {
  10070. public:
  10071. ~TagAliasRegistry() override;
  10072. TagAlias const* find( std::string const& alias ) const override;
  10073. std::string expandAliases( std::string const& unexpandedTestSpec ) const override;
  10074. void add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo );
  10075. private:
  10076. std::map<std::string, TagAlias> m_registry;
  10077. };
  10078. } // end namespace Catch
  10079. // end catch_tag_alias_registry.h
  10080. // start catch_startup_exception_registry.h
  10081. #include <vector>
  10082. #include <exception>
  10083. namespace Catch {
  10084. class StartupExceptionRegistry {
  10085. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  10086. public:
  10087. void add(std::exception_ptr const& exception) noexcept;
  10088. std::vector<std::exception_ptr> const& getExceptions() const noexcept;
  10089. private:
  10090. std::vector<std::exception_ptr> m_exceptions;
  10091. #endif
  10092. };
  10093. } // end namespace Catch
  10094. // end catch_startup_exception_registry.h
  10095. // start catch_singletons.hpp
  10096. namespace Catch {
  10097. struct ISingleton {
  10098. virtual ~ISingleton();
  10099. };
  10100. void addSingleton( ISingleton* singleton );
  10101. void cleanupSingletons();
  10102. template<typename SingletonImplT, typename InterfaceT = SingletonImplT, typename MutableInterfaceT = InterfaceT>
  10103. class Singleton : SingletonImplT, public ISingleton {
  10104. static auto getInternal() -> Singleton* {
  10105. static Singleton* s_instance = nullptr;
  10106. if( !s_instance ) {
  10107. s_instance = new Singleton;
  10108. addSingleton( s_instance );
  10109. }
  10110. return s_instance;
  10111. }
  10112. public:
  10113. static auto get() -> InterfaceT const& {
  10114. return *getInternal();
  10115. }
  10116. static auto getMutable() -> MutableInterfaceT& {
  10117. return *getInternal();
  10118. }
  10119. };
  10120. } // namespace Catch
  10121. // end catch_singletons.hpp
  10122. namespace Catch {
  10123. namespace {
  10124. class RegistryHub : public IRegistryHub, public IMutableRegistryHub,
  10125. private NonCopyable {
  10126. public: // IRegistryHub
  10127. RegistryHub() = default;
  10128. IReporterRegistry const& getReporterRegistry() const override {
  10129. return m_reporterRegistry;
  10130. }
  10131. ITestCaseRegistry const& getTestCaseRegistry() const override {
  10132. return m_testCaseRegistry;
  10133. }
  10134. IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const override {
  10135. return m_exceptionTranslatorRegistry;
  10136. }
  10137. ITagAliasRegistry const& getTagAliasRegistry() const override {
  10138. return m_tagAliasRegistry;
  10139. }
  10140. StartupExceptionRegistry const& getStartupExceptionRegistry() const override {
  10141. return m_exceptionRegistry;
  10142. }
  10143. public: // IMutableRegistryHub
  10144. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) override {
  10145. m_reporterRegistry.registerReporter( name, factory );
  10146. }
  10147. void registerListener( IReporterFactoryPtr const& factory ) override {
  10148. m_reporterRegistry.registerListener( factory );
  10149. }
  10150. void registerTest( TestCase const& testInfo ) override {
  10151. m_testCaseRegistry.registerTest( testInfo );
  10152. }
  10153. void registerTranslator( const IExceptionTranslator* translator ) override {
  10154. m_exceptionTranslatorRegistry.registerTranslator( translator );
  10155. }
  10156. void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) override {
  10157. m_tagAliasRegistry.add( alias, tag, lineInfo );
  10158. }
  10159. void registerStartupException() noexcept override {
  10160. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  10161. m_exceptionRegistry.add(std::current_exception());
  10162. #else
  10163. CATCH_INTERNAL_ERROR("Attempted to register active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
  10164. #endif
  10165. }
  10166. IMutableEnumValuesRegistry& getMutableEnumValuesRegistry() override {
  10167. return m_enumValuesRegistry;
  10168. }
  10169. private:
  10170. TestRegistry m_testCaseRegistry;
  10171. ReporterRegistry m_reporterRegistry;
  10172. ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
  10173. TagAliasRegistry m_tagAliasRegistry;
  10174. StartupExceptionRegistry m_exceptionRegistry;
  10175. Detail::EnumValuesRegistry m_enumValuesRegistry;
  10176. };
  10177. }
  10178. using RegistryHubSingleton = Singleton<RegistryHub, IRegistryHub, IMutableRegistryHub>;
  10179. IRegistryHub const& getRegistryHub() {
  10180. return RegistryHubSingleton::get();
  10181. }
  10182. IMutableRegistryHub& getMutableRegistryHub() {
  10183. return RegistryHubSingleton::getMutable();
  10184. }
  10185. void cleanUp() {
  10186. cleanupSingletons();
  10187. cleanUpContext();
  10188. }
  10189. std::string translateActiveException() {
  10190. return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException();
  10191. }
  10192. } // end namespace Catch
  10193. // end catch_registry_hub.cpp
  10194. // start catch_reporter_registry.cpp
  10195. namespace Catch {
  10196. ReporterRegistry::~ReporterRegistry() = default;
  10197. IStreamingReporterPtr ReporterRegistry::create( std::string const& name, IConfigPtr const& config ) const {
  10198. auto it = m_factories.find( name );
  10199. if( it == m_factories.end() )
  10200. return nullptr;
  10201. return it->second->create( ReporterConfig( config ) );
  10202. }
  10203. void ReporterRegistry::registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) {
  10204. m_factories.emplace(name, factory);
  10205. }
  10206. void ReporterRegistry::registerListener( IReporterFactoryPtr const& factory ) {
  10207. m_listeners.push_back( factory );
  10208. }
  10209. IReporterRegistry::FactoryMap const& ReporterRegistry::getFactories() const {
  10210. return m_factories;
  10211. }
  10212. IReporterRegistry::Listeners const& ReporterRegistry::getListeners() const {
  10213. return m_listeners;
  10214. }
  10215. }
  10216. // end catch_reporter_registry.cpp
  10217. // start catch_result_type.cpp
  10218. namespace Catch {
  10219. bool isOk( ResultWas::OfType resultType ) {
  10220. return ( resultType & ResultWas::FailureBit ) == 0;
  10221. }
  10222. bool isJustInfo( int flags ) {
  10223. return flags == ResultWas::Info;
  10224. }
  10225. ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) {
  10226. return static_cast<ResultDisposition::Flags>( static_cast<int>( lhs ) | static_cast<int>( rhs ) );
  10227. }
  10228. bool shouldContinueOnFailure( int flags ) { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; }
  10229. bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; }
  10230. } // end namespace Catch
  10231. // end catch_result_type.cpp
  10232. // start catch_run_context.cpp
  10233. #include <cassert>
  10234. #include <algorithm>
  10235. #include <sstream>
  10236. namespace Catch {
  10237. namespace Generators {
  10238. struct GeneratorTracker : TestCaseTracking::TrackerBase, IGeneratorTracker {
  10239. GeneratorBasePtr m_generator;
  10240. GeneratorTracker( TestCaseTracking::NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  10241. : TrackerBase( nameAndLocation, ctx, parent )
  10242. {}
  10243. ~GeneratorTracker();
  10244. static GeneratorTracker& acquire( TrackerContext& ctx, TestCaseTracking::NameAndLocation const& nameAndLocation ) {
  10245. std::shared_ptr<GeneratorTracker> tracker;
  10246. ITracker& currentTracker = ctx.currentTracker();
  10247. // Under specific circumstances, the generator we want
  10248. // to acquire is also the current tracker. If this is
  10249. // the case, we have to avoid looking through current
  10250. // tracker's children, and instead return the current
  10251. // tracker.
  10252. // A case where this check is important is e.g.
  10253. // for (int i = 0; i < 5; ++i) {
  10254. // int n = GENERATE(1, 2);
  10255. // }
  10256. //
  10257. // without it, the code above creates 5 nested generators.
  10258. if (currentTracker.nameAndLocation() == nameAndLocation) {
  10259. auto thisTracker = currentTracker.parent().findChild(nameAndLocation);
  10260. assert(thisTracker);
  10261. assert(thisTracker->isGeneratorTracker());
  10262. tracker = std::static_pointer_cast<GeneratorTracker>(thisTracker);
  10263. } else if ( TestCaseTracking::ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  10264. assert( childTracker );
  10265. assert( childTracker->isGeneratorTracker() );
  10266. tracker = std::static_pointer_cast<GeneratorTracker>( childTracker );
  10267. } else {
  10268. tracker = std::make_shared<GeneratorTracker>( nameAndLocation, ctx, &currentTracker );
  10269. currentTracker.addChild( tracker );
  10270. }
  10271. if( !tracker->isComplete() ) {
  10272. tracker->open();
  10273. }
  10274. return *tracker;
  10275. }
  10276. // TrackerBase interface
  10277. bool isGeneratorTracker() const override { return true; }
  10278. auto hasGenerator() const -> bool override {
  10279. return !!m_generator;
  10280. }
  10281. void close() override {
  10282. TrackerBase::close();
  10283. // If a generator has a child (it is followed by a section)
  10284. // and none of its children have started, then we must wait
  10285. // until later to start consuming its values.
  10286. // This catches cases where `GENERATE` is placed between two
  10287. // `SECTION`s.
  10288. // **The check for m_children.empty cannot be removed**.
  10289. // doing so would break `GENERATE` _not_ followed by `SECTION`s.
  10290. const bool should_wait_for_child = [&]() {
  10291. // No children -> nobody to wait for
  10292. if ( m_children.empty() ) {
  10293. return false;
  10294. }
  10295. // If at least one child started executing, don't wait
  10296. if ( std::find_if(
  10297. m_children.begin(),
  10298. m_children.end(),
  10299. []( TestCaseTracking::ITrackerPtr tracker ) {
  10300. return tracker->hasStarted();
  10301. } ) != m_children.end() ) {
  10302. return false;
  10303. }
  10304. // No children have started. We need to check if they _can_
  10305. // start, and thus we should wait for them, or they cannot
  10306. // start (due to filters), and we shouldn't wait for them
  10307. auto* parent = m_parent;
  10308. // This is safe: there is always at least one section
  10309. // tracker in a test case tracking tree
  10310. while ( !parent->isSectionTracker() ) {
  10311. parent = &( parent->parent() );
  10312. }
  10313. assert( parent &&
  10314. "Missing root (test case) level section" );
  10315. auto const& parentSection =
  10316. static_cast<SectionTracker&>( *parent );
  10317. auto const& filters = parentSection.getFilters();
  10318. // No filters -> no restrictions on running sections
  10319. if ( filters.empty() ) {
  10320. return true;
  10321. }
  10322. for ( auto const& child : m_children ) {
  10323. if ( child->isSectionTracker() &&
  10324. std::find( filters.begin(),
  10325. filters.end(),
  10326. static_cast<SectionTracker&>( *child )
  10327. .trimmedName() ) !=
  10328. filters.end() ) {
  10329. return true;
  10330. }
  10331. }
  10332. return false;
  10333. }();
  10334. // This check is a bit tricky, because m_generator->next()
  10335. // has a side-effect, where it consumes generator's current
  10336. // value, but we do not want to invoke the side-effect if
  10337. // this generator is still waiting for any child to start.
  10338. if ( should_wait_for_child ||
  10339. ( m_runState == CompletedSuccessfully &&
  10340. m_generator->next() ) ) {
  10341. m_children.clear();
  10342. m_runState = Executing;
  10343. }
  10344. }
  10345. // IGeneratorTracker interface
  10346. auto getGenerator() const -> GeneratorBasePtr const& override {
  10347. return m_generator;
  10348. }
  10349. void setGenerator( GeneratorBasePtr&& generator ) override {
  10350. m_generator = std::move( generator );
  10351. }
  10352. };
  10353. GeneratorTracker::~GeneratorTracker() {}
  10354. }
  10355. RunContext::RunContext(IConfigPtr const& _config, IStreamingReporterPtr&& reporter)
  10356. : m_runInfo(_config->name()),
  10357. m_context(getCurrentMutableContext()),
  10358. m_config(_config),
  10359. m_reporter(std::move(reporter)),
  10360. m_lastAssertionInfo{ StringRef(), SourceLineInfo("",0), StringRef(), ResultDisposition::Normal },
  10361. m_includeSuccessfulResults( m_config->includeSuccessfulResults() || m_reporter->getPreferences().shouldReportAllAssertions )
  10362. {
  10363. m_context.setRunner(this);
  10364. m_context.setConfig(m_config);
  10365. m_context.setResultCapture(this);
  10366. m_reporter->testRunStarting(m_runInfo);
  10367. }
  10368. RunContext::~RunContext() {
  10369. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting()));
  10370. }
  10371. void RunContext::testGroupStarting(std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount) {
  10372. m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount));
  10373. }
  10374. void RunContext::testGroupEnded(std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount) {
  10375. m_reporter->testGroupEnded(TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting()));
  10376. }
  10377. Totals RunContext::runTest(TestCase const& testCase) {
  10378. Totals prevTotals = m_totals;
  10379. std::string redirectedCout;
  10380. std::string redirectedCerr;
  10381. auto const& testInfo = testCase.getTestCaseInfo();
  10382. m_reporter->testCaseStarting(testInfo);
  10383. m_activeTestCase = &testCase;
  10384. ITracker& rootTracker = m_trackerContext.startRun();
  10385. assert(rootTracker.isSectionTracker());
  10386. static_cast<SectionTracker&>(rootTracker).addInitialFilters(m_config->getSectionsToRun());
  10387. do {
  10388. m_trackerContext.startCycle();
  10389. m_testCaseTracker = &SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo));
  10390. runCurrentTest(redirectedCout, redirectedCerr);
  10391. } while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting());
  10392. Totals deltaTotals = m_totals.delta(prevTotals);
  10393. if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) {
  10394. deltaTotals.assertions.failed++;
  10395. deltaTotals.testCases.passed--;
  10396. deltaTotals.testCases.failed++;
  10397. }
  10398. m_totals.testCases += deltaTotals.testCases;
  10399. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  10400. deltaTotals,
  10401. redirectedCout,
  10402. redirectedCerr,
  10403. aborting()));
  10404. m_activeTestCase = nullptr;
  10405. m_testCaseTracker = nullptr;
  10406. return deltaTotals;
  10407. }
  10408. IConfigPtr RunContext::config() const {
  10409. return m_config;
  10410. }
  10411. IStreamingReporter& RunContext::reporter() const {
  10412. return *m_reporter;
  10413. }
  10414. void RunContext::assertionEnded(AssertionResult const & result) {
  10415. if (result.getResultType() == ResultWas::Ok) {
  10416. m_totals.assertions.passed++;
  10417. m_lastAssertionPassed = true;
  10418. } else if (!result.isOk()) {
  10419. m_lastAssertionPassed = false;
  10420. if( m_activeTestCase->getTestCaseInfo().okToFail() )
  10421. m_totals.assertions.failedButOk++;
  10422. else
  10423. m_totals.assertions.failed++;
  10424. }
  10425. else {
  10426. m_lastAssertionPassed = true;
  10427. }
  10428. // We have no use for the return value (whether messages should be cleared), because messages were made scoped
  10429. // and should be let to clear themselves out.
  10430. static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals)));
  10431. if (result.getResultType() != ResultWas::Warning)
  10432. m_messageScopes.clear();
  10433. // Reset working state
  10434. resetAssertionInfo();
  10435. m_lastResult = result;
  10436. }
  10437. void RunContext::resetAssertionInfo() {
  10438. m_lastAssertionInfo.macroName = StringRef();
  10439. m_lastAssertionInfo.capturedExpression = "{Unknown expression after the reported line}"_sr;
  10440. }
  10441. bool RunContext::sectionStarted(SectionInfo const & sectionInfo, Counts & assertions) {
  10442. ITracker& sectionTracker = SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(sectionInfo.name, sectionInfo.lineInfo));
  10443. if (!sectionTracker.isOpen())
  10444. return false;
  10445. m_activeSections.push_back(&sectionTracker);
  10446. m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;
  10447. m_reporter->sectionStarting(sectionInfo);
  10448. assertions = m_totals.assertions;
  10449. return true;
  10450. }
  10451. auto RunContext::acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
  10452. using namespace Generators;
  10453. GeneratorTracker& tracker = GeneratorTracker::acquire(m_trackerContext,
  10454. TestCaseTracking::NameAndLocation( static_cast<std::string>(generatorName), lineInfo ) );
  10455. m_lastAssertionInfo.lineInfo = lineInfo;
  10456. return tracker;
  10457. }
  10458. bool RunContext::testForMissingAssertions(Counts& assertions) {
  10459. if (assertions.total() != 0)
  10460. return false;
  10461. if (!m_config->warnAboutMissingAssertions())
  10462. return false;
  10463. if (m_trackerContext.currentTracker().hasChildren())
  10464. return false;
  10465. m_totals.assertions.failed++;
  10466. assertions.failed++;
  10467. return true;
  10468. }
  10469. void RunContext::sectionEnded(SectionEndInfo const & endInfo) {
  10470. Counts assertions = m_totals.assertions - endInfo.prevAssertions;
  10471. bool missingAssertions = testForMissingAssertions(assertions);
  10472. if (!m_activeSections.empty()) {
  10473. m_activeSections.back()->close();
  10474. m_activeSections.pop_back();
  10475. }
  10476. m_reporter->sectionEnded(SectionStats(endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions));
  10477. m_messages.clear();
  10478. m_messageScopes.clear();
  10479. }
  10480. void RunContext::sectionEndedEarly(SectionEndInfo const & endInfo) {
  10481. if (m_unfinishedSections.empty())
  10482. m_activeSections.back()->fail();
  10483. else
  10484. m_activeSections.back()->close();
  10485. m_activeSections.pop_back();
  10486. m_unfinishedSections.push_back(endInfo);
  10487. }
  10488. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  10489. void RunContext::benchmarkPreparing(std::string const& name) {
  10490. m_reporter->benchmarkPreparing(name);
  10491. }
  10492. void RunContext::benchmarkStarting( BenchmarkInfo const& info ) {
  10493. m_reporter->benchmarkStarting( info );
  10494. }
  10495. void RunContext::benchmarkEnded( BenchmarkStats<> const& stats ) {
  10496. m_reporter->benchmarkEnded( stats );
  10497. }
  10498. void RunContext::benchmarkFailed(std::string const & error) {
  10499. m_reporter->benchmarkFailed(error);
  10500. }
  10501. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  10502. void RunContext::pushScopedMessage(MessageInfo const & message) {
  10503. m_messages.push_back(message);
  10504. }
  10505. void RunContext::popScopedMessage(MessageInfo const & message) {
  10506. m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end());
  10507. }
  10508. void RunContext::emplaceUnscopedMessage( MessageBuilder const& builder ) {
  10509. m_messageScopes.emplace_back( builder );
  10510. }
  10511. std::string RunContext::getCurrentTestName() const {
  10512. return m_activeTestCase
  10513. ? m_activeTestCase->getTestCaseInfo().name
  10514. : std::string();
  10515. }
  10516. const AssertionResult * RunContext::getLastResult() const {
  10517. return &(*m_lastResult);
  10518. }
  10519. void RunContext::exceptionEarlyReported() {
  10520. m_shouldReportUnexpected = false;
  10521. }
  10522. void RunContext::handleFatalErrorCondition( StringRef message ) {
  10523. // First notify reporter that bad things happened
  10524. m_reporter->fatalErrorEncountered(message);
  10525. // Don't rebuild the result -- the stringification itself can cause more fatal errors
  10526. // Instead, fake a result data.
  10527. AssertionResultData tempResult( ResultWas::FatalErrorCondition, { false } );
  10528. tempResult.message = static_cast<std::string>(message);
  10529. AssertionResult result(m_lastAssertionInfo, tempResult);
  10530. assertionEnded(result);
  10531. handleUnfinishedSections();
  10532. // Recreate section for test case (as we will lose the one that was in scope)
  10533. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  10534. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
  10535. Counts assertions;
  10536. assertions.failed = 1;
  10537. SectionStats testCaseSectionStats(testCaseSection, assertions, 0, false);
  10538. m_reporter->sectionEnded(testCaseSectionStats);
  10539. auto const& testInfo = m_activeTestCase->getTestCaseInfo();
  10540. Totals deltaTotals;
  10541. deltaTotals.testCases.failed = 1;
  10542. deltaTotals.assertions.failed = 1;
  10543. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  10544. deltaTotals,
  10545. std::string(),
  10546. std::string(),
  10547. false));
  10548. m_totals.testCases.failed++;
  10549. testGroupEnded(std::string(), m_totals, 1, 1);
  10550. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, false));
  10551. }
  10552. bool RunContext::lastAssertionPassed() {
  10553. return m_lastAssertionPassed;
  10554. }
  10555. void RunContext::assertionPassed() {
  10556. m_lastAssertionPassed = true;
  10557. ++m_totals.assertions.passed;
  10558. resetAssertionInfo();
  10559. m_messageScopes.clear();
  10560. }
  10561. bool RunContext::aborting() const {
  10562. return m_totals.assertions.failed >= static_cast<std::size_t>(m_config->abortAfter());
  10563. }
  10564. void RunContext::runCurrentTest(std::string & redirectedCout, std::string & redirectedCerr) {
  10565. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  10566. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
  10567. m_reporter->sectionStarting(testCaseSection);
  10568. Counts prevAssertions = m_totals.assertions;
  10569. double duration = 0;
  10570. m_shouldReportUnexpected = true;
  10571. m_lastAssertionInfo = { "TEST_CASE"_sr, testCaseInfo.lineInfo, StringRef(), ResultDisposition::Normal };
  10572. seedRng(*m_config);
  10573. Timer timer;
  10574. CATCH_TRY {
  10575. if (m_reporter->getPreferences().shouldRedirectStdOut) {
  10576. #if !defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
  10577. RedirectedStreams redirectedStreams(redirectedCout, redirectedCerr);
  10578. timer.start();
  10579. invokeActiveTestCase();
  10580. #else
  10581. OutputRedirect r(redirectedCout, redirectedCerr);
  10582. timer.start();
  10583. invokeActiveTestCase();
  10584. #endif
  10585. } else {
  10586. timer.start();
  10587. invokeActiveTestCase();
  10588. }
  10589. duration = timer.getElapsedSeconds();
  10590. } CATCH_CATCH_ANON (TestFailureException&) {
  10591. // This just means the test was aborted due to failure
  10592. } CATCH_CATCH_ALL {
  10593. // Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under REQUIRE assertions
  10594. // are reported without translation at the point of origin.
  10595. if( m_shouldReportUnexpected ) {
  10596. AssertionReaction dummyReaction;
  10597. handleUnexpectedInflightException( m_lastAssertionInfo, translateActiveException(), dummyReaction );
  10598. }
  10599. }
  10600. Counts assertions = m_totals.assertions - prevAssertions;
  10601. bool missingAssertions = testForMissingAssertions(assertions);
  10602. m_testCaseTracker->close();
  10603. handleUnfinishedSections();
  10604. m_messages.clear();
  10605. m_messageScopes.clear();
  10606. SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions);
  10607. m_reporter->sectionEnded(testCaseSectionStats);
  10608. }
  10609. void RunContext::invokeActiveTestCase() {
  10610. FatalConditionHandlerGuard _(&m_fatalConditionhandler);
  10611. m_activeTestCase->invoke();
  10612. }
  10613. void RunContext::handleUnfinishedSections() {
  10614. // If sections ended prematurely due to an exception we stored their
  10615. // infos here so we can tear them down outside the unwind process.
  10616. for (auto it = m_unfinishedSections.rbegin(),
  10617. itEnd = m_unfinishedSections.rend();
  10618. it != itEnd;
  10619. ++it)
  10620. sectionEnded(*it);
  10621. m_unfinishedSections.clear();
  10622. }
  10623. void RunContext::handleExpr(
  10624. AssertionInfo const& info,
  10625. ITransientExpression const& expr,
  10626. AssertionReaction& reaction
  10627. ) {
  10628. m_reporter->assertionStarting( info );
  10629. bool negated = isFalseTest( info.resultDisposition );
  10630. bool result = expr.getResult() != negated;
  10631. if( result ) {
  10632. if (!m_includeSuccessfulResults) {
  10633. assertionPassed();
  10634. }
  10635. else {
  10636. reportExpr(info, ResultWas::Ok, &expr, negated);
  10637. }
  10638. }
  10639. else {
  10640. reportExpr(info, ResultWas::ExpressionFailed, &expr, negated );
  10641. populateReaction( reaction );
  10642. }
  10643. }
  10644. void RunContext::reportExpr(
  10645. AssertionInfo const &info,
  10646. ResultWas::OfType resultType,
  10647. ITransientExpression const *expr,
  10648. bool negated ) {
  10649. m_lastAssertionInfo = info;
  10650. AssertionResultData data( resultType, LazyExpression( negated ) );
  10651. AssertionResult assertionResult{ info, data };
  10652. assertionResult.m_resultData.lazyExpression.m_transientExpression = expr;
  10653. assertionEnded( assertionResult );
  10654. }
  10655. void RunContext::handleMessage(
  10656. AssertionInfo const& info,
  10657. ResultWas::OfType resultType,
  10658. StringRef const& message,
  10659. AssertionReaction& reaction
  10660. ) {
  10661. m_reporter->assertionStarting( info );
  10662. m_lastAssertionInfo = info;
  10663. AssertionResultData data( resultType, LazyExpression( false ) );
  10664. data.message = static_cast<std::string>(message);
  10665. AssertionResult assertionResult{ m_lastAssertionInfo, data };
  10666. assertionEnded( assertionResult );
  10667. if( !assertionResult.isOk() )
  10668. populateReaction( reaction );
  10669. }
  10670. void RunContext::handleUnexpectedExceptionNotThrown(
  10671. AssertionInfo const& info,
  10672. AssertionReaction& reaction
  10673. ) {
  10674. handleNonExpr(info, Catch::ResultWas::DidntThrowException, reaction);
  10675. }
  10676. void RunContext::handleUnexpectedInflightException(
  10677. AssertionInfo const& info,
  10678. std::string const& message,
  10679. AssertionReaction& reaction
  10680. ) {
  10681. m_lastAssertionInfo = info;
  10682. AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
  10683. data.message = message;
  10684. AssertionResult assertionResult{ info, data };
  10685. assertionEnded( assertionResult );
  10686. populateReaction( reaction );
  10687. }
  10688. void RunContext::populateReaction( AssertionReaction& reaction ) {
  10689. reaction.shouldDebugBreak = m_config->shouldDebugBreak();
  10690. reaction.shouldThrow = aborting() || (m_lastAssertionInfo.resultDisposition & ResultDisposition::Normal);
  10691. }
  10692. void RunContext::handleIncomplete(
  10693. AssertionInfo const& info
  10694. ) {
  10695. m_lastAssertionInfo = info;
  10696. AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
  10697. data.message = "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE";
  10698. AssertionResult assertionResult{ info, data };
  10699. assertionEnded( assertionResult );
  10700. }
  10701. void RunContext::handleNonExpr(
  10702. AssertionInfo const &info,
  10703. ResultWas::OfType resultType,
  10704. AssertionReaction &reaction
  10705. ) {
  10706. m_lastAssertionInfo = info;
  10707. AssertionResultData data( resultType, LazyExpression( false ) );
  10708. AssertionResult assertionResult{ info, data };
  10709. assertionEnded( assertionResult );
  10710. if( !assertionResult.isOk() )
  10711. populateReaction( reaction );
  10712. }
  10713. IResultCapture& getResultCapture() {
  10714. if (auto* capture = getCurrentContext().getResultCapture())
  10715. return *capture;
  10716. else
  10717. CATCH_INTERNAL_ERROR("No result capture instance");
  10718. }
  10719. void seedRng(IConfig const& config) {
  10720. if (config.rngSeed() != 0) {
  10721. std::srand(config.rngSeed());
  10722. rng().seed(config.rngSeed());
  10723. }
  10724. }
  10725. unsigned int rngSeed() {
  10726. return getCurrentContext().getConfig()->rngSeed();
  10727. }
  10728. }
  10729. // end catch_run_context.cpp
  10730. // start catch_section.cpp
  10731. namespace Catch {
  10732. Section::Section( SectionInfo const& info )
  10733. : m_info( info ),
  10734. m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) )
  10735. {
  10736. m_timer.start();
  10737. }
  10738. Section::~Section() {
  10739. if( m_sectionIncluded ) {
  10740. SectionEndInfo endInfo{ m_info, m_assertions, m_timer.getElapsedSeconds() };
  10741. if( uncaught_exceptions() )
  10742. getResultCapture().sectionEndedEarly( endInfo );
  10743. else
  10744. getResultCapture().sectionEnded( endInfo );
  10745. }
  10746. }
  10747. // This indicates whether the section should be executed or not
  10748. Section::operator bool() const {
  10749. return m_sectionIncluded;
  10750. }
  10751. } // end namespace Catch
  10752. // end catch_section.cpp
  10753. // start catch_section_info.cpp
  10754. namespace Catch {
  10755. SectionInfo::SectionInfo
  10756. ( SourceLineInfo const& _lineInfo,
  10757. std::string const& _name )
  10758. : name( _name ),
  10759. lineInfo( _lineInfo )
  10760. {}
  10761. } // end namespace Catch
  10762. // end catch_section_info.cpp
  10763. // start catch_session.cpp
  10764. // start catch_session.h
  10765. #include <memory>
  10766. namespace Catch {
  10767. class Session : NonCopyable {
  10768. public:
  10769. Session();
  10770. ~Session() override;
  10771. void showHelp() const;
  10772. void libIdentify();
  10773. int applyCommandLine( int argc, char const * const * argv );
  10774. #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)
  10775. int applyCommandLine( int argc, wchar_t const * const * argv );
  10776. #endif
  10777. void useConfigData( ConfigData const& configData );
  10778. template<typename CharT>
  10779. int run(int argc, CharT const * const argv[]) {
  10780. if (m_startupExceptions)
  10781. return 1;
  10782. int returnCode = applyCommandLine(argc, argv);
  10783. if (returnCode == 0)
  10784. returnCode = run();
  10785. return returnCode;
  10786. }
  10787. int run();
  10788. clara::Parser const& cli() const;
  10789. void cli( clara::Parser const& newParser );
  10790. ConfigData& configData();
  10791. Config& config();
  10792. private:
  10793. int runInternal();
  10794. clara::Parser m_cli;
  10795. ConfigData m_configData;
  10796. std::shared_ptr<Config> m_config;
  10797. bool m_startupExceptions = false;
  10798. };
  10799. } // end namespace Catch
  10800. // end catch_session.h
  10801. // start catch_version.h
  10802. #include <iosfwd>
  10803. namespace Catch {
  10804. // Versioning information
  10805. struct Version {
  10806. Version( Version const& ) = delete;
  10807. Version& operator=( Version const& ) = delete;
  10808. Version( unsigned int _majorVersion,
  10809. unsigned int _minorVersion,
  10810. unsigned int _patchNumber,
  10811. char const * const _branchName,
  10812. unsigned int _buildNumber );
  10813. unsigned int const majorVersion;
  10814. unsigned int const minorVersion;
  10815. unsigned int const patchNumber;
  10816. // buildNumber is only used if branchName is not null
  10817. char const * const branchName;
  10818. unsigned int const buildNumber;
  10819. friend std::ostream& operator << ( std::ostream& os, Version const& version );
  10820. };
  10821. Version const& libraryVersion();
  10822. }
  10823. // end catch_version.h
  10824. #include <cstdlib>
  10825. #include <iomanip>
  10826. #include <set>
  10827. #include <iterator>
  10828. namespace Catch {
  10829. namespace {
  10830. const int MaxExitCode = 255;
  10831. IStreamingReporterPtr createReporter(std::string const& reporterName, IConfigPtr const& config) {
  10832. auto reporter = Catch::getRegistryHub().getReporterRegistry().create(reporterName, config);
  10833. CATCH_ENFORCE(reporter, "No reporter registered with name: '" << reporterName << "'");
  10834. return reporter;
  10835. }
  10836. IStreamingReporterPtr makeReporter(std::shared_ptr<Config> const& config) {
  10837. if (Catch::getRegistryHub().getReporterRegistry().getListeners().empty()) {
  10838. return createReporter(config->getReporterName(), config);
  10839. }
  10840. // On older platforms, returning std::unique_ptr<ListeningReporter>
  10841. // when the return type is std::unique_ptr<IStreamingReporter>
  10842. // doesn't compile without a std::move call. However, this causes
  10843. // a warning on newer platforms. Thus, we have to work around
  10844. // it a bit and downcast the pointer manually.
  10845. auto ret = std::unique_ptr<IStreamingReporter>(new ListeningReporter);
  10846. auto& multi = static_cast<ListeningReporter&>(*ret);
  10847. auto const& listeners = Catch::getRegistryHub().getReporterRegistry().getListeners();
  10848. for (auto const& listener : listeners) {
  10849. multi.addListener(listener->create(Catch::ReporterConfig(config)));
  10850. }
  10851. multi.addReporter(createReporter(config->getReporterName(), config));
  10852. return ret;
  10853. }
  10854. class TestGroup {
  10855. public:
  10856. explicit TestGroup(std::shared_ptr<Config> const& config)
  10857. : m_config{config}
  10858. , m_context{config, makeReporter(config)}
  10859. {
  10860. auto const& allTestCases = getAllTestCasesSorted(*m_config);
  10861. m_matches = m_config->testSpec().matchesByFilter(allTestCases, *m_config);
  10862. auto const& invalidArgs = m_config->testSpec().getInvalidArgs();
  10863. if (m_matches.empty() && invalidArgs.empty()) {
  10864. for (auto const& test : allTestCases)
  10865. if (!test.isHidden())
  10866. m_tests.emplace(&test);
  10867. } else {
  10868. for (auto const& match : m_matches)
  10869. m_tests.insert(match.tests.begin(), match.tests.end());
  10870. }
  10871. }
  10872. Totals execute() {
  10873. auto const& invalidArgs = m_config->testSpec().getInvalidArgs();
  10874. Totals totals;
  10875. m_context.testGroupStarting(m_config->name(), 1, 1);
  10876. for (auto const& testCase : m_tests) {
  10877. if (!m_context.aborting())
  10878. totals += m_context.runTest(*testCase);
  10879. else
  10880. m_context.reporter().skipTest(*testCase);
  10881. }
  10882. for (auto const& match : m_matches) {
  10883. if (match.tests.empty()) {
  10884. m_context.reporter().noMatchingTestCases(match.name);
  10885. totals.error = -1;
  10886. }
  10887. }
  10888. if (!invalidArgs.empty()) {
  10889. for (auto const& invalidArg: invalidArgs)
  10890. m_context.reporter().reportInvalidArguments(invalidArg);
  10891. }
  10892. m_context.testGroupEnded(m_config->name(), totals, 1, 1);
  10893. return totals;
  10894. }
  10895. private:
  10896. using Tests = std::set<TestCase const*>;
  10897. std::shared_ptr<Config> m_config;
  10898. RunContext m_context;
  10899. Tests m_tests;
  10900. TestSpec::Matches m_matches;
  10901. };
  10902. void applyFilenamesAsTags(Catch::IConfig const& config) {
  10903. auto& tests = const_cast<std::vector<TestCase>&>(getAllTestCasesSorted(config));
  10904. for (auto& testCase : tests) {
  10905. auto tags = testCase.tags;
  10906. std::string filename = testCase.lineInfo.file;
  10907. auto lastSlash = filename.find_last_of("\\/");
  10908. if (lastSlash != std::string::npos) {
  10909. filename.erase(0, lastSlash);
  10910. filename[0] = '#';
  10911. }
  10912. auto lastDot = filename.find_last_of('.');
  10913. if (lastDot != std::string::npos) {
  10914. filename.erase(lastDot);
  10915. }
  10916. tags.push_back(std::move(filename));
  10917. setTags(testCase, tags);
  10918. }
  10919. }
  10920. } // anon namespace
  10921. Session::Session() {
  10922. static bool alreadyInstantiated = false;
  10923. if( alreadyInstantiated ) {
  10924. CATCH_TRY { CATCH_INTERNAL_ERROR( "Only one instance of Catch::Session can ever be used" ); }
  10925. CATCH_CATCH_ALL { getMutableRegistryHub().registerStartupException(); }
  10926. }
  10927. // There cannot be exceptions at startup in no-exception mode.
  10928. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  10929. const auto& exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions();
  10930. if ( !exceptions.empty() ) {
  10931. config();
  10932. getCurrentMutableContext().setConfig(m_config);
  10933. m_startupExceptions = true;
  10934. Colour colourGuard( Colour::Red );
  10935. Catch::cerr() << "Errors occurred during startup!" << '\n';
  10936. // iterate over all exceptions and notify user
  10937. for ( const auto& ex_ptr : exceptions ) {
  10938. try {
  10939. std::rethrow_exception(ex_ptr);
  10940. } catch ( std::exception const& ex ) {
  10941. Catch::cerr() << Column( ex.what() ).indent(2) << '\n';
  10942. }
  10943. }
  10944. }
  10945. #endif
  10946. alreadyInstantiated = true;
  10947. m_cli = makeCommandLineParser( m_configData );
  10948. }
  10949. Session::~Session() {
  10950. Catch::cleanUp();
  10951. }
  10952. void Session::showHelp() const {
  10953. Catch::cout()
  10954. << "\nCatch v" << libraryVersion() << "\n"
  10955. << m_cli << std::endl
  10956. << "For more detailed usage please see the project docs\n" << std::endl;
  10957. }
  10958. void Session::libIdentify() {
  10959. Catch::cout()
  10960. << std::left << std::setw(16) << "description: " << "A Catch2 test executable\n"
  10961. << std::left << std::setw(16) << "category: " << "testframework\n"
  10962. << std::left << std::setw(16) << "framework: " << "Catch Test\n"
  10963. << std::left << std::setw(16) << "version: " << libraryVersion() << std::endl;
  10964. }
  10965. int Session::applyCommandLine( int argc, char const * const * argv ) {
  10966. if( m_startupExceptions )
  10967. return 1;
  10968. auto result = m_cli.parse( clara::Args( argc, argv ) );
  10969. if( !result ) {
  10970. config();
  10971. getCurrentMutableContext().setConfig(m_config);
  10972. Catch::cerr()
  10973. << Colour( Colour::Red )
  10974. << "\nError(s) in input:\n"
  10975. << Column( result.errorMessage() ).indent( 2 )
  10976. << "\n\n";
  10977. Catch::cerr() << "Run with -? for usage\n" << std::endl;
  10978. return MaxExitCode;
  10979. }
  10980. if( m_configData.showHelp )
  10981. showHelp();
  10982. if( m_configData.libIdentify )
  10983. libIdentify();
  10984. m_config.reset();
  10985. return 0;
  10986. }
  10987. #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)
  10988. int Session::applyCommandLine( int argc, wchar_t const * const * argv ) {
  10989. char **utf8Argv = new char *[ argc ];
  10990. for ( int i = 0; i < argc; ++i ) {
  10991. int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, nullptr, 0, nullptr, nullptr );
  10992. utf8Argv[ i ] = new char[ bufSize ];
  10993. WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, nullptr, nullptr );
  10994. }
  10995. int returnCode = applyCommandLine( argc, utf8Argv );
  10996. for ( int i = 0; i < argc; ++i )
  10997. delete [] utf8Argv[ i ];
  10998. delete [] utf8Argv;
  10999. return returnCode;
  11000. }
  11001. #endif
  11002. void Session::useConfigData( ConfigData const& configData ) {
  11003. m_configData = configData;
  11004. m_config.reset();
  11005. }
  11006. int Session::run() {
  11007. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeStart ) != 0 ) {
  11008. Catch::cout() << "...waiting for enter/ return before starting" << std::endl;
  11009. static_cast<void>(std::getchar());
  11010. }
  11011. int exitCode = runInternal();
  11012. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeExit ) != 0 ) {
  11013. Catch::cout() << "...waiting for enter/ return before exiting, with code: " << exitCode << std::endl;
  11014. static_cast<void>(std::getchar());
  11015. }
  11016. return exitCode;
  11017. }
  11018. clara::Parser const& Session::cli() const {
  11019. return m_cli;
  11020. }
  11021. void Session::cli( clara::Parser const& newParser ) {
  11022. m_cli = newParser;
  11023. }
  11024. ConfigData& Session::configData() {
  11025. return m_configData;
  11026. }
  11027. Config& Session::config() {
  11028. if( !m_config )
  11029. m_config = std::make_shared<Config>( m_configData );
  11030. return *m_config;
  11031. }
  11032. int Session::runInternal() {
  11033. if( m_startupExceptions )
  11034. return 1;
  11035. if (m_configData.showHelp || m_configData.libIdentify) {
  11036. return 0;
  11037. }
  11038. CATCH_TRY {
  11039. config(); // Force config to be constructed
  11040. seedRng( *m_config );
  11041. if( m_configData.filenamesAsTags )
  11042. applyFilenamesAsTags( *m_config );
  11043. // Handle list request
  11044. if( Option<std::size_t> listed = list( m_config ) )
  11045. return static_cast<int>( *listed );
  11046. TestGroup tests { m_config };
  11047. auto const totals = tests.execute();
  11048. if( m_config->warnAboutNoTests() && totals.error == -1 )
  11049. return 2;
  11050. // Note that on unices only the lower 8 bits are usually used, clamping
  11051. // the return value to 255 prevents false negative when some multiple
  11052. // of 256 tests has failed
  11053. return (std::min) (MaxExitCode, (std::max) (totals.error, static_cast<int>(totals.assertions.failed)));
  11054. }
  11055. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  11056. catch( std::exception& ex ) {
  11057. Catch::cerr() << ex.what() << std::endl;
  11058. return MaxExitCode;
  11059. }
  11060. #endif
  11061. }
  11062. } // end namespace Catch
  11063. // end catch_session.cpp
  11064. // start catch_singletons.cpp
  11065. #include <vector>
  11066. namespace Catch {
  11067. namespace {
  11068. static auto getSingletons() -> std::vector<ISingleton*>*& {
  11069. static std::vector<ISingleton*>* g_singletons = nullptr;
  11070. if( !g_singletons )
  11071. g_singletons = new std::vector<ISingleton*>();
  11072. return g_singletons;
  11073. }
  11074. }
  11075. ISingleton::~ISingleton() {}
  11076. void addSingleton(ISingleton* singleton ) {
  11077. getSingletons()->push_back( singleton );
  11078. }
  11079. void cleanupSingletons() {
  11080. auto& singletons = getSingletons();
  11081. for( auto singleton : *singletons )
  11082. delete singleton;
  11083. delete singletons;
  11084. singletons = nullptr;
  11085. }
  11086. } // namespace Catch
  11087. // end catch_singletons.cpp
  11088. // start catch_startup_exception_registry.cpp
  11089. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  11090. namespace Catch {
  11091. void StartupExceptionRegistry::add( std::exception_ptr const& exception ) noexcept {
  11092. CATCH_TRY {
  11093. m_exceptions.push_back(exception);
  11094. } CATCH_CATCH_ALL {
  11095. // If we run out of memory during start-up there's really not a lot more we can do about it
  11096. std::terminate();
  11097. }
  11098. }
  11099. std::vector<std::exception_ptr> const& StartupExceptionRegistry::getExceptions() const noexcept {
  11100. return m_exceptions;
  11101. }
  11102. } // end namespace Catch
  11103. #endif
  11104. // end catch_startup_exception_registry.cpp
  11105. // start catch_stream.cpp
  11106. #include <cstdio>
  11107. #include <iostream>
  11108. #include <fstream>
  11109. #include <sstream>
  11110. #include <vector>
  11111. #include <memory>
  11112. namespace Catch {
  11113. Catch::IStream::~IStream() = default;
  11114. namespace Detail { namespace {
  11115. template<typename WriterF, std::size_t bufferSize=256>
  11116. class StreamBufImpl : public std::streambuf {
  11117. char data[bufferSize];
  11118. WriterF m_writer;
  11119. public:
  11120. StreamBufImpl() {
  11121. setp( data, data + sizeof(data) );
  11122. }
  11123. ~StreamBufImpl() noexcept {
  11124. StreamBufImpl::sync();
  11125. }
  11126. private:
  11127. int overflow( int c ) override {
  11128. sync();
  11129. if( c != EOF ) {
  11130. if( pbase() == epptr() )
  11131. m_writer( std::string( 1, static_cast<char>( c ) ) );
  11132. else
  11133. sputc( static_cast<char>( c ) );
  11134. }
  11135. return 0;
  11136. }
  11137. int sync() override {
  11138. if( pbase() != pptr() ) {
  11139. m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) );
  11140. setp( pbase(), epptr() );
  11141. }
  11142. return 0;
  11143. }
  11144. };
  11145. ///////////////////////////////////////////////////////////////////////////
  11146. struct OutputDebugWriter {
  11147. void operator()( std::string const&str ) {
  11148. writeToDebugConsole( str );
  11149. }
  11150. };
  11151. ///////////////////////////////////////////////////////////////////////////
  11152. class FileStream : public IStream {
  11153. mutable std::ofstream m_ofs;
  11154. public:
  11155. FileStream( StringRef filename ) {
  11156. m_ofs.open( filename.c_str() );
  11157. CATCH_ENFORCE( !m_ofs.fail(), "Unable to open file: '" << filename << "'" );
  11158. }
  11159. ~FileStream() override = default;
  11160. public: // IStream
  11161. std::ostream& stream() const override {
  11162. return m_ofs;
  11163. }
  11164. };
  11165. ///////////////////////////////////////////////////////////////////////////
  11166. class CoutStream : public IStream {
  11167. mutable std::ostream m_os;
  11168. public:
  11169. // Store the streambuf from cout up-front because
  11170. // cout may get redirected when running tests
  11171. CoutStream() : m_os( Catch::cout().rdbuf() ) {}
  11172. ~CoutStream() override = default;
  11173. public: // IStream
  11174. std::ostream& stream() const override { return m_os; }
  11175. };
  11176. ///////////////////////////////////////////////////////////////////////////
  11177. class DebugOutStream : public IStream {
  11178. std::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf;
  11179. mutable std::ostream m_os;
  11180. public:
  11181. DebugOutStream()
  11182. : m_streamBuf( new StreamBufImpl<OutputDebugWriter>() ),
  11183. m_os( m_streamBuf.get() )
  11184. {}
  11185. ~DebugOutStream() override = default;
  11186. public: // IStream
  11187. std::ostream& stream() const override { return m_os; }
  11188. };
  11189. }} // namespace anon::detail
  11190. ///////////////////////////////////////////////////////////////////////////
  11191. auto makeStream( StringRef const &filename ) -> IStream const* {
  11192. if( filename.empty() )
  11193. return new Detail::CoutStream();
  11194. else if( filename[0] == '%' ) {
  11195. if( filename == "%debug" )
  11196. return new Detail::DebugOutStream();
  11197. else
  11198. CATCH_ERROR( "Unrecognised stream: '" << filename << "'" );
  11199. }
  11200. else
  11201. return new Detail::FileStream( filename );
  11202. }
  11203. // This class encapsulates the idea of a pool of ostringstreams that can be reused.
  11204. struct StringStreams {
  11205. std::vector<std::unique_ptr<std::ostringstream>> m_streams;
  11206. std::vector<std::size_t> m_unused;
  11207. std::ostringstream m_referenceStream; // Used for copy state/ flags from
  11208. auto add() -> std::size_t {
  11209. if( m_unused.empty() ) {
  11210. m_streams.push_back( std::unique_ptr<std::ostringstream>( new std::ostringstream ) );
  11211. return m_streams.size()-1;
  11212. }
  11213. else {
  11214. auto index = m_unused.back();
  11215. m_unused.pop_back();
  11216. return index;
  11217. }
  11218. }
  11219. void release( std::size_t index ) {
  11220. m_streams[index]->copyfmt( m_referenceStream ); // Restore initial flags and other state
  11221. m_unused.push_back(index);
  11222. }
  11223. };
  11224. ReusableStringStream::ReusableStringStream()
  11225. : m_index( Singleton<StringStreams>::getMutable().add() ),
  11226. m_oss( Singleton<StringStreams>::getMutable().m_streams[m_index].get() )
  11227. {}
  11228. ReusableStringStream::~ReusableStringStream() {
  11229. static_cast<std::ostringstream*>( m_oss )->str("");
  11230. m_oss->clear();
  11231. Singleton<StringStreams>::getMutable().release( m_index );
  11232. }
  11233. auto ReusableStringStream::str() const -> std::string {
  11234. return static_cast<std::ostringstream*>( m_oss )->str();
  11235. }
  11236. ///////////////////////////////////////////////////////////////////////////
  11237. #ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions
  11238. std::ostream& cout() { return std::cout; }
  11239. std::ostream& cerr() { return std::cerr; }
  11240. std::ostream& clog() { return std::clog; }
  11241. #endif
  11242. }
  11243. // end catch_stream.cpp
  11244. // start catch_string_manip.cpp
  11245. #include <algorithm>
  11246. #include <ostream>
  11247. #include <cstring>
  11248. #include <cctype>
  11249. #include <vector>
  11250. namespace Catch {
  11251. namespace {
  11252. char toLowerCh(char c) {
  11253. return static_cast<char>( std::tolower( static_cast<unsigned char>(c) ) );
  11254. }
  11255. }
  11256. bool startsWith( std::string const& s, std::string const& prefix ) {
  11257. return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
  11258. }
  11259. bool startsWith( std::string const& s, char prefix ) {
  11260. return !s.empty() && s[0] == prefix;
  11261. }
  11262. bool endsWith( std::string const& s, std::string const& suffix ) {
  11263. return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
  11264. }
  11265. bool endsWith( std::string const& s, char suffix ) {
  11266. return !s.empty() && s[s.size()-1] == suffix;
  11267. }
  11268. bool contains( std::string const& s, std::string const& infix ) {
  11269. return s.find( infix ) != std::string::npos;
  11270. }
  11271. void toLowerInPlace( std::string& s ) {
  11272. std::transform( s.begin(), s.end(), s.begin(), toLowerCh );
  11273. }
  11274. std::string toLower( std::string const& s ) {
  11275. std::string lc = s;
  11276. toLowerInPlace( lc );
  11277. return lc;
  11278. }
  11279. std::string trim( std::string const& str ) {
  11280. static char const* whitespaceChars = "\n\r\t ";
  11281. std::string::size_type start = str.find_first_not_of( whitespaceChars );
  11282. std::string::size_type end = str.find_last_not_of( whitespaceChars );
  11283. return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string();
  11284. }
  11285. StringRef trim(StringRef ref) {
  11286. const auto is_ws = [](char c) {
  11287. return c == ' ' || c == '\t' || c == '\n' || c == '\r';
  11288. };
  11289. size_t real_begin = 0;
  11290. while (real_begin < ref.size() && is_ws(ref[real_begin])) { ++real_begin; }
  11291. size_t real_end = ref.size();
  11292. while (real_end > real_begin && is_ws(ref[real_end - 1])) { --real_end; }
  11293. return ref.substr(real_begin, real_end - real_begin);
  11294. }
  11295. bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) {
  11296. bool replaced = false;
  11297. std::size_t i = str.find( replaceThis );
  11298. while( i != std::string::npos ) {
  11299. replaced = true;
  11300. str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() );
  11301. if( i < str.size()-withThis.size() )
  11302. i = str.find( replaceThis, i+withThis.size() );
  11303. else
  11304. i = std::string::npos;
  11305. }
  11306. return replaced;
  11307. }
  11308. std::vector<StringRef> splitStringRef( StringRef str, char delimiter ) {
  11309. std::vector<StringRef> subStrings;
  11310. std::size_t start = 0;
  11311. for(std::size_t pos = 0; pos < str.size(); ++pos ) {
  11312. if( str[pos] == delimiter ) {
  11313. if( pos - start > 1 )
  11314. subStrings.push_back( str.substr( start, pos-start ) );
  11315. start = pos+1;
  11316. }
  11317. }
  11318. if( start < str.size() )
  11319. subStrings.push_back( str.substr( start, str.size()-start ) );
  11320. return subStrings;
  11321. }
  11322. pluralise::pluralise( std::size_t count, std::string const& label )
  11323. : m_count( count ),
  11324. m_label( label )
  11325. {}
  11326. std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) {
  11327. os << pluraliser.m_count << ' ' << pluraliser.m_label;
  11328. if( pluraliser.m_count != 1 )
  11329. os << 's';
  11330. return os;
  11331. }
  11332. }
  11333. // end catch_string_manip.cpp
  11334. // start catch_stringref.cpp
  11335. #include <algorithm>
  11336. #include <ostream>
  11337. #include <cstring>
  11338. #include <cstdint>
  11339. namespace Catch {
  11340. StringRef::StringRef( char const* rawChars ) noexcept
  11341. : StringRef( rawChars, static_cast<StringRef::size_type>(std::strlen(rawChars) ) )
  11342. {}
  11343. auto StringRef::c_str() const -> char const* {
  11344. CATCH_ENFORCE(isNullTerminated(), "Called StringRef::c_str() on a non-null-terminated instance");
  11345. return m_start;
  11346. }
  11347. auto StringRef::data() const noexcept -> char const* {
  11348. return m_start;
  11349. }
  11350. auto StringRef::substr( size_type start, size_type size ) const noexcept -> StringRef {
  11351. if (start < m_size) {
  11352. return StringRef(m_start + start, (std::min)(m_size - start, size));
  11353. } else {
  11354. return StringRef();
  11355. }
  11356. }
  11357. auto StringRef::operator == ( StringRef const& other ) const noexcept -> bool {
  11358. return m_size == other.m_size
  11359. && (std::memcmp( m_start, other.m_start, m_size ) == 0);
  11360. }
  11361. auto operator << ( std::ostream& os, StringRef const& str ) -> std::ostream& {
  11362. return os.write(str.data(), str.size());
  11363. }
  11364. auto operator+=( std::string& lhs, StringRef const& rhs ) -> std::string& {
  11365. lhs.append(rhs.data(), rhs.size());
  11366. return lhs;
  11367. }
  11368. } // namespace Catch
  11369. // end catch_stringref.cpp
  11370. // start catch_tag_alias.cpp
  11371. namespace Catch {
  11372. TagAlias::TagAlias(std::string const & _tag, SourceLineInfo _lineInfo): tag(_tag), lineInfo(_lineInfo) {}
  11373. }
  11374. // end catch_tag_alias.cpp
  11375. // start catch_tag_alias_autoregistrar.cpp
  11376. namespace Catch {
  11377. RegistrarForTagAliases::RegistrarForTagAliases(char const* alias, char const* tag, SourceLineInfo const& lineInfo) {
  11378. CATCH_TRY {
  11379. getMutableRegistryHub().registerTagAlias(alias, tag, lineInfo);
  11380. } CATCH_CATCH_ALL {
  11381. // Do not throw when constructing global objects, instead register the exception to be processed later
  11382. getMutableRegistryHub().registerStartupException();
  11383. }
  11384. }
  11385. }
  11386. // end catch_tag_alias_autoregistrar.cpp
  11387. // start catch_tag_alias_registry.cpp
  11388. #include <sstream>
  11389. namespace Catch {
  11390. TagAliasRegistry::~TagAliasRegistry() {}
  11391. TagAlias const* TagAliasRegistry::find( std::string const& alias ) const {
  11392. auto it = m_registry.find( alias );
  11393. if( it != m_registry.end() )
  11394. return &(it->second);
  11395. else
  11396. return nullptr;
  11397. }
  11398. std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const {
  11399. std::string expandedTestSpec = unexpandedTestSpec;
  11400. for( auto const& registryKvp : m_registry ) {
  11401. std::size_t pos = expandedTestSpec.find( registryKvp.first );
  11402. if( pos != std::string::npos ) {
  11403. expandedTestSpec = expandedTestSpec.substr( 0, pos ) +
  11404. registryKvp.second.tag +
  11405. expandedTestSpec.substr( pos + registryKvp.first.size() );
  11406. }
  11407. }
  11408. return expandedTestSpec;
  11409. }
  11410. void TagAliasRegistry::add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) {
  11411. CATCH_ENFORCE( startsWith(alias, "[@") && endsWith(alias, ']'),
  11412. "error: tag alias, '" << alias << "' is not of the form [@alias name].\n" << lineInfo );
  11413. CATCH_ENFORCE( m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second,
  11414. "error: tag alias, '" << alias << "' already registered.\n"
  11415. << "\tFirst seen at: " << find(alias)->lineInfo << "\n"
  11416. << "\tRedefined at: " << lineInfo );
  11417. }
  11418. ITagAliasRegistry::~ITagAliasRegistry() {}
  11419. ITagAliasRegistry const& ITagAliasRegistry::get() {
  11420. return getRegistryHub().getTagAliasRegistry();
  11421. }
  11422. } // end namespace Catch
  11423. // end catch_tag_alias_registry.cpp
  11424. // start catch_test_case_info.cpp
  11425. #include <cctype>
  11426. #include <exception>
  11427. #include <algorithm>
  11428. #include <sstream>
  11429. namespace Catch {
  11430. namespace {
  11431. TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) {
  11432. if( startsWith( tag, '.' ) ||
  11433. tag == "!hide" )
  11434. return TestCaseInfo::IsHidden;
  11435. else if( tag == "!throws" )
  11436. return TestCaseInfo::Throws;
  11437. else if( tag == "!shouldfail" )
  11438. return TestCaseInfo::ShouldFail;
  11439. else if( tag == "!mayfail" )
  11440. return TestCaseInfo::MayFail;
  11441. else if( tag == "!nonportable" )
  11442. return TestCaseInfo::NonPortable;
  11443. else if( tag == "!benchmark" )
  11444. return static_cast<TestCaseInfo::SpecialProperties>( TestCaseInfo::Benchmark | TestCaseInfo::IsHidden );
  11445. else
  11446. return TestCaseInfo::None;
  11447. }
  11448. bool isReservedTag( std::string const& tag ) {
  11449. return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !std::isalnum( static_cast<unsigned char>(tag[0]) );
  11450. }
  11451. void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) {
  11452. CATCH_ENFORCE( !isReservedTag(tag),
  11453. "Tag name: [" << tag << "] is not allowed.\n"
  11454. << "Tag names starting with non alphanumeric characters are reserved\n"
  11455. << _lineInfo );
  11456. }
  11457. }
  11458. TestCase makeTestCase( ITestInvoker* _testCase,
  11459. std::string const& _className,
  11460. NameAndTags const& nameAndTags,
  11461. SourceLineInfo const& _lineInfo )
  11462. {
  11463. bool isHidden = false;
  11464. // Parse out tags
  11465. std::vector<std::string> tags;
  11466. std::string desc, tag;
  11467. bool inTag = false;
  11468. for (char c : nameAndTags.tags) {
  11469. if( !inTag ) {
  11470. if( c == '[' )
  11471. inTag = true;
  11472. else
  11473. desc += c;
  11474. }
  11475. else {
  11476. if( c == ']' ) {
  11477. TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag );
  11478. if( ( prop & TestCaseInfo::IsHidden ) != 0 )
  11479. isHidden = true;
  11480. else if( prop == TestCaseInfo::None )
  11481. enforceNotReservedTag( tag, _lineInfo );
  11482. // Merged hide tags like `[.approvals]` should be added as
  11483. // `[.][approvals]`. The `[.]` is added at later point, so
  11484. // we only strip the prefix
  11485. if (startsWith(tag, '.') && tag.size() > 1) {
  11486. tag.erase(0, 1);
  11487. }
  11488. tags.push_back( tag );
  11489. tag.clear();
  11490. inTag = false;
  11491. }
  11492. else
  11493. tag += c;
  11494. }
  11495. }
  11496. if( isHidden ) {
  11497. // Add all "hidden" tags to make them behave identically
  11498. tags.insert( tags.end(), { ".", "!hide" } );
  11499. }
  11500. TestCaseInfo info( static_cast<std::string>(nameAndTags.name), _className, desc, tags, _lineInfo );
  11501. return TestCase( _testCase, std::move(info) );
  11502. }
  11503. void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags ) {
  11504. std::sort(begin(tags), end(tags));
  11505. tags.erase(std::unique(begin(tags), end(tags)), end(tags));
  11506. testCaseInfo.lcaseTags.clear();
  11507. for( auto const& tag : tags ) {
  11508. std::string lcaseTag = toLower( tag );
  11509. testCaseInfo.properties = static_cast<TestCaseInfo::SpecialProperties>( testCaseInfo.properties | parseSpecialTag( lcaseTag ) );
  11510. testCaseInfo.lcaseTags.push_back( lcaseTag );
  11511. }
  11512. testCaseInfo.tags = std::move(tags);
  11513. }
  11514. TestCaseInfo::TestCaseInfo( std::string const& _name,
  11515. std::string const& _className,
  11516. std::string const& _description,
  11517. std::vector<std::string> const& _tags,
  11518. SourceLineInfo const& _lineInfo )
  11519. : name( _name ),
  11520. className( _className ),
  11521. description( _description ),
  11522. lineInfo( _lineInfo ),
  11523. properties( None )
  11524. {
  11525. setTags( *this, _tags );
  11526. }
  11527. bool TestCaseInfo::isHidden() const {
  11528. return ( properties & IsHidden ) != 0;
  11529. }
  11530. bool TestCaseInfo::throws() const {
  11531. return ( properties & Throws ) != 0;
  11532. }
  11533. bool TestCaseInfo::okToFail() const {
  11534. return ( properties & (ShouldFail | MayFail ) ) != 0;
  11535. }
  11536. bool TestCaseInfo::expectedToFail() const {
  11537. return ( properties & (ShouldFail ) ) != 0;
  11538. }
  11539. std::string TestCaseInfo::tagsAsString() const {
  11540. std::string ret;
  11541. // '[' and ']' per tag
  11542. std::size_t full_size = 2 * tags.size();
  11543. for (const auto& tag : tags) {
  11544. full_size += tag.size();
  11545. }
  11546. ret.reserve(full_size);
  11547. for (const auto& tag : tags) {
  11548. ret.push_back('[');
  11549. ret.append(tag);
  11550. ret.push_back(']');
  11551. }
  11552. return ret;
  11553. }
  11554. TestCase::TestCase( ITestInvoker* testCase, TestCaseInfo&& info ) : TestCaseInfo( std::move(info) ), test( testCase ) {}
  11555. TestCase TestCase::withName( std::string const& _newName ) const {
  11556. TestCase other( *this );
  11557. other.name = _newName;
  11558. return other;
  11559. }
  11560. void TestCase::invoke() const {
  11561. test->invoke();
  11562. }
  11563. bool TestCase::operator == ( TestCase const& other ) const {
  11564. return test.get() == other.test.get() &&
  11565. name == other.name &&
  11566. className == other.className;
  11567. }
  11568. bool TestCase::operator < ( TestCase const& other ) const {
  11569. return name < other.name;
  11570. }
  11571. TestCaseInfo const& TestCase::getTestCaseInfo() const
  11572. {
  11573. return *this;
  11574. }
  11575. } // end namespace Catch
  11576. // end catch_test_case_info.cpp
  11577. // start catch_test_case_registry_impl.cpp
  11578. #include <algorithm>
  11579. #include <sstream>
  11580. namespace Catch {
  11581. namespace {
  11582. struct TestHasher {
  11583. using hash_t = uint64_t;
  11584. explicit TestHasher( hash_t hashSuffix ):
  11585. m_hashSuffix{ hashSuffix } {}
  11586. uint32_t operator()( TestCase const& t ) const {
  11587. // FNV-1a hash with multiplication fold.
  11588. const hash_t prime = 1099511628211u;
  11589. hash_t hash = 14695981039346656037u;
  11590. for ( const char c : t.name ) {
  11591. hash ^= c;
  11592. hash *= prime;
  11593. }
  11594. hash ^= m_hashSuffix;
  11595. hash *= prime;
  11596. const uint32_t low{ static_cast<uint32_t>( hash ) };
  11597. const uint32_t high{ static_cast<uint32_t>( hash >> 32 ) };
  11598. return low * high;
  11599. }
  11600. private:
  11601. hash_t m_hashSuffix;
  11602. };
  11603. } // end unnamed namespace
  11604. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases ) {
  11605. switch( config.runOrder() ) {
  11606. case RunTests::InDeclarationOrder:
  11607. // already in declaration order
  11608. break;
  11609. case RunTests::InLexicographicalOrder: {
  11610. std::vector<TestCase> sorted = unsortedTestCases;
  11611. std::sort( sorted.begin(), sorted.end() );
  11612. return sorted;
  11613. }
  11614. case RunTests::InRandomOrder: {
  11615. seedRng( config );
  11616. TestHasher h{ config.rngSeed() };
  11617. using hashedTest = std::pair<TestHasher::hash_t, TestCase const*>;
  11618. std::vector<hashedTest> indexed_tests;
  11619. indexed_tests.reserve( unsortedTestCases.size() );
  11620. for (auto const& testCase : unsortedTestCases) {
  11621. indexed_tests.emplace_back(h(testCase), &testCase);
  11622. }
  11623. std::sort(indexed_tests.begin(), indexed_tests.end(),
  11624. [](hashedTest const& lhs, hashedTest const& rhs) {
  11625. if (lhs.first == rhs.first) {
  11626. return lhs.second->name < rhs.second->name;
  11627. }
  11628. return lhs.first < rhs.first;
  11629. });
  11630. std::vector<TestCase> sorted;
  11631. sorted.reserve( indexed_tests.size() );
  11632. for (auto const& hashed : indexed_tests) {
  11633. sorted.emplace_back(*hashed.second);
  11634. }
  11635. return sorted;
  11636. }
  11637. }
  11638. return unsortedTestCases;
  11639. }
  11640. bool isThrowSafe( TestCase const& testCase, IConfig const& config ) {
  11641. return !testCase.throws() || config.allowThrows();
  11642. }
  11643. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ) {
  11644. return testSpec.matches( testCase ) && isThrowSafe( testCase, config );
  11645. }
  11646. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions ) {
  11647. std::set<TestCase> seenFunctions;
  11648. for( auto const& function : functions ) {
  11649. auto prev = seenFunctions.insert( function );
  11650. CATCH_ENFORCE( prev.second,
  11651. "error: TEST_CASE( \"" << function.name << "\" ) already defined.\n"
  11652. << "\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo << "\n"
  11653. << "\tRedefined at " << function.getTestCaseInfo().lineInfo );
  11654. }
  11655. }
  11656. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config ) {
  11657. std::vector<TestCase> filtered;
  11658. filtered.reserve( testCases.size() );
  11659. for (auto const& testCase : testCases) {
  11660. if ((!testSpec.hasFilters() && !testCase.isHidden()) ||
  11661. (testSpec.hasFilters() && matchTest(testCase, testSpec, config))) {
  11662. filtered.push_back(testCase);
  11663. }
  11664. }
  11665. return filtered;
  11666. }
  11667. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config ) {
  11668. return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config );
  11669. }
  11670. void TestRegistry::registerTest( TestCase const& testCase ) {
  11671. std::string name = testCase.getTestCaseInfo().name;
  11672. if( name.empty() ) {
  11673. ReusableStringStream rss;
  11674. rss << "Anonymous test case " << ++m_unnamedCount;
  11675. return registerTest( testCase.withName( rss.str() ) );
  11676. }
  11677. m_functions.push_back( testCase );
  11678. }
  11679. std::vector<TestCase> const& TestRegistry::getAllTests() const {
  11680. return m_functions;
  11681. }
  11682. std::vector<TestCase> const& TestRegistry::getAllTestsSorted( IConfig const& config ) const {
  11683. if( m_sortedFunctions.empty() )
  11684. enforceNoDuplicateTestCases( m_functions );
  11685. if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) {
  11686. m_sortedFunctions = sortTests( config, m_functions );
  11687. m_currentSortOrder = config.runOrder();
  11688. }
  11689. return m_sortedFunctions;
  11690. }
  11691. ///////////////////////////////////////////////////////////////////////////
  11692. TestInvokerAsFunction::TestInvokerAsFunction( void(*testAsFunction)() ) noexcept : m_testAsFunction( testAsFunction ) {}
  11693. void TestInvokerAsFunction::invoke() const {
  11694. m_testAsFunction();
  11695. }
  11696. std::string extractClassName( StringRef const& classOrQualifiedMethodName ) {
  11697. std::string className(classOrQualifiedMethodName);
  11698. if( startsWith( className, '&' ) )
  11699. {
  11700. std::size_t lastColons = className.rfind( "::" );
  11701. std::size_t penultimateColons = className.rfind( "::", lastColons-1 );
  11702. if( penultimateColons == std::string::npos )
  11703. penultimateColons = 1;
  11704. className = className.substr( penultimateColons, lastColons-penultimateColons );
  11705. }
  11706. return className;
  11707. }
  11708. } // end namespace Catch
  11709. // end catch_test_case_registry_impl.cpp
  11710. // start catch_test_case_tracker.cpp
  11711. #include <algorithm>
  11712. #include <cassert>
  11713. #include <stdexcept>
  11714. #include <memory>
  11715. #include <sstream>
  11716. #if defined(__clang__)
  11717. # pragma clang diagnostic push
  11718. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  11719. #endif
  11720. namespace Catch {
  11721. namespace TestCaseTracking {
  11722. NameAndLocation::NameAndLocation( std::string const& _name, SourceLineInfo const& _location )
  11723. : name( _name ),
  11724. location( _location )
  11725. {}
  11726. ITracker::~ITracker() = default;
  11727. ITracker& TrackerContext::startRun() {
  11728. m_rootTracker = std::make_shared<SectionTracker>( NameAndLocation( "{root}", CATCH_INTERNAL_LINEINFO ), *this, nullptr );
  11729. m_currentTracker = nullptr;
  11730. m_runState = Executing;
  11731. return *m_rootTracker;
  11732. }
  11733. void TrackerContext::endRun() {
  11734. m_rootTracker.reset();
  11735. m_currentTracker = nullptr;
  11736. m_runState = NotStarted;
  11737. }
  11738. void TrackerContext::startCycle() {
  11739. m_currentTracker = m_rootTracker.get();
  11740. m_runState = Executing;
  11741. }
  11742. void TrackerContext::completeCycle() {
  11743. m_runState = CompletedCycle;
  11744. }
  11745. bool TrackerContext::completedCycle() const {
  11746. return m_runState == CompletedCycle;
  11747. }
  11748. ITracker& TrackerContext::currentTracker() {
  11749. return *m_currentTracker;
  11750. }
  11751. void TrackerContext::setCurrentTracker( ITracker* tracker ) {
  11752. m_currentTracker = tracker;
  11753. }
  11754. TrackerBase::TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent ):
  11755. ITracker(nameAndLocation),
  11756. m_ctx( ctx ),
  11757. m_parent( parent )
  11758. {}
  11759. bool TrackerBase::isComplete() const {
  11760. return m_runState == CompletedSuccessfully || m_runState == Failed;
  11761. }
  11762. bool TrackerBase::isSuccessfullyCompleted() const {
  11763. return m_runState == CompletedSuccessfully;
  11764. }
  11765. bool TrackerBase::isOpen() const {
  11766. return m_runState != NotStarted && !isComplete();
  11767. }
  11768. bool TrackerBase::hasChildren() const {
  11769. return !m_children.empty();
  11770. }
  11771. void TrackerBase::addChild( ITrackerPtr const& child ) {
  11772. m_children.push_back( child );
  11773. }
  11774. ITrackerPtr TrackerBase::findChild( NameAndLocation const& nameAndLocation ) {
  11775. auto it = std::find_if( m_children.begin(), m_children.end(),
  11776. [&nameAndLocation]( ITrackerPtr const& tracker ){
  11777. return
  11778. tracker->nameAndLocation().location == nameAndLocation.location &&
  11779. tracker->nameAndLocation().name == nameAndLocation.name;
  11780. } );
  11781. return( it != m_children.end() )
  11782. ? *it
  11783. : nullptr;
  11784. }
  11785. ITracker& TrackerBase::parent() {
  11786. assert( m_parent ); // Should always be non-null except for root
  11787. return *m_parent;
  11788. }
  11789. void TrackerBase::openChild() {
  11790. if( m_runState != ExecutingChildren ) {
  11791. m_runState = ExecutingChildren;
  11792. if( m_parent )
  11793. m_parent->openChild();
  11794. }
  11795. }
  11796. bool TrackerBase::isSectionTracker() const { return false; }
  11797. bool TrackerBase::isGeneratorTracker() const { return false; }
  11798. void TrackerBase::open() {
  11799. m_runState = Executing;
  11800. moveToThis();
  11801. if( m_parent )
  11802. m_parent->openChild();
  11803. }
  11804. void TrackerBase::close() {
  11805. // Close any still open children (e.g. generators)
  11806. while( &m_ctx.currentTracker() != this )
  11807. m_ctx.currentTracker().close();
  11808. switch( m_runState ) {
  11809. case NeedsAnotherRun:
  11810. break;
  11811. case Executing:
  11812. m_runState = CompletedSuccessfully;
  11813. break;
  11814. case ExecutingChildren:
  11815. if( std::all_of(m_children.begin(), m_children.end(), [](ITrackerPtr const& t){ return t->isComplete(); }) )
  11816. m_runState = CompletedSuccessfully;
  11817. break;
  11818. case NotStarted:
  11819. case CompletedSuccessfully:
  11820. case Failed:
  11821. CATCH_INTERNAL_ERROR( "Illogical state: " << m_runState );
  11822. default:
  11823. CATCH_INTERNAL_ERROR( "Unknown state: " << m_runState );
  11824. }
  11825. moveToParent();
  11826. m_ctx.completeCycle();
  11827. }
  11828. void TrackerBase::fail() {
  11829. m_runState = Failed;
  11830. if( m_parent )
  11831. m_parent->markAsNeedingAnotherRun();
  11832. moveToParent();
  11833. m_ctx.completeCycle();
  11834. }
  11835. void TrackerBase::markAsNeedingAnotherRun() {
  11836. m_runState = NeedsAnotherRun;
  11837. }
  11838. void TrackerBase::moveToParent() {
  11839. assert( m_parent );
  11840. m_ctx.setCurrentTracker( m_parent );
  11841. }
  11842. void TrackerBase::moveToThis() {
  11843. m_ctx.setCurrentTracker( this );
  11844. }
  11845. SectionTracker::SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  11846. : TrackerBase( nameAndLocation, ctx, parent ),
  11847. m_trimmed_name(trim(nameAndLocation.name))
  11848. {
  11849. if( parent ) {
  11850. while( !parent->isSectionTracker() )
  11851. parent = &parent->parent();
  11852. SectionTracker& parentSection = static_cast<SectionTracker&>( *parent );
  11853. addNextFilters( parentSection.m_filters );
  11854. }
  11855. }
  11856. bool SectionTracker::isComplete() const {
  11857. bool complete = true;
  11858. if (m_filters.empty()
  11859. || m_filters[0] == ""
  11860. || std::find(m_filters.begin(), m_filters.end(), m_trimmed_name) != m_filters.end()) {
  11861. complete = TrackerBase::isComplete();
  11862. }
  11863. return complete;
  11864. }
  11865. bool SectionTracker::isSectionTracker() const { return true; }
  11866. SectionTracker& SectionTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ) {
  11867. std::shared_ptr<SectionTracker> section;
  11868. ITracker& currentTracker = ctx.currentTracker();
  11869. if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  11870. assert( childTracker );
  11871. assert( childTracker->isSectionTracker() );
  11872. section = std::static_pointer_cast<SectionTracker>( childTracker );
  11873. }
  11874. else {
  11875. section = std::make_shared<SectionTracker>( nameAndLocation, ctx, &currentTracker );
  11876. currentTracker.addChild( section );
  11877. }
  11878. if( !ctx.completedCycle() )
  11879. section->tryOpen();
  11880. return *section;
  11881. }
  11882. void SectionTracker::tryOpen() {
  11883. if( !isComplete() )
  11884. open();
  11885. }
  11886. void SectionTracker::addInitialFilters( std::vector<std::string> const& filters ) {
  11887. if( !filters.empty() ) {
  11888. m_filters.reserve( m_filters.size() + filters.size() + 2 );
  11889. m_filters.emplace_back(""); // Root - should never be consulted
  11890. m_filters.emplace_back(""); // Test Case - not a section filter
  11891. m_filters.insert( m_filters.end(), filters.begin(), filters.end() );
  11892. }
  11893. }
  11894. void SectionTracker::addNextFilters( std::vector<std::string> const& filters ) {
  11895. if( filters.size() > 1 )
  11896. m_filters.insert( m_filters.end(), filters.begin()+1, filters.end() );
  11897. }
  11898. std::vector<std::string> const& SectionTracker::getFilters() const {
  11899. return m_filters;
  11900. }
  11901. std::string const& SectionTracker::trimmedName() const {
  11902. return m_trimmed_name;
  11903. }
  11904. } // namespace TestCaseTracking
  11905. using TestCaseTracking::ITracker;
  11906. using TestCaseTracking::TrackerContext;
  11907. using TestCaseTracking::SectionTracker;
  11908. } // namespace Catch
  11909. #if defined(__clang__)
  11910. # pragma clang diagnostic pop
  11911. #endif
  11912. // end catch_test_case_tracker.cpp
  11913. // start catch_test_registry.cpp
  11914. namespace Catch {
  11915. auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker* {
  11916. return new(std::nothrow) TestInvokerAsFunction( testAsFunction );
  11917. }
  11918. NameAndTags::NameAndTags( StringRef const& name_ , StringRef const& tags_ ) noexcept : name( name_ ), tags( tags_ ) {}
  11919. AutoReg::AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept {
  11920. CATCH_TRY {
  11921. getMutableRegistryHub()
  11922. .registerTest(
  11923. makeTestCase(
  11924. invoker,
  11925. extractClassName( classOrMethod ),
  11926. nameAndTags,
  11927. lineInfo));
  11928. } CATCH_CATCH_ALL {
  11929. // Do not throw when constructing global objects, instead register the exception to be processed later
  11930. getMutableRegistryHub().registerStartupException();
  11931. }
  11932. }
  11933. AutoReg::~AutoReg() = default;
  11934. }
  11935. // end catch_test_registry.cpp
  11936. // start catch_test_spec.cpp
  11937. #include <algorithm>
  11938. #include <string>
  11939. #include <vector>
  11940. #include <memory>
  11941. namespace Catch {
  11942. TestSpec::Pattern::Pattern( std::string const& name )
  11943. : m_name( name )
  11944. {}
  11945. TestSpec::Pattern::~Pattern() = default;
  11946. std::string const& TestSpec::Pattern::name() const {
  11947. return m_name;
  11948. }
  11949. TestSpec::NamePattern::NamePattern( std::string const& name, std::string const& filterString )
  11950. : Pattern( filterString )
  11951. , m_wildcardPattern( toLower( name ), CaseSensitive::No )
  11952. {}
  11953. bool TestSpec::NamePattern::matches( TestCaseInfo const& testCase ) const {
  11954. return m_wildcardPattern.matches( testCase.name );
  11955. }
  11956. TestSpec::TagPattern::TagPattern( std::string const& tag, std::string const& filterString )
  11957. : Pattern( filterString )
  11958. , m_tag( toLower( tag ) )
  11959. {}
  11960. bool TestSpec::TagPattern::matches( TestCaseInfo const& testCase ) const {
  11961. return std::find(begin(testCase.lcaseTags),
  11962. end(testCase.lcaseTags),
  11963. m_tag) != end(testCase.lcaseTags);
  11964. }
  11965. TestSpec::ExcludedPattern::ExcludedPattern( PatternPtr const& underlyingPattern )
  11966. : Pattern( underlyingPattern->name() )
  11967. , m_underlyingPattern( underlyingPattern )
  11968. {}
  11969. bool TestSpec::ExcludedPattern::matches( TestCaseInfo const& testCase ) const {
  11970. return !m_underlyingPattern->matches( testCase );
  11971. }
  11972. bool TestSpec::Filter::matches( TestCaseInfo const& testCase ) const {
  11973. return std::all_of( m_patterns.begin(), m_patterns.end(), [&]( PatternPtr const& p ){ return p->matches( testCase ); } );
  11974. }
  11975. std::string TestSpec::Filter::name() const {
  11976. std::string name;
  11977. for( auto const& p : m_patterns )
  11978. name += p->name();
  11979. return name;
  11980. }
  11981. bool TestSpec::hasFilters() const {
  11982. return !m_filters.empty();
  11983. }
  11984. bool TestSpec::matches( TestCaseInfo const& testCase ) const {
  11985. return std::any_of( m_filters.begin(), m_filters.end(), [&]( Filter const& f ){ return f.matches( testCase ); } );
  11986. }
  11987. TestSpec::Matches TestSpec::matchesByFilter( std::vector<TestCase> const& testCases, IConfig const& config ) const
  11988. {
  11989. Matches matches( m_filters.size() );
  11990. std::transform( m_filters.begin(), m_filters.end(), matches.begin(), [&]( Filter const& filter ){
  11991. std::vector<TestCase const*> currentMatches;
  11992. for( auto const& test : testCases )
  11993. if( isThrowSafe( test, config ) && filter.matches( test ) )
  11994. currentMatches.emplace_back( &test );
  11995. return FilterMatch{ filter.name(), currentMatches };
  11996. } );
  11997. return matches;
  11998. }
  11999. const TestSpec::vectorStrings& TestSpec::getInvalidArgs() const{
  12000. return (m_invalidArgs);
  12001. }
  12002. }
  12003. // end catch_test_spec.cpp
  12004. // start catch_test_spec_parser.cpp
  12005. namespace Catch {
  12006. TestSpecParser::TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {}
  12007. TestSpecParser& TestSpecParser::parse( std::string const& arg ) {
  12008. m_mode = None;
  12009. m_exclusion = false;
  12010. m_arg = m_tagAliases->expandAliases( arg );
  12011. m_escapeChars.clear();
  12012. m_substring.reserve(m_arg.size());
  12013. m_patternName.reserve(m_arg.size());
  12014. m_realPatternPos = 0;
  12015. for( m_pos = 0; m_pos < m_arg.size(); ++m_pos )
  12016. //if visitChar fails
  12017. if( !visitChar( m_arg[m_pos] ) ){
  12018. m_testSpec.m_invalidArgs.push_back(arg);
  12019. break;
  12020. }
  12021. endMode();
  12022. return *this;
  12023. }
  12024. TestSpec TestSpecParser::testSpec() {
  12025. addFilter();
  12026. return m_testSpec;
  12027. }
  12028. bool TestSpecParser::visitChar( char c ) {
  12029. if( (m_mode != EscapedName) && (c == '\\') ) {
  12030. escape();
  12031. addCharToPattern(c);
  12032. return true;
  12033. }else if((m_mode != EscapedName) && (c == ',') ) {
  12034. return separate();
  12035. }
  12036. switch( m_mode ) {
  12037. case None:
  12038. if( processNoneChar( c ) )
  12039. return true;
  12040. break;
  12041. case Name:
  12042. processNameChar( c );
  12043. break;
  12044. case EscapedName:
  12045. endMode();
  12046. addCharToPattern(c);
  12047. return true;
  12048. default:
  12049. case Tag:
  12050. case QuotedName:
  12051. if( processOtherChar( c ) )
  12052. return true;
  12053. break;
  12054. }
  12055. m_substring += c;
  12056. if( !isControlChar( c ) ) {
  12057. m_patternName += c;
  12058. m_realPatternPos++;
  12059. }
  12060. return true;
  12061. }
  12062. // Two of the processing methods return true to signal the caller to return
  12063. // without adding the given character to the current pattern strings
  12064. bool TestSpecParser::processNoneChar( char c ) {
  12065. switch( c ) {
  12066. case ' ':
  12067. return true;
  12068. case '~':
  12069. m_exclusion = true;
  12070. return false;
  12071. case '[':
  12072. startNewMode( Tag );
  12073. return false;
  12074. case '"':
  12075. startNewMode( QuotedName );
  12076. return false;
  12077. default:
  12078. startNewMode( Name );
  12079. return false;
  12080. }
  12081. }
  12082. void TestSpecParser::processNameChar( char c ) {
  12083. if( c == '[' ) {
  12084. if( m_substring == "exclude:" )
  12085. m_exclusion = true;
  12086. else
  12087. endMode();
  12088. startNewMode( Tag );
  12089. }
  12090. }
  12091. bool TestSpecParser::processOtherChar( char c ) {
  12092. if( !isControlChar( c ) )
  12093. return false;
  12094. m_substring += c;
  12095. endMode();
  12096. return true;
  12097. }
  12098. void TestSpecParser::startNewMode( Mode mode ) {
  12099. m_mode = mode;
  12100. }
  12101. void TestSpecParser::endMode() {
  12102. switch( m_mode ) {
  12103. case Name:
  12104. case QuotedName:
  12105. return addNamePattern();
  12106. case Tag:
  12107. return addTagPattern();
  12108. case EscapedName:
  12109. revertBackToLastMode();
  12110. return;
  12111. case None:
  12112. default:
  12113. return startNewMode( None );
  12114. }
  12115. }
  12116. void TestSpecParser::escape() {
  12117. saveLastMode();
  12118. m_mode = EscapedName;
  12119. m_escapeChars.push_back(m_realPatternPos);
  12120. }
  12121. bool TestSpecParser::isControlChar( char c ) const {
  12122. switch( m_mode ) {
  12123. default:
  12124. return false;
  12125. case None:
  12126. return c == '~';
  12127. case Name:
  12128. return c == '[';
  12129. case EscapedName:
  12130. return true;
  12131. case QuotedName:
  12132. return c == '"';
  12133. case Tag:
  12134. return c == '[' || c == ']';
  12135. }
  12136. }
  12137. void TestSpecParser::addFilter() {
  12138. if( !m_currentFilter.m_patterns.empty() ) {
  12139. m_testSpec.m_filters.push_back( m_currentFilter );
  12140. m_currentFilter = TestSpec::Filter();
  12141. }
  12142. }
  12143. void TestSpecParser::saveLastMode() {
  12144. lastMode = m_mode;
  12145. }
  12146. void TestSpecParser::revertBackToLastMode() {
  12147. m_mode = lastMode;
  12148. }
  12149. bool TestSpecParser::separate() {
  12150. if( (m_mode==QuotedName) || (m_mode==Tag) ){
  12151. //invalid argument, signal failure to previous scope.
  12152. m_mode = None;
  12153. m_pos = m_arg.size();
  12154. m_substring.clear();
  12155. m_patternName.clear();
  12156. m_realPatternPos = 0;
  12157. return false;
  12158. }
  12159. endMode();
  12160. addFilter();
  12161. return true; //success
  12162. }
  12163. std::string TestSpecParser::preprocessPattern() {
  12164. std::string token = m_patternName;
  12165. for (std::size_t i = 0; i < m_escapeChars.size(); ++i)
  12166. token = token.substr(0, m_escapeChars[i] - i) + token.substr(m_escapeChars[i] - i + 1);
  12167. m_escapeChars.clear();
  12168. if (startsWith(token, "exclude:")) {
  12169. m_exclusion = true;
  12170. token = token.substr(8);
  12171. }
  12172. m_patternName.clear();
  12173. m_realPatternPos = 0;
  12174. return token;
  12175. }
  12176. void TestSpecParser::addNamePattern() {
  12177. auto token = preprocessPattern();
  12178. if (!token.empty()) {
  12179. TestSpec::PatternPtr pattern = std::make_shared<TestSpec::NamePattern>(token, m_substring);
  12180. if (m_exclusion)
  12181. pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
  12182. m_currentFilter.m_patterns.push_back(pattern);
  12183. }
  12184. m_substring.clear();
  12185. m_exclusion = false;
  12186. m_mode = None;
  12187. }
  12188. void TestSpecParser::addTagPattern() {
  12189. auto token = preprocessPattern();
  12190. if (!token.empty()) {
  12191. // If the tag pattern is the "hide and tag" shorthand (e.g. [.foo])
  12192. // we have to create a separate hide tag and shorten the real one
  12193. if (token.size() > 1 && token[0] == '.') {
  12194. token.erase(token.begin());
  12195. TestSpec::PatternPtr pattern = std::make_shared<TestSpec::TagPattern>(".", m_substring);
  12196. if (m_exclusion) {
  12197. pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
  12198. }
  12199. m_currentFilter.m_patterns.push_back(pattern);
  12200. }
  12201. TestSpec::PatternPtr pattern = std::make_shared<TestSpec::TagPattern>(token, m_substring);
  12202. if (m_exclusion) {
  12203. pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
  12204. }
  12205. m_currentFilter.m_patterns.push_back(pattern);
  12206. }
  12207. m_substring.clear();
  12208. m_exclusion = false;
  12209. m_mode = None;
  12210. }
  12211. TestSpec parseTestSpec( std::string const& arg ) {
  12212. return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec();
  12213. }
  12214. } // namespace Catch
  12215. // end catch_test_spec_parser.cpp
  12216. // start catch_timer.cpp
  12217. #include <chrono>
  12218. static const uint64_t nanosecondsInSecond = 1000000000;
  12219. namespace Catch {
  12220. auto getCurrentNanosecondsSinceEpoch() -> uint64_t {
  12221. return std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::high_resolution_clock::now().time_since_epoch() ).count();
  12222. }
  12223. namespace {
  12224. auto estimateClockResolution() -> uint64_t {
  12225. uint64_t sum = 0;
  12226. static const uint64_t iterations = 1000000;
  12227. auto startTime = getCurrentNanosecondsSinceEpoch();
  12228. for( std::size_t i = 0; i < iterations; ++i ) {
  12229. uint64_t ticks;
  12230. uint64_t baseTicks = getCurrentNanosecondsSinceEpoch();
  12231. do {
  12232. ticks = getCurrentNanosecondsSinceEpoch();
  12233. } while( ticks == baseTicks );
  12234. auto delta = ticks - baseTicks;
  12235. sum += delta;
  12236. // If we have been calibrating for over 3 seconds -- the clock
  12237. // is terrible and we should move on.
  12238. // TBD: How to signal that the measured resolution is probably wrong?
  12239. if (ticks > startTime + 3 * nanosecondsInSecond) {
  12240. return sum / ( i + 1u );
  12241. }
  12242. }
  12243. // We're just taking the mean, here. To do better we could take the std. dev and exclude outliers
  12244. // - and potentially do more iterations if there's a high variance.
  12245. return sum/iterations;
  12246. }
  12247. }
  12248. auto getEstimatedClockResolution() -> uint64_t {
  12249. static auto s_resolution = estimateClockResolution();
  12250. return s_resolution;
  12251. }
  12252. void Timer::start() {
  12253. m_nanoseconds = getCurrentNanosecondsSinceEpoch();
  12254. }
  12255. auto Timer::getElapsedNanoseconds() const -> uint64_t {
  12256. return getCurrentNanosecondsSinceEpoch() - m_nanoseconds;
  12257. }
  12258. auto Timer::getElapsedMicroseconds() const -> uint64_t {
  12259. return getElapsedNanoseconds()/1000;
  12260. }
  12261. auto Timer::getElapsedMilliseconds() const -> unsigned int {
  12262. return static_cast<unsigned int>(getElapsedMicroseconds()/1000);
  12263. }
  12264. auto Timer::getElapsedSeconds() const -> double {
  12265. return getElapsedMicroseconds()/1000000.0;
  12266. }
  12267. } // namespace Catch
  12268. // end catch_timer.cpp
  12269. // start catch_tostring.cpp
  12270. #if defined(__clang__)
  12271. # pragma clang diagnostic push
  12272. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  12273. # pragma clang diagnostic ignored "-Wglobal-constructors"
  12274. #endif
  12275. // Enable specific decls locally
  12276. #if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  12277. #define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  12278. #endif
  12279. #include <cmath>
  12280. #include <iomanip>
  12281. namespace Catch {
  12282. namespace Detail {
  12283. const std::string unprintableString = "{?}";
  12284. namespace {
  12285. const int hexThreshold = 255;
  12286. struct Endianness {
  12287. enum Arch { Big, Little };
  12288. static Arch which() {
  12289. int one = 1;
  12290. // If the lowest byte we read is non-zero, we can assume
  12291. // that little endian format is used.
  12292. auto value = *reinterpret_cast<char*>(&one);
  12293. return value ? Little : Big;
  12294. }
  12295. };
  12296. }
  12297. std::string rawMemoryToString( const void *object, std::size_t size ) {
  12298. // Reverse order for little endian architectures
  12299. int i = 0, end = static_cast<int>( size ), inc = 1;
  12300. if( Endianness::which() == Endianness::Little ) {
  12301. i = end-1;
  12302. end = inc = -1;
  12303. }
  12304. unsigned char const *bytes = static_cast<unsigned char const *>(object);
  12305. ReusableStringStream rss;
  12306. rss << "0x" << std::setfill('0') << std::hex;
  12307. for( ; i != end; i += inc )
  12308. rss << std::setw(2) << static_cast<unsigned>(bytes[i]);
  12309. return rss.str();
  12310. }
  12311. }
  12312. template<typename T>
  12313. std::string fpToString( T value, int precision ) {
  12314. if (Catch::isnan(value)) {
  12315. return "nan";
  12316. }
  12317. ReusableStringStream rss;
  12318. rss << std::setprecision( precision )
  12319. << std::fixed
  12320. << value;
  12321. std::string d = rss.str();
  12322. std::size_t i = d.find_last_not_of( '0' );
  12323. if( i != std::string::npos && i != d.size()-1 ) {
  12324. if( d[i] == '.' )
  12325. i++;
  12326. d = d.substr( 0, i+1 );
  12327. }
  12328. return d;
  12329. }
  12330. //// ======================================================= ////
  12331. //
  12332. // Out-of-line defs for full specialization of StringMaker
  12333. //
  12334. //// ======================================================= ////
  12335. std::string StringMaker<std::string>::convert(const std::string& str) {
  12336. if (!getCurrentContext().getConfig()->showInvisibles()) {
  12337. return '"' + str + '"';
  12338. }
  12339. std::string s("\"");
  12340. for (char c : str) {
  12341. switch (c) {
  12342. case '\n':
  12343. s.append("\\n");
  12344. break;
  12345. case '\t':
  12346. s.append("\\t");
  12347. break;
  12348. default:
  12349. s.push_back(c);
  12350. break;
  12351. }
  12352. }
  12353. s.append("\"");
  12354. return s;
  12355. }
  12356. #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  12357. std::string StringMaker<std::string_view>::convert(std::string_view str) {
  12358. return ::Catch::Detail::stringify(std::string{ str });
  12359. }
  12360. #endif
  12361. std::string StringMaker<char const*>::convert(char const* str) {
  12362. if (str) {
  12363. return ::Catch::Detail::stringify(std::string{ str });
  12364. } else {
  12365. return{ "{null string}" };
  12366. }
  12367. }
  12368. std::string StringMaker<char*>::convert(char* str) {
  12369. if (str) {
  12370. return ::Catch::Detail::stringify(std::string{ str });
  12371. } else {
  12372. return{ "{null string}" };
  12373. }
  12374. }
  12375. #ifdef CATCH_CONFIG_WCHAR
  12376. std::string StringMaker<std::wstring>::convert(const std::wstring& wstr) {
  12377. std::string s;
  12378. s.reserve(wstr.size());
  12379. for (auto c : wstr) {
  12380. s += (c <= 0xff) ? static_cast<char>(c) : '?';
  12381. }
  12382. return ::Catch::Detail::stringify(s);
  12383. }
  12384. # ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  12385. std::string StringMaker<std::wstring_view>::convert(std::wstring_view str) {
  12386. return StringMaker<std::wstring>::convert(std::wstring(str));
  12387. }
  12388. # endif
  12389. std::string StringMaker<wchar_t const*>::convert(wchar_t const * str) {
  12390. if (str) {
  12391. return ::Catch::Detail::stringify(std::wstring{ str });
  12392. } else {
  12393. return{ "{null string}" };
  12394. }
  12395. }
  12396. std::string StringMaker<wchar_t *>::convert(wchar_t * str) {
  12397. if (str) {
  12398. return ::Catch::Detail::stringify(std::wstring{ str });
  12399. } else {
  12400. return{ "{null string}" };
  12401. }
  12402. }
  12403. #endif
  12404. #if defined(CATCH_CONFIG_CPP17_BYTE)
  12405. #include <cstddef>
  12406. std::string StringMaker<std::byte>::convert(std::byte value) {
  12407. return ::Catch::Detail::stringify(std::to_integer<unsigned long long>(value));
  12408. }
  12409. #endif // defined(CATCH_CONFIG_CPP17_BYTE)
  12410. std::string StringMaker<int>::convert(int value) {
  12411. return ::Catch::Detail::stringify(static_cast<long long>(value));
  12412. }
  12413. std::string StringMaker<long>::convert(long value) {
  12414. return ::Catch::Detail::stringify(static_cast<long long>(value));
  12415. }
  12416. std::string StringMaker<long long>::convert(long long value) {
  12417. ReusableStringStream rss;
  12418. rss << value;
  12419. if (value > Detail::hexThreshold) {
  12420. rss << " (0x" << std::hex << value << ')';
  12421. }
  12422. return rss.str();
  12423. }
  12424. std::string StringMaker<unsigned int>::convert(unsigned int value) {
  12425. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  12426. }
  12427. std::string StringMaker<unsigned long>::convert(unsigned long value) {
  12428. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  12429. }
  12430. std::string StringMaker<unsigned long long>::convert(unsigned long long value) {
  12431. ReusableStringStream rss;
  12432. rss << value;
  12433. if (value > Detail::hexThreshold) {
  12434. rss << " (0x" << std::hex << value << ')';
  12435. }
  12436. return rss.str();
  12437. }
  12438. std::string StringMaker<bool>::convert(bool b) {
  12439. return b ? "true" : "false";
  12440. }
  12441. std::string StringMaker<signed char>::convert(signed char value) {
  12442. if (value == '\r') {
  12443. return "'\\r'";
  12444. } else if (value == '\f') {
  12445. return "'\\f'";
  12446. } else if (value == '\n') {
  12447. return "'\\n'";
  12448. } else if (value == '\t') {
  12449. return "'\\t'";
  12450. } else if ('\0' <= value && value < ' ') {
  12451. return ::Catch::Detail::stringify(static_cast<unsigned int>(value));
  12452. } else {
  12453. char chstr[] = "' '";
  12454. chstr[1] = value;
  12455. return chstr;
  12456. }
  12457. }
  12458. std::string StringMaker<char>::convert(char c) {
  12459. return ::Catch::Detail::stringify(static_cast<signed char>(c));
  12460. }
  12461. std::string StringMaker<unsigned char>::convert(unsigned char c) {
  12462. return ::Catch::Detail::stringify(static_cast<char>(c));
  12463. }
  12464. std::string StringMaker<std::nullptr_t>::convert(std::nullptr_t) {
  12465. return "nullptr";
  12466. }
  12467. int StringMaker<float>::precision = 5;
  12468. std::string StringMaker<float>::convert(float value) {
  12469. return fpToString(value, precision) + 'f';
  12470. }
  12471. int StringMaker<double>::precision = 10;
  12472. std::string StringMaker<double>::convert(double value) {
  12473. return fpToString(value, precision);
  12474. }
  12475. std::string ratio_string<std::atto>::symbol() { return "a"; }
  12476. std::string ratio_string<std::femto>::symbol() { return "f"; }
  12477. std::string ratio_string<std::pico>::symbol() { return "p"; }
  12478. std::string ratio_string<std::nano>::symbol() { return "n"; }
  12479. std::string ratio_string<std::micro>::symbol() { return "u"; }
  12480. std::string ratio_string<std::milli>::symbol() { return "m"; }
  12481. } // end namespace Catch
  12482. #if defined(__clang__)
  12483. # pragma clang diagnostic pop
  12484. #endif
  12485. // end catch_tostring.cpp
  12486. // start catch_totals.cpp
  12487. namespace Catch {
  12488. Counts Counts::operator - ( Counts const& other ) const {
  12489. Counts diff;
  12490. diff.passed = passed - other.passed;
  12491. diff.failed = failed - other.failed;
  12492. diff.failedButOk = failedButOk - other.failedButOk;
  12493. return diff;
  12494. }
  12495. Counts& Counts::operator += ( Counts const& other ) {
  12496. passed += other.passed;
  12497. failed += other.failed;
  12498. failedButOk += other.failedButOk;
  12499. return *this;
  12500. }
  12501. std::size_t Counts::total() const {
  12502. return passed + failed + failedButOk;
  12503. }
  12504. bool Counts::allPassed() const {
  12505. return failed == 0 && failedButOk == 0;
  12506. }
  12507. bool Counts::allOk() const {
  12508. return failed == 0;
  12509. }
  12510. Totals Totals::operator - ( Totals const& other ) const {
  12511. Totals diff;
  12512. diff.assertions = assertions - other.assertions;
  12513. diff.testCases = testCases - other.testCases;
  12514. return diff;
  12515. }
  12516. Totals& Totals::operator += ( Totals const& other ) {
  12517. assertions += other.assertions;
  12518. testCases += other.testCases;
  12519. return *this;
  12520. }
  12521. Totals Totals::delta( Totals const& prevTotals ) const {
  12522. Totals diff = *this - prevTotals;
  12523. if( diff.assertions.failed > 0 )
  12524. ++diff.testCases.failed;
  12525. else if( diff.assertions.failedButOk > 0 )
  12526. ++diff.testCases.failedButOk;
  12527. else
  12528. ++diff.testCases.passed;
  12529. return diff;
  12530. }
  12531. }
  12532. // end catch_totals.cpp
  12533. // start catch_uncaught_exceptions.cpp
  12534. // start catch_config_uncaught_exceptions.hpp
  12535. // Copyright Catch2 Authors
  12536. // Distributed under the Boost Software License, Version 1.0.
  12537. // (See accompanying file LICENSE_1_0.txt or copy at
  12538. // https://www.boost.org/LICENSE_1_0.txt)
  12539. // SPDX-License-Identifier: BSL-1.0
  12540. #ifndef CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP
  12541. #define CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP
  12542. #if defined(_MSC_VER)
  12543. # if _MSC_VER >= 1900 // Visual Studio 2015 or newer
  12544. # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
  12545. # endif
  12546. #endif
  12547. #include <exception>
  12548. #if defined(__cpp_lib_uncaught_exceptions) \
  12549. && !defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
  12550. # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
  12551. #endif // __cpp_lib_uncaught_exceptions
  12552. #if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) \
  12553. && !defined(CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) \
  12554. && !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
  12555. # define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
  12556. #endif
  12557. #endif // CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP
  12558. // end catch_config_uncaught_exceptions.hpp
  12559. #include <exception>
  12560. namespace Catch {
  12561. bool uncaught_exceptions() {
  12562. #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  12563. return false;
  12564. #elif defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
  12565. return std::uncaught_exceptions() > 0;
  12566. #else
  12567. return std::uncaught_exception();
  12568. #endif
  12569. }
  12570. } // end namespace Catch
  12571. // end catch_uncaught_exceptions.cpp
  12572. // start catch_version.cpp
  12573. #include <ostream>
  12574. namespace Catch {
  12575. Version::Version
  12576. ( unsigned int _majorVersion,
  12577. unsigned int _minorVersion,
  12578. unsigned int _patchNumber,
  12579. char const * const _branchName,
  12580. unsigned int _buildNumber )
  12581. : majorVersion( _majorVersion ),
  12582. minorVersion( _minorVersion ),
  12583. patchNumber( _patchNumber ),
  12584. branchName( _branchName ),
  12585. buildNumber( _buildNumber )
  12586. {}
  12587. std::ostream& operator << ( std::ostream& os, Version const& version ) {
  12588. os << version.majorVersion << '.'
  12589. << version.minorVersion << '.'
  12590. << version.patchNumber;
  12591. // branchName is never null -> 0th char is \0 if it is empty
  12592. if (version.branchName[0]) {
  12593. os << '-' << version.branchName
  12594. << '.' << version.buildNumber;
  12595. }
  12596. return os;
  12597. }
  12598. Version const& libraryVersion() {
  12599. static Version version( 2, 13, 7, "", 0 );
  12600. return version;
  12601. }
  12602. }
  12603. // end catch_version.cpp
  12604. // start catch_wildcard_pattern.cpp
  12605. namespace Catch {
  12606. WildcardPattern::WildcardPattern( std::string const& pattern,
  12607. CaseSensitive::Choice caseSensitivity )
  12608. : m_caseSensitivity( caseSensitivity ),
  12609. m_pattern( normaliseString( pattern ) )
  12610. {
  12611. if( startsWith( m_pattern, '*' ) ) {
  12612. m_pattern = m_pattern.substr( 1 );
  12613. m_wildcard = WildcardAtStart;
  12614. }
  12615. if( endsWith( m_pattern, '*' ) ) {
  12616. m_pattern = m_pattern.substr( 0, m_pattern.size()-1 );
  12617. m_wildcard = static_cast<WildcardPosition>( m_wildcard | WildcardAtEnd );
  12618. }
  12619. }
  12620. bool WildcardPattern::matches( std::string const& str ) const {
  12621. switch( m_wildcard ) {
  12622. case NoWildcard:
  12623. return m_pattern == normaliseString( str );
  12624. case WildcardAtStart:
  12625. return endsWith( normaliseString( str ), m_pattern );
  12626. case WildcardAtEnd:
  12627. return startsWith( normaliseString( str ), m_pattern );
  12628. case WildcardAtBothEnds:
  12629. return contains( normaliseString( str ), m_pattern );
  12630. default:
  12631. CATCH_INTERNAL_ERROR( "Unknown enum" );
  12632. }
  12633. }
  12634. std::string WildcardPattern::normaliseString( std::string const& str ) const {
  12635. return trim( m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str );
  12636. }
  12637. }
  12638. // end catch_wildcard_pattern.cpp
  12639. // start catch_xmlwriter.cpp
  12640. #include <iomanip>
  12641. #include <type_traits>
  12642. namespace Catch {
  12643. namespace {
  12644. size_t trailingBytes(unsigned char c) {
  12645. if ((c & 0xE0) == 0xC0) {
  12646. return 2;
  12647. }
  12648. if ((c & 0xF0) == 0xE0) {
  12649. return 3;
  12650. }
  12651. if ((c & 0xF8) == 0xF0) {
  12652. return 4;
  12653. }
  12654. CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
  12655. }
  12656. uint32_t headerValue(unsigned char c) {
  12657. if ((c & 0xE0) == 0xC0) {
  12658. return c & 0x1F;
  12659. }
  12660. if ((c & 0xF0) == 0xE0) {
  12661. return c & 0x0F;
  12662. }
  12663. if ((c & 0xF8) == 0xF0) {
  12664. return c & 0x07;
  12665. }
  12666. CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
  12667. }
  12668. void hexEscapeChar(std::ostream& os, unsigned char c) {
  12669. std::ios_base::fmtflags f(os.flags());
  12670. os << "\\x"
  12671. << std::uppercase << std::hex << std::setfill('0') << std::setw(2)
  12672. << static_cast<int>(c);
  12673. os.flags(f);
  12674. }
  12675. bool shouldNewline(XmlFormatting fmt) {
  12676. return !!(static_cast<std::underlying_type<XmlFormatting>::type>(fmt & XmlFormatting::Newline));
  12677. }
  12678. bool shouldIndent(XmlFormatting fmt) {
  12679. return !!(static_cast<std::underlying_type<XmlFormatting>::type>(fmt & XmlFormatting::Indent));
  12680. }
  12681. } // anonymous namespace
  12682. XmlFormatting operator | (XmlFormatting lhs, XmlFormatting rhs) {
  12683. return static_cast<XmlFormatting>(
  12684. static_cast<std::underlying_type<XmlFormatting>::type>(lhs) |
  12685. static_cast<std::underlying_type<XmlFormatting>::type>(rhs)
  12686. );
  12687. }
  12688. XmlFormatting operator & (XmlFormatting lhs, XmlFormatting rhs) {
  12689. return static_cast<XmlFormatting>(
  12690. static_cast<std::underlying_type<XmlFormatting>::type>(lhs) &
  12691. static_cast<std::underlying_type<XmlFormatting>::type>(rhs)
  12692. );
  12693. }
  12694. XmlEncode::XmlEncode( std::string const& str, ForWhat forWhat )
  12695. : m_str( str ),
  12696. m_forWhat( forWhat )
  12697. {}
  12698. void XmlEncode::encodeTo( std::ostream& os ) const {
  12699. // Apostrophe escaping not necessary if we always use " to write attributes
  12700. // (see: http://www.w3.org/TR/xml/#syntax)
  12701. for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) {
  12702. unsigned char c = m_str[idx];
  12703. switch (c) {
  12704. case '<': os << "&lt;"; break;
  12705. case '&': os << "&amp;"; break;
  12706. case '>':
  12707. // See: http://www.w3.org/TR/xml/#syntax
  12708. if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']')
  12709. os << "&gt;";
  12710. else
  12711. os << c;
  12712. break;
  12713. case '\"':
  12714. if (m_forWhat == ForAttributes)
  12715. os << "&quot;";
  12716. else
  12717. os << c;
  12718. break;
  12719. default:
  12720. // Check for control characters and invalid utf-8
  12721. // Escape control characters in standard ascii
  12722. // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0
  12723. if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) {
  12724. hexEscapeChar(os, c);
  12725. break;
  12726. }
  12727. // Plain ASCII: Write it to stream
  12728. if (c < 0x7F) {
  12729. os << c;
  12730. break;
  12731. }
  12732. // UTF-8 territory
  12733. // Check if the encoding is valid and if it is not, hex escape bytes.
  12734. // Important: We do not check the exact decoded values for validity, only the encoding format
  12735. // First check that this bytes is a valid lead byte:
  12736. // This means that it is not encoded as 1111 1XXX
  12737. // Or as 10XX XXXX
  12738. if (c < 0xC0 ||
  12739. c >= 0xF8) {
  12740. hexEscapeChar(os, c);
  12741. break;
  12742. }
  12743. auto encBytes = trailingBytes(c);
  12744. // Are there enough bytes left to avoid accessing out-of-bounds memory?
  12745. if (idx + encBytes - 1 >= m_str.size()) {
  12746. hexEscapeChar(os, c);
  12747. break;
  12748. }
  12749. // The header is valid, check data
  12750. // The next encBytes bytes must together be a valid utf-8
  12751. // This means: bitpattern 10XX XXXX and the extracted value is sane (ish)
  12752. bool valid = true;
  12753. uint32_t value = headerValue(c);
  12754. for (std::size_t n = 1; n < encBytes; ++n) {
  12755. unsigned char nc = m_str[idx + n];
  12756. valid &= ((nc & 0xC0) == 0x80);
  12757. value = (value << 6) | (nc & 0x3F);
  12758. }
  12759. if (
  12760. // Wrong bit pattern of following bytes
  12761. (!valid) ||
  12762. // Overlong encodings
  12763. (value < 0x80) ||
  12764. (0x80 <= value && value < 0x800 && encBytes > 2) ||
  12765. (0x800 < value && value < 0x10000 && encBytes > 3) ||
  12766. // Encoded value out of range
  12767. (value >= 0x110000)
  12768. ) {
  12769. hexEscapeChar(os, c);
  12770. break;
  12771. }
  12772. // If we got here, this is in fact a valid(ish) utf-8 sequence
  12773. for (std::size_t n = 0; n < encBytes; ++n) {
  12774. os << m_str[idx + n];
  12775. }
  12776. idx += encBytes - 1;
  12777. break;
  12778. }
  12779. }
  12780. }
  12781. std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) {
  12782. xmlEncode.encodeTo( os );
  12783. return os;
  12784. }
  12785. XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer, XmlFormatting fmt )
  12786. : m_writer( writer ),
  12787. m_fmt(fmt)
  12788. {}
  12789. XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept
  12790. : m_writer( other.m_writer ),
  12791. m_fmt(other.m_fmt)
  12792. {
  12793. other.m_writer = nullptr;
  12794. other.m_fmt = XmlFormatting::None;
  12795. }
  12796. XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) noexcept {
  12797. if ( m_writer ) {
  12798. m_writer->endElement();
  12799. }
  12800. m_writer = other.m_writer;
  12801. other.m_writer = nullptr;
  12802. m_fmt = other.m_fmt;
  12803. other.m_fmt = XmlFormatting::None;
  12804. return *this;
  12805. }
  12806. XmlWriter::ScopedElement::~ScopedElement() {
  12807. if (m_writer) {
  12808. m_writer->endElement(m_fmt);
  12809. }
  12810. }
  12811. XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string const& text, XmlFormatting fmt ) {
  12812. m_writer->writeText( text, fmt );
  12813. return *this;
  12814. }
  12815. XmlWriter::XmlWriter( std::ostream& os ) : m_os( os )
  12816. {
  12817. writeDeclaration();
  12818. }
  12819. XmlWriter::~XmlWriter() {
  12820. while (!m_tags.empty()) {
  12821. endElement();
  12822. }
  12823. newlineIfNecessary();
  12824. }
  12825. XmlWriter& XmlWriter::startElement( std::string const& name, XmlFormatting fmt ) {
  12826. ensureTagClosed();
  12827. newlineIfNecessary();
  12828. if (shouldIndent(fmt)) {
  12829. m_os << m_indent;
  12830. m_indent += " ";
  12831. }
  12832. m_os << '<' << name;
  12833. m_tags.push_back( name );
  12834. m_tagIsOpen = true;
  12835. applyFormatting(fmt);
  12836. return *this;
  12837. }
  12838. XmlWriter::ScopedElement XmlWriter::scopedElement( std::string const& name, XmlFormatting fmt ) {
  12839. ScopedElement scoped( this, fmt );
  12840. startElement( name, fmt );
  12841. return scoped;
  12842. }
  12843. XmlWriter& XmlWriter::endElement(XmlFormatting fmt) {
  12844. m_indent = m_indent.substr(0, m_indent.size() - 2);
  12845. if( m_tagIsOpen ) {
  12846. m_os << "/>";
  12847. m_tagIsOpen = false;
  12848. } else {
  12849. newlineIfNecessary();
  12850. if (shouldIndent(fmt)) {
  12851. m_os << m_indent;
  12852. }
  12853. m_os << "</" << m_tags.back() << ">";
  12854. }
  12855. m_os << std::flush;
  12856. applyFormatting(fmt);
  12857. m_tags.pop_back();
  12858. return *this;
  12859. }
  12860. XmlWriter& XmlWriter::writeAttribute( std::string const& name, std::string const& attribute ) {
  12861. if( !name.empty() && !attribute.empty() )
  12862. m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"';
  12863. return *this;
  12864. }
  12865. XmlWriter& XmlWriter::writeAttribute( std::string const& name, bool attribute ) {
  12866. m_os << ' ' << name << "=\"" << ( attribute ? "true" : "false" ) << '"';
  12867. return *this;
  12868. }
  12869. XmlWriter& XmlWriter::writeText( std::string const& text, XmlFormatting fmt) {
  12870. if( !text.empty() ){
  12871. bool tagWasOpen = m_tagIsOpen;
  12872. ensureTagClosed();
  12873. if (tagWasOpen && shouldIndent(fmt)) {
  12874. m_os << m_indent;
  12875. }
  12876. m_os << XmlEncode( text );
  12877. applyFormatting(fmt);
  12878. }
  12879. return *this;
  12880. }
  12881. XmlWriter& XmlWriter::writeComment( std::string const& text, XmlFormatting fmt) {
  12882. ensureTagClosed();
  12883. if (shouldIndent(fmt)) {
  12884. m_os << m_indent;
  12885. }
  12886. m_os << "<!--" << text << "-->";
  12887. applyFormatting(fmt);
  12888. return *this;
  12889. }
  12890. void XmlWriter::writeStylesheetRef( std::string const& url ) {
  12891. m_os << "<?xml-stylesheet type=\"text/xsl\" href=\"" << url << "\"?>\n";
  12892. }
  12893. XmlWriter& XmlWriter::writeBlankLine() {
  12894. ensureTagClosed();
  12895. m_os << '\n';
  12896. return *this;
  12897. }
  12898. void XmlWriter::ensureTagClosed() {
  12899. if( m_tagIsOpen ) {
  12900. m_os << '>' << std::flush;
  12901. newlineIfNecessary();
  12902. m_tagIsOpen = false;
  12903. }
  12904. }
  12905. void XmlWriter::applyFormatting(XmlFormatting fmt) {
  12906. m_needsNewline = shouldNewline(fmt);
  12907. }
  12908. void XmlWriter::writeDeclaration() {
  12909. m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
  12910. }
  12911. void XmlWriter::newlineIfNecessary() {
  12912. if( m_needsNewline ) {
  12913. m_os << std::endl;
  12914. m_needsNewline = false;
  12915. }
  12916. }
  12917. }
  12918. // end catch_xmlwriter.cpp
  12919. // start catch_reporter_bases.cpp
  12920. #include <cstring>
  12921. #include <cfloat>
  12922. #include <cstdio>
  12923. #include <cassert>
  12924. #include <memory>
  12925. namespace Catch {
  12926. void prepareExpandedExpression(AssertionResult& result) {
  12927. result.getExpandedExpression();
  12928. }
  12929. // Because formatting using c++ streams is stateful, drop down to C is required
  12930. // Alternatively we could use stringstream, but its performance is... not good.
  12931. std::string getFormattedDuration( double duration ) {
  12932. // Max exponent + 1 is required to represent the whole part
  12933. // + 1 for decimal point
  12934. // + 3 for the 3 decimal places
  12935. // + 1 for null terminator
  12936. const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1;
  12937. char buffer[maxDoubleSize];
  12938. // Save previous errno, to prevent sprintf from overwriting it
  12939. ErrnoGuard guard;
  12940. #ifdef _MSC_VER
  12941. sprintf_s(buffer, "%.3f", duration);
  12942. #else
  12943. std::sprintf(buffer, "%.3f", duration);
  12944. #endif
  12945. return std::string(buffer);
  12946. }
  12947. bool shouldShowDuration( IConfig const& config, double duration ) {
  12948. if ( config.showDurations() == ShowDurations::Always ) {
  12949. return true;
  12950. }
  12951. if ( config.showDurations() == ShowDurations::Never ) {
  12952. return false;
  12953. }
  12954. const double min = config.minDuration();
  12955. return min >= 0 && duration >= min;
  12956. }
  12957. std::string serializeFilters( std::vector<std::string> const& container ) {
  12958. ReusableStringStream oss;
  12959. bool first = true;
  12960. for (auto&& filter : container)
  12961. {
  12962. if (!first)
  12963. oss << ' ';
  12964. else
  12965. first = false;
  12966. oss << filter;
  12967. }
  12968. return oss.str();
  12969. }
  12970. TestEventListenerBase::TestEventListenerBase(ReporterConfig const & _config)
  12971. :StreamingReporterBase(_config) {}
  12972. std::set<Verbosity> TestEventListenerBase::getSupportedVerbosities() {
  12973. return { Verbosity::Quiet, Verbosity::Normal, Verbosity::High };
  12974. }
  12975. void TestEventListenerBase::assertionStarting(AssertionInfo const &) {}
  12976. bool TestEventListenerBase::assertionEnded(AssertionStats const &) {
  12977. return false;
  12978. }
  12979. } // end namespace Catch
  12980. // end catch_reporter_bases.cpp
  12981. // start catch_reporter_compact.cpp
  12982. namespace {
  12983. #ifdef CATCH_PLATFORM_MAC
  12984. const char* failedString() { return "FAILED"; }
  12985. const char* passedString() { return "PASSED"; }
  12986. #else
  12987. const char* failedString() { return "failed"; }
  12988. const char* passedString() { return "passed"; }
  12989. #endif
  12990. // Colour::LightGrey
  12991. Catch::Colour::Code dimColour() { return Catch::Colour::FileName; }
  12992. std::string bothOrAll( std::size_t count ) {
  12993. return count == 1 ? std::string() :
  12994. count == 2 ? "both " : "all " ;
  12995. }
  12996. } // anon namespace
  12997. namespace Catch {
  12998. namespace {
  12999. // Colour, message variants:
  13000. // - white: No tests ran.
  13001. // - red: Failed [both/all] N test cases, failed [both/all] M assertions.
  13002. // - white: Passed [both/all] N test cases (no assertions).
  13003. // - red: Failed N tests cases, failed M assertions.
  13004. // - green: Passed [both/all] N tests cases with M assertions.
  13005. void printTotals(std::ostream& out, const Totals& totals) {
  13006. if (totals.testCases.total() == 0) {
  13007. out << "No tests ran.";
  13008. } else if (totals.testCases.failed == totals.testCases.total()) {
  13009. Colour colour(Colour::ResultError);
  13010. const std::string qualify_assertions_failed =
  13011. totals.assertions.failed == totals.assertions.total() ?
  13012. bothOrAll(totals.assertions.failed) : std::string();
  13013. out <<
  13014. "Failed " << bothOrAll(totals.testCases.failed)
  13015. << pluralise(totals.testCases.failed, "test case") << ", "
  13016. "failed " << qualify_assertions_failed <<
  13017. pluralise(totals.assertions.failed, "assertion") << '.';
  13018. } else if (totals.assertions.total() == 0) {
  13019. out <<
  13020. "Passed " << bothOrAll(totals.testCases.total())
  13021. << pluralise(totals.testCases.total(), "test case")
  13022. << " (no assertions).";
  13023. } else if (totals.assertions.failed) {
  13024. Colour colour(Colour::ResultError);
  13025. out <<
  13026. "Failed " << pluralise(totals.testCases.failed, "test case") << ", "
  13027. "failed " << pluralise(totals.assertions.failed, "assertion") << '.';
  13028. } else {
  13029. Colour colour(Colour::ResultSuccess);
  13030. out <<
  13031. "Passed " << bothOrAll(totals.testCases.passed)
  13032. << pluralise(totals.testCases.passed, "test case") <<
  13033. " with " << pluralise(totals.assertions.passed, "assertion") << '.';
  13034. }
  13035. }
  13036. // Implementation of CompactReporter formatting
  13037. class AssertionPrinter {
  13038. public:
  13039. AssertionPrinter& operator= (AssertionPrinter const&) = delete;
  13040. AssertionPrinter(AssertionPrinter const&) = delete;
  13041. AssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
  13042. : stream(_stream)
  13043. , result(_stats.assertionResult)
  13044. , messages(_stats.infoMessages)
  13045. , itMessage(_stats.infoMessages.begin())
  13046. , printInfoMessages(_printInfoMessages) {}
  13047. void print() {
  13048. printSourceInfo();
  13049. itMessage = messages.begin();
  13050. switch (result.getResultType()) {
  13051. case ResultWas::Ok:
  13052. printResultType(Colour::ResultSuccess, passedString());
  13053. printOriginalExpression();
  13054. printReconstructedExpression();
  13055. if (!result.hasExpression())
  13056. printRemainingMessages(Colour::None);
  13057. else
  13058. printRemainingMessages();
  13059. break;
  13060. case ResultWas::ExpressionFailed:
  13061. if (result.isOk())
  13062. printResultType(Colour::ResultSuccess, failedString() + std::string(" - but was ok"));
  13063. else
  13064. printResultType(Colour::Error, failedString());
  13065. printOriginalExpression();
  13066. printReconstructedExpression();
  13067. printRemainingMessages();
  13068. break;
  13069. case ResultWas::ThrewException:
  13070. printResultType(Colour::Error, failedString());
  13071. printIssue("unexpected exception with message:");
  13072. printMessage();
  13073. printExpressionWas();
  13074. printRemainingMessages();
  13075. break;
  13076. case ResultWas::FatalErrorCondition:
  13077. printResultType(Colour::Error, failedString());
  13078. printIssue("fatal error condition with message:");
  13079. printMessage();
  13080. printExpressionWas();
  13081. printRemainingMessages();
  13082. break;
  13083. case ResultWas::DidntThrowException:
  13084. printResultType(Colour::Error, failedString());
  13085. printIssue("expected exception, got none");
  13086. printExpressionWas();
  13087. printRemainingMessages();
  13088. break;
  13089. case ResultWas::Info:
  13090. printResultType(Colour::None, "info");
  13091. printMessage();
  13092. printRemainingMessages();
  13093. break;
  13094. case ResultWas::Warning:
  13095. printResultType(Colour::None, "warning");
  13096. printMessage();
  13097. printRemainingMessages();
  13098. break;
  13099. case ResultWas::ExplicitFailure:
  13100. printResultType(Colour::Error, failedString());
  13101. printIssue("explicitly");
  13102. printRemainingMessages(Colour::None);
  13103. break;
  13104. // These cases are here to prevent compiler warnings
  13105. case ResultWas::Unknown:
  13106. case ResultWas::FailureBit:
  13107. case ResultWas::Exception:
  13108. printResultType(Colour::Error, "** internal error **");
  13109. break;
  13110. }
  13111. }
  13112. private:
  13113. void printSourceInfo() const {
  13114. Colour colourGuard(Colour::FileName);
  13115. stream << result.getSourceInfo() << ':';
  13116. }
  13117. void printResultType(Colour::Code colour, std::string const& passOrFail) const {
  13118. if (!passOrFail.empty()) {
  13119. {
  13120. Colour colourGuard(colour);
  13121. stream << ' ' << passOrFail;
  13122. }
  13123. stream << ':';
  13124. }
  13125. }
  13126. void printIssue(std::string const& issue) const {
  13127. stream << ' ' << issue;
  13128. }
  13129. void printExpressionWas() {
  13130. if (result.hasExpression()) {
  13131. stream << ';';
  13132. {
  13133. Colour colour(dimColour());
  13134. stream << " expression was:";
  13135. }
  13136. printOriginalExpression();
  13137. }
  13138. }
  13139. void printOriginalExpression() const {
  13140. if (result.hasExpression()) {
  13141. stream << ' ' << result.getExpression();
  13142. }
  13143. }
  13144. void printReconstructedExpression() const {
  13145. if (result.hasExpandedExpression()) {
  13146. {
  13147. Colour colour(dimColour());
  13148. stream << " for: ";
  13149. }
  13150. stream << result.getExpandedExpression();
  13151. }
  13152. }
  13153. void printMessage() {
  13154. if (itMessage != messages.end()) {
  13155. stream << " '" << itMessage->message << '\'';
  13156. ++itMessage;
  13157. }
  13158. }
  13159. void printRemainingMessages(Colour::Code colour = dimColour()) {
  13160. if (itMessage == messages.end())
  13161. return;
  13162. const auto itEnd = messages.cend();
  13163. const auto N = static_cast<std::size_t>(std::distance(itMessage, itEnd));
  13164. {
  13165. Colour colourGuard(colour);
  13166. stream << " with " << pluralise(N, "message") << ':';
  13167. }
  13168. while (itMessage != itEnd) {
  13169. // If this assertion is a warning ignore any INFO messages
  13170. if (printInfoMessages || itMessage->type != ResultWas::Info) {
  13171. printMessage();
  13172. if (itMessage != itEnd) {
  13173. Colour colourGuard(dimColour());
  13174. stream << " and";
  13175. }
  13176. continue;
  13177. }
  13178. ++itMessage;
  13179. }
  13180. }
  13181. private:
  13182. std::ostream& stream;
  13183. AssertionResult const& result;
  13184. std::vector<MessageInfo> messages;
  13185. std::vector<MessageInfo>::const_iterator itMessage;
  13186. bool printInfoMessages;
  13187. };
  13188. } // anon namespace
  13189. std::string CompactReporter::getDescription() {
  13190. return "Reports test results on a single line, suitable for IDEs";
  13191. }
  13192. void CompactReporter::noMatchingTestCases( std::string const& spec ) {
  13193. stream << "No test cases matched '" << spec << '\'' << std::endl;
  13194. }
  13195. void CompactReporter::assertionStarting( AssertionInfo const& ) {}
  13196. bool CompactReporter::assertionEnded( AssertionStats const& _assertionStats ) {
  13197. AssertionResult const& result = _assertionStats.assertionResult;
  13198. bool printInfoMessages = true;
  13199. // Drop out if result was successful and we're not printing those
  13200. if( !m_config->includeSuccessfulResults() && result.isOk() ) {
  13201. if( result.getResultType() != ResultWas::Warning )
  13202. return false;
  13203. printInfoMessages = false;
  13204. }
  13205. AssertionPrinter printer( stream, _assertionStats, printInfoMessages );
  13206. printer.print();
  13207. stream << std::endl;
  13208. return true;
  13209. }
  13210. void CompactReporter::sectionEnded(SectionStats const& _sectionStats) {
  13211. double dur = _sectionStats.durationInSeconds;
  13212. if ( shouldShowDuration( *m_config, dur ) ) {
  13213. stream << getFormattedDuration( dur ) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  13214. }
  13215. }
  13216. void CompactReporter::testRunEnded( TestRunStats const& _testRunStats ) {
  13217. printTotals( stream, _testRunStats.totals );
  13218. stream << '\n' << std::endl;
  13219. StreamingReporterBase::testRunEnded( _testRunStats );
  13220. }
  13221. CompactReporter::~CompactReporter() {}
  13222. CATCH_REGISTER_REPORTER( "compact", CompactReporter )
  13223. } // end namespace Catch
  13224. // end catch_reporter_compact.cpp
  13225. // start catch_reporter_console.cpp
  13226. #include <cfloat>
  13227. #include <cstdio>
  13228. #if defined(_MSC_VER)
  13229. #pragma warning(push)
  13230. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  13231. // Note that 4062 (not all labels are handled and default is missing) is enabled
  13232. #endif
  13233. #if defined(__clang__)
  13234. # pragma clang diagnostic push
  13235. // For simplicity, benchmarking-only helpers are always enabled
  13236. # pragma clang diagnostic ignored "-Wunused-function"
  13237. #endif
  13238. namespace Catch {
  13239. namespace {
  13240. // Formatter impl for ConsoleReporter
  13241. class ConsoleAssertionPrinter {
  13242. public:
  13243. ConsoleAssertionPrinter& operator= (ConsoleAssertionPrinter const&) = delete;
  13244. ConsoleAssertionPrinter(ConsoleAssertionPrinter const&) = delete;
  13245. ConsoleAssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
  13246. : stream(_stream),
  13247. stats(_stats),
  13248. result(_stats.assertionResult),
  13249. colour(Colour::None),
  13250. message(result.getMessage()),
  13251. messages(_stats.infoMessages),
  13252. printInfoMessages(_printInfoMessages) {
  13253. switch (result.getResultType()) {
  13254. case ResultWas::Ok:
  13255. colour = Colour::Success;
  13256. passOrFail = "PASSED";
  13257. //if( result.hasMessage() )
  13258. if (_stats.infoMessages.size() == 1)
  13259. messageLabel = "with message";
  13260. if (_stats.infoMessages.size() > 1)
  13261. messageLabel = "with messages";
  13262. break;
  13263. case ResultWas::ExpressionFailed:
  13264. if (result.isOk()) {
  13265. colour = Colour::Success;
  13266. passOrFail = "FAILED - but was ok";
  13267. } else {
  13268. colour = Colour::Error;
  13269. passOrFail = "FAILED";
  13270. }
  13271. if (_stats.infoMessages.size() == 1)
  13272. messageLabel = "with message";
  13273. if (_stats.infoMessages.size() > 1)
  13274. messageLabel = "with messages";
  13275. break;
  13276. case ResultWas::ThrewException:
  13277. colour = Colour::Error;
  13278. passOrFail = "FAILED";
  13279. messageLabel = "due to unexpected exception with ";
  13280. if (_stats.infoMessages.size() == 1)
  13281. messageLabel += "message";
  13282. if (_stats.infoMessages.size() > 1)
  13283. messageLabel += "messages";
  13284. break;
  13285. case ResultWas::FatalErrorCondition:
  13286. colour = Colour::Error;
  13287. passOrFail = "FAILED";
  13288. messageLabel = "due to a fatal error condition";
  13289. break;
  13290. case ResultWas::DidntThrowException:
  13291. colour = Colour::Error;
  13292. passOrFail = "FAILED";
  13293. messageLabel = "because no exception was thrown where one was expected";
  13294. break;
  13295. case ResultWas::Info:
  13296. messageLabel = "info";
  13297. break;
  13298. case ResultWas::Warning:
  13299. messageLabel = "warning";
  13300. break;
  13301. case ResultWas::ExplicitFailure:
  13302. passOrFail = "FAILED";
  13303. colour = Colour::Error;
  13304. if (_stats.infoMessages.size() == 1)
  13305. messageLabel = "explicitly with message";
  13306. if (_stats.infoMessages.size() > 1)
  13307. messageLabel = "explicitly with messages";
  13308. break;
  13309. // These cases are here to prevent compiler warnings
  13310. case ResultWas::Unknown:
  13311. case ResultWas::FailureBit:
  13312. case ResultWas::Exception:
  13313. passOrFail = "** internal error **";
  13314. colour = Colour::Error;
  13315. break;
  13316. }
  13317. }
  13318. void print() const {
  13319. printSourceInfo();
  13320. if (stats.totals.assertions.total() > 0) {
  13321. printResultType();
  13322. printOriginalExpression();
  13323. printReconstructedExpression();
  13324. } else {
  13325. stream << '\n';
  13326. }
  13327. printMessage();
  13328. }
  13329. private:
  13330. void printResultType() const {
  13331. if (!passOrFail.empty()) {
  13332. Colour colourGuard(colour);
  13333. stream << passOrFail << ":\n";
  13334. }
  13335. }
  13336. void printOriginalExpression() const {
  13337. if (result.hasExpression()) {
  13338. Colour colourGuard(Colour::OriginalExpression);
  13339. stream << " ";
  13340. stream << result.getExpressionInMacro();
  13341. stream << '\n';
  13342. }
  13343. }
  13344. void printReconstructedExpression() const {
  13345. if (result.hasExpandedExpression()) {
  13346. stream << "with expansion:\n";
  13347. Colour colourGuard(Colour::ReconstructedExpression);
  13348. stream << Column(result.getExpandedExpression()).indent(2) << '\n';
  13349. }
  13350. }
  13351. void printMessage() const {
  13352. if (!messageLabel.empty())
  13353. stream << messageLabel << ':' << '\n';
  13354. for (auto const& msg : messages) {
  13355. // If this assertion is a warning ignore any INFO messages
  13356. if (printInfoMessages || msg.type != ResultWas::Info)
  13357. stream << Column(msg.message).indent(2) << '\n';
  13358. }
  13359. }
  13360. void printSourceInfo() const {
  13361. Colour colourGuard(Colour::FileName);
  13362. stream << result.getSourceInfo() << ": ";
  13363. }
  13364. std::ostream& stream;
  13365. AssertionStats const& stats;
  13366. AssertionResult const& result;
  13367. Colour::Code colour;
  13368. std::string passOrFail;
  13369. std::string messageLabel;
  13370. std::string message;
  13371. std::vector<MessageInfo> messages;
  13372. bool printInfoMessages;
  13373. };
  13374. std::size_t makeRatio(std::size_t number, std::size_t total) {
  13375. std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0;
  13376. return (ratio == 0 && number > 0) ? 1 : ratio;
  13377. }
  13378. std::size_t& findMax(std::size_t& i, std::size_t& j, std::size_t& k) {
  13379. if (i > j && i > k)
  13380. return i;
  13381. else if (j > k)
  13382. return j;
  13383. else
  13384. return k;
  13385. }
  13386. struct ColumnInfo {
  13387. enum Justification { Left, Right };
  13388. std::string name;
  13389. int width;
  13390. Justification justification;
  13391. };
  13392. struct ColumnBreak {};
  13393. struct RowBreak {};
  13394. class Duration {
  13395. enum class Unit {
  13396. Auto,
  13397. Nanoseconds,
  13398. Microseconds,
  13399. Milliseconds,
  13400. Seconds,
  13401. Minutes
  13402. };
  13403. static const uint64_t s_nanosecondsInAMicrosecond = 1000;
  13404. static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond;
  13405. static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond;
  13406. static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond;
  13407. double m_inNanoseconds;
  13408. Unit m_units;
  13409. public:
  13410. explicit Duration(double inNanoseconds, Unit units = Unit::Auto)
  13411. : m_inNanoseconds(inNanoseconds),
  13412. m_units(units) {
  13413. if (m_units == Unit::Auto) {
  13414. if (m_inNanoseconds < s_nanosecondsInAMicrosecond)
  13415. m_units = Unit::Nanoseconds;
  13416. else if (m_inNanoseconds < s_nanosecondsInAMillisecond)
  13417. m_units = Unit::Microseconds;
  13418. else if (m_inNanoseconds < s_nanosecondsInASecond)
  13419. m_units = Unit::Milliseconds;
  13420. else if (m_inNanoseconds < s_nanosecondsInAMinute)
  13421. m_units = Unit::Seconds;
  13422. else
  13423. m_units = Unit::Minutes;
  13424. }
  13425. }
  13426. auto value() const -> double {
  13427. switch (m_units) {
  13428. case Unit::Microseconds:
  13429. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMicrosecond);
  13430. case Unit::Milliseconds:
  13431. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMillisecond);
  13432. case Unit::Seconds:
  13433. return m_inNanoseconds / static_cast<double>(s_nanosecondsInASecond);
  13434. case Unit::Minutes:
  13435. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMinute);
  13436. default:
  13437. return m_inNanoseconds;
  13438. }
  13439. }
  13440. auto unitsAsString() const -> std::string {
  13441. switch (m_units) {
  13442. case Unit::Nanoseconds:
  13443. return "ns";
  13444. case Unit::Microseconds:
  13445. return "us";
  13446. case Unit::Milliseconds:
  13447. return "ms";
  13448. case Unit::Seconds:
  13449. return "s";
  13450. case Unit::Minutes:
  13451. return "m";
  13452. default:
  13453. return "** internal error **";
  13454. }
  13455. }
  13456. friend auto operator << (std::ostream& os, Duration const& duration) -> std::ostream& {
  13457. return os << duration.value() << ' ' << duration.unitsAsString();
  13458. }
  13459. };
  13460. } // end anon namespace
  13461. class TablePrinter {
  13462. std::ostream& m_os;
  13463. std::vector<ColumnInfo> m_columnInfos;
  13464. std::ostringstream m_oss;
  13465. int m_currentColumn = -1;
  13466. bool m_isOpen = false;
  13467. public:
  13468. TablePrinter( std::ostream& os, std::vector<ColumnInfo> columnInfos )
  13469. : m_os( os ),
  13470. m_columnInfos( std::move( columnInfos ) ) {}
  13471. auto columnInfos() const -> std::vector<ColumnInfo> const& {
  13472. return m_columnInfos;
  13473. }
  13474. void open() {
  13475. if (!m_isOpen) {
  13476. m_isOpen = true;
  13477. *this << RowBreak();
  13478. Columns headerCols;
  13479. Spacer spacer(2);
  13480. for (auto const& info : m_columnInfos) {
  13481. headerCols += Column(info.name).width(static_cast<std::size_t>(info.width - 2));
  13482. headerCols += spacer;
  13483. }
  13484. m_os << headerCols << '\n';
  13485. m_os << Catch::getLineOfChars<'-'>() << '\n';
  13486. }
  13487. }
  13488. void close() {
  13489. if (m_isOpen) {
  13490. *this << RowBreak();
  13491. m_os << std::endl;
  13492. m_isOpen = false;
  13493. }
  13494. }
  13495. template<typename T>
  13496. friend TablePrinter& operator << (TablePrinter& tp, T const& value) {
  13497. tp.m_oss << value;
  13498. return tp;
  13499. }
  13500. friend TablePrinter& operator << (TablePrinter& tp, ColumnBreak) {
  13501. auto colStr = tp.m_oss.str();
  13502. const auto strSize = colStr.size();
  13503. tp.m_oss.str("");
  13504. tp.open();
  13505. if (tp.m_currentColumn == static_cast<int>(tp.m_columnInfos.size() - 1)) {
  13506. tp.m_currentColumn = -1;
  13507. tp.m_os << '\n';
  13508. }
  13509. tp.m_currentColumn++;
  13510. auto colInfo = tp.m_columnInfos[tp.m_currentColumn];
  13511. auto padding = (strSize + 1 < static_cast<std::size_t>(colInfo.width))
  13512. ? std::string(colInfo.width - (strSize + 1), ' ')
  13513. : std::string();
  13514. if (colInfo.justification == ColumnInfo::Left)
  13515. tp.m_os << colStr << padding << ' ';
  13516. else
  13517. tp.m_os << padding << colStr << ' ';
  13518. return tp;
  13519. }
  13520. friend TablePrinter& operator << (TablePrinter& tp, RowBreak) {
  13521. if (tp.m_currentColumn > 0) {
  13522. tp.m_os << '\n';
  13523. tp.m_currentColumn = -1;
  13524. }
  13525. return tp;
  13526. }
  13527. };
  13528. ConsoleReporter::ConsoleReporter(ReporterConfig const& config)
  13529. : StreamingReporterBase(config),
  13530. m_tablePrinter(new TablePrinter(config.stream(),
  13531. [&config]() -> std::vector<ColumnInfo> {
  13532. if (config.fullConfig()->benchmarkNoAnalysis())
  13533. {
  13534. return{
  13535. { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, ColumnInfo::Left },
  13536. { " samples", 14, ColumnInfo::Right },
  13537. { " iterations", 14, ColumnInfo::Right },
  13538. { " mean", 14, ColumnInfo::Right }
  13539. };
  13540. }
  13541. else
  13542. {
  13543. return{
  13544. { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, ColumnInfo::Left },
  13545. { "samples mean std dev", 14, ColumnInfo::Right },
  13546. { "iterations low mean low std dev", 14, ColumnInfo::Right },
  13547. { "estimated high mean high std dev", 14, ColumnInfo::Right }
  13548. };
  13549. }
  13550. }())) {}
  13551. ConsoleReporter::~ConsoleReporter() = default;
  13552. std::string ConsoleReporter::getDescription() {
  13553. return "Reports test results as plain lines of text";
  13554. }
  13555. void ConsoleReporter::noMatchingTestCases(std::string const& spec) {
  13556. stream << "No test cases matched '" << spec << '\'' << std::endl;
  13557. }
  13558. void ConsoleReporter::reportInvalidArguments(std::string const&arg){
  13559. stream << "Invalid Filter: " << arg << std::endl;
  13560. }
  13561. void ConsoleReporter::assertionStarting(AssertionInfo const&) {}
  13562. bool ConsoleReporter::assertionEnded(AssertionStats const& _assertionStats) {
  13563. AssertionResult const& result = _assertionStats.assertionResult;
  13564. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  13565. // Drop out if result was successful but we're not printing them.
  13566. if (!includeResults && result.getResultType() != ResultWas::Warning)
  13567. return false;
  13568. lazyPrint();
  13569. ConsoleAssertionPrinter printer(stream, _assertionStats, includeResults);
  13570. printer.print();
  13571. stream << std::endl;
  13572. return true;
  13573. }
  13574. void ConsoleReporter::sectionStarting(SectionInfo const& _sectionInfo) {
  13575. m_tablePrinter->close();
  13576. m_headerPrinted = false;
  13577. StreamingReporterBase::sectionStarting(_sectionInfo);
  13578. }
  13579. void ConsoleReporter::sectionEnded(SectionStats const& _sectionStats) {
  13580. m_tablePrinter->close();
  13581. if (_sectionStats.missingAssertions) {
  13582. lazyPrint();
  13583. Colour colour(Colour::ResultError);
  13584. if (m_sectionStack.size() > 1)
  13585. stream << "\nNo assertions in section";
  13586. else
  13587. stream << "\nNo assertions in test case";
  13588. stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl;
  13589. }
  13590. double dur = _sectionStats.durationInSeconds;
  13591. if (shouldShowDuration(*m_config, dur)) {
  13592. stream << getFormattedDuration(dur) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  13593. }
  13594. if (m_headerPrinted) {
  13595. m_headerPrinted = false;
  13596. }
  13597. StreamingReporterBase::sectionEnded(_sectionStats);
  13598. }
  13599. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  13600. void ConsoleReporter::benchmarkPreparing(std::string const& name) {
  13601. lazyPrintWithoutClosingBenchmarkTable();
  13602. auto nameCol = Column(name).width(static_cast<std::size_t>(m_tablePrinter->columnInfos()[0].width - 2));
  13603. bool firstLine = true;
  13604. for (auto line : nameCol) {
  13605. if (!firstLine)
  13606. (*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak();
  13607. else
  13608. firstLine = false;
  13609. (*m_tablePrinter) << line << ColumnBreak();
  13610. }
  13611. }
  13612. void ConsoleReporter::benchmarkStarting(BenchmarkInfo const& info) {
  13613. (*m_tablePrinter) << info.samples << ColumnBreak()
  13614. << info.iterations << ColumnBreak();
  13615. if (!m_config->benchmarkNoAnalysis())
  13616. (*m_tablePrinter) << Duration(info.estimatedDuration) << ColumnBreak();
  13617. }
  13618. void ConsoleReporter::benchmarkEnded(BenchmarkStats<> const& stats) {
  13619. if (m_config->benchmarkNoAnalysis())
  13620. {
  13621. (*m_tablePrinter) << Duration(stats.mean.point.count()) << ColumnBreak();
  13622. }
  13623. else
  13624. {
  13625. (*m_tablePrinter) << ColumnBreak()
  13626. << Duration(stats.mean.point.count()) << ColumnBreak()
  13627. << Duration(stats.mean.lower_bound.count()) << ColumnBreak()
  13628. << Duration(stats.mean.upper_bound.count()) << ColumnBreak() << ColumnBreak()
  13629. << Duration(stats.standardDeviation.point.count()) << ColumnBreak()
  13630. << Duration(stats.standardDeviation.lower_bound.count()) << ColumnBreak()
  13631. << Duration(stats.standardDeviation.upper_bound.count()) << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak();
  13632. }
  13633. }
  13634. void ConsoleReporter::benchmarkFailed(std::string const& error) {
  13635. Colour colour(Colour::Red);
  13636. (*m_tablePrinter)
  13637. << "Benchmark failed (" << error << ')'
  13638. << ColumnBreak() << RowBreak();
  13639. }
  13640. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  13641. void ConsoleReporter::testCaseEnded(TestCaseStats const& _testCaseStats) {
  13642. m_tablePrinter->close();
  13643. StreamingReporterBase::testCaseEnded(_testCaseStats);
  13644. m_headerPrinted = false;
  13645. }
  13646. void ConsoleReporter::testGroupEnded(TestGroupStats const& _testGroupStats) {
  13647. if (currentGroupInfo.used) {
  13648. printSummaryDivider();
  13649. stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n";
  13650. printTotals(_testGroupStats.totals);
  13651. stream << '\n' << std::endl;
  13652. }
  13653. StreamingReporterBase::testGroupEnded(_testGroupStats);
  13654. }
  13655. void ConsoleReporter::testRunEnded(TestRunStats const& _testRunStats) {
  13656. printTotalsDivider(_testRunStats.totals);
  13657. printTotals(_testRunStats.totals);
  13658. stream << std::endl;
  13659. StreamingReporterBase::testRunEnded(_testRunStats);
  13660. }
  13661. void ConsoleReporter::testRunStarting(TestRunInfo const& _testInfo) {
  13662. StreamingReporterBase::testRunStarting(_testInfo);
  13663. printTestFilters();
  13664. }
  13665. void ConsoleReporter::lazyPrint() {
  13666. m_tablePrinter->close();
  13667. lazyPrintWithoutClosingBenchmarkTable();
  13668. }
  13669. void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() {
  13670. if (!currentTestRunInfo.used)
  13671. lazyPrintRunInfo();
  13672. if (!currentGroupInfo.used)
  13673. lazyPrintGroupInfo();
  13674. if (!m_headerPrinted) {
  13675. printTestCaseAndSectionHeader();
  13676. m_headerPrinted = true;
  13677. }
  13678. }
  13679. void ConsoleReporter::lazyPrintRunInfo() {
  13680. stream << '\n' << getLineOfChars<'~'>() << '\n';
  13681. Colour colour(Colour::SecondaryText);
  13682. stream << currentTestRunInfo->name
  13683. << " is a Catch v" << libraryVersion() << " host application.\n"
  13684. << "Run with -? for options\n\n";
  13685. if (m_config->rngSeed() != 0)
  13686. stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n";
  13687. currentTestRunInfo.used = true;
  13688. }
  13689. void ConsoleReporter::lazyPrintGroupInfo() {
  13690. if (!currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1) {
  13691. printClosedHeader("Group: " + currentGroupInfo->name);
  13692. currentGroupInfo.used = true;
  13693. }
  13694. }
  13695. void ConsoleReporter::printTestCaseAndSectionHeader() {
  13696. assert(!m_sectionStack.empty());
  13697. printOpenHeader(currentTestCaseInfo->name);
  13698. if (m_sectionStack.size() > 1) {
  13699. Colour colourGuard(Colour::Headers);
  13700. auto
  13701. it = m_sectionStack.begin() + 1, // Skip first section (test case)
  13702. itEnd = m_sectionStack.end();
  13703. for (; it != itEnd; ++it)
  13704. printHeaderString(it->name, 2);
  13705. }
  13706. SourceLineInfo lineInfo = m_sectionStack.back().lineInfo;
  13707. stream << getLineOfChars<'-'>() << '\n';
  13708. Colour colourGuard(Colour::FileName);
  13709. stream << lineInfo << '\n';
  13710. stream << getLineOfChars<'.'>() << '\n' << std::endl;
  13711. }
  13712. void ConsoleReporter::printClosedHeader(std::string const& _name) {
  13713. printOpenHeader(_name);
  13714. stream << getLineOfChars<'.'>() << '\n';
  13715. }
  13716. void ConsoleReporter::printOpenHeader(std::string const& _name) {
  13717. stream << getLineOfChars<'-'>() << '\n';
  13718. {
  13719. Colour colourGuard(Colour::Headers);
  13720. printHeaderString(_name);
  13721. }
  13722. }
  13723. // if string has a : in first line will set indent to follow it on
  13724. // subsequent lines
  13725. void ConsoleReporter::printHeaderString(std::string const& _string, std::size_t indent) {
  13726. std::size_t i = _string.find(": ");
  13727. if (i != std::string::npos)
  13728. i += 2;
  13729. else
  13730. i = 0;
  13731. stream << Column(_string).indent(indent + i).initialIndent(indent) << '\n';
  13732. }
  13733. struct SummaryColumn {
  13734. SummaryColumn( std::string _label, Colour::Code _colour )
  13735. : label( std::move( _label ) ),
  13736. colour( _colour ) {}
  13737. SummaryColumn addRow( std::size_t count ) {
  13738. ReusableStringStream rss;
  13739. rss << count;
  13740. std::string row = rss.str();
  13741. for (auto& oldRow : rows) {
  13742. while (oldRow.size() < row.size())
  13743. oldRow = ' ' + oldRow;
  13744. while (oldRow.size() > row.size())
  13745. row = ' ' + row;
  13746. }
  13747. rows.push_back(row);
  13748. return *this;
  13749. }
  13750. std::string label;
  13751. Colour::Code colour;
  13752. std::vector<std::string> rows;
  13753. };
  13754. void ConsoleReporter::printTotals( Totals const& totals ) {
  13755. if (totals.testCases.total() == 0) {
  13756. stream << Colour(Colour::Warning) << "No tests ran\n";
  13757. } else if (totals.assertions.total() > 0 && totals.testCases.allPassed()) {
  13758. stream << Colour(Colour::ResultSuccess) << "All tests passed";
  13759. stream << " ("
  13760. << pluralise(totals.assertions.passed, "assertion") << " in "
  13761. << pluralise(totals.testCases.passed, "test case") << ')'
  13762. << '\n';
  13763. } else {
  13764. std::vector<SummaryColumn> columns;
  13765. columns.push_back(SummaryColumn("", Colour::None)
  13766. .addRow(totals.testCases.total())
  13767. .addRow(totals.assertions.total()));
  13768. columns.push_back(SummaryColumn("passed", Colour::Success)
  13769. .addRow(totals.testCases.passed)
  13770. .addRow(totals.assertions.passed));
  13771. columns.push_back(SummaryColumn("failed", Colour::ResultError)
  13772. .addRow(totals.testCases.failed)
  13773. .addRow(totals.assertions.failed));
  13774. columns.push_back(SummaryColumn("failed as expected", Colour::ResultExpectedFailure)
  13775. .addRow(totals.testCases.failedButOk)
  13776. .addRow(totals.assertions.failedButOk));
  13777. printSummaryRow("test cases", columns, 0);
  13778. printSummaryRow("assertions", columns, 1);
  13779. }
  13780. }
  13781. void ConsoleReporter::printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row) {
  13782. for (auto col : cols) {
  13783. std::string value = col.rows[row];
  13784. if (col.label.empty()) {
  13785. stream << label << ": ";
  13786. if (value != "0")
  13787. stream << value;
  13788. else
  13789. stream << Colour(Colour::Warning) << "- none -";
  13790. } else if (value != "0") {
  13791. stream << Colour(Colour::LightGrey) << " | ";
  13792. stream << Colour(col.colour)
  13793. << value << ' ' << col.label;
  13794. }
  13795. }
  13796. stream << '\n';
  13797. }
  13798. void ConsoleReporter::printTotalsDivider(Totals const& totals) {
  13799. if (totals.testCases.total() > 0) {
  13800. std::size_t failedRatio = makeRatio(totals.testCases.failed, totals.testCases.total());
  13801. std::size_t failedButOkRatio = makeRatio(totals.testCases.failedButOk, totals.testCases.total());
  13802. std::size_t passedRatio = makeRatio(totals.testCases.passed, totals.testCases.total());
  13803. while (failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1)
  13804. findMax(failedRatio, failedButOkRatio, passedRatio)++;
  13805. while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1)
  13806. findMax(failedRatio, failedButOkRatio, passedRatio)--;
  13807. stream << Colour(Colour::Error) << std::string(failedRatio, '=');
  13808. stream << Colour(Colour::ResultExpectedFailure) << std::string(failedButOkRatio, '=');
  13809. if (totals.testCases.allPassed())
  13810. stream << Colour(Colour::ResultSuccess) << std::string(passedRatio, '=');
  13811. else
  13812. stream << Colour(Colour::Success) << std::string(passedRatio, '=');
  13813. } else {
  13814. stream << Colour(Colour::Warning) << std::string(CATCH_CONFIG_CONSOLE_WIDTH - 1, '=');
  13815. }
  13816. stream << '\n';
  13817. }
  13818. void ConsoleReporter::printSummaryDivider() {
  13819. stream << getLineOfChars<'-'>() << '\n';
  13820. }
  13821. void ConsoleReporter::printTestFilters() {
  13822. if (m_config->testSpec().hasFilters()) {
  13823. Colour guard(Colour::BrightYellow);
  13824. stream << "Filters: " << serializeFilters(m_config->getTestsOrTags()) << '\n';
  13825. }
  13826. }
  13827. CATCH_REGISTER_REPORTER("console", ConsoleReporter)
  13828. } // end namespace Catch
  13829. #if defined(_MSC_VER)
  13830. #pragma warning(pop)
  13831. #endif
  13832. #if defined(__clang__)
  13833. # pragma clang diagnostic pop
  13834. #endif
  13835. // end catch_reporter_console.cpp
  13836. // start catch_reporter_junit.cpp
  13837. #include <cassert>
  13838. #include <sstream>
  13839. #include <ctime>
  13840. #include <algorithm>
  13841. #include <iomanip>
  13842. namespace Catch {
  13843. namespace {
  13844. std::string getCurrentTimestamp() {
  13845. // Beware, this is not reentrant because of backward compatibility issues
  13846. // Also, UTC only, again because of backward compatibility (%z is C++11)
  13847. time_t rawtime;
  13848. std::time(&rawtime);
  13849. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  13850. #ifdef _MSC_VER
  13851. std::tm timeInfo = {};
  13852. gmtime_s(&timeInfo, &rawtime);
  13853. #else
  13854. std::tm* timeInfo;
  13855. timeInfo = std::gmtime(&rawtime);
  13856. #endif
  13857. char timeStamp[timeStampSize];
  13858. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  13859. #ifdef _MSC_VER
  13860. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  13861. #else
  13862. std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
  13863. #endif
  13864. return std::string(timeStamp, timeStampSize-1);
  13865. }
  13866. std::string fileNameTag(const std::vector<std::string> &tags) {
  13867. auto it = std::find_if(begin(tags),
  13868. end(tags),
  13869. [] (std::string const& tag) {return tag.front() == '#'; });
  13870. if (it != tags.end())
  13871. return it->substr(1);
  13872. return std::string();
  13873. }
  13874. // Formats the duration in seconds to 3 decimal places.
  13875. // This is done because some genius defined Maven Surefire schema
  13876. // in a way that only accepts 3 decimal places, and tools like
  13877. // Jenkins use that schema for validation JUnit reporter output.
  13878. std::string formatDuration( double seconds ) {
  13879. ReusableStringStream rss;
  13880. rss << std::fixed << std::setprecision( 3 ) << seconds;
  13881. return rss.str();
  13882. }
  13883. } // anonymous namespace
  13884. JunitReporter::JunitReporter( ReporterConfig const& _config )
  13885. : CumulativeReporterBase( _config ),
  13886. xml( _config.stream() )
  13887. {
  13888. m_reporterPrefs.shouldRedirectStdOut = true;
  13889. m_reporterPrefs.shouldReportAllAssertions = true;
  13890. }
  13891. JunitReporter::~JunitReporter() {}
  13892. std::string JunitReporter::getDescription() {
  13893. return "Reports test results in an XML format that looks like Ant's junitreport target";
  13894. }
  13895. void JunitReporter::noMatchingTestCases( std::string const& /*spec*/ ) {}
  13896. void JunitReporter::testRunStarting( TestRunInfo const& runInfo ) {
  13897. CumulativeReporterBase::testRunStarting( runInfo );
  13898. xml.startElement( "testsuites" );
  13899. }
  13900. void JunitReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  13901. suiteTimer.start();
  13902. stdOutForSuite.clear();
  13903. stdErrForSuite.clear();
  13904. unexpectedExceptions = 0;
  13905. CumulativeReporterBase::testGroupStarting( groupInfo );
  13906. }
  13907. void JunitReporter::testCaseStarting( TestCaseInfo const& testCaseInfo ) {
  13908. m_okToFail = testCaseInfo.okToFail();
  13909. }
  13910. bool JunitReporter::assertionEnded( AssertionStats const& assertionStats ) {
  13911. if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail )
  13912. unexpectedExceptions++;
  13913. return CumulativeReporterBase::assertionEnded( assertionStats );
  13914. }
  13915. void JunitReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  13916. stdOutForSuite += testCaseStats.stdOut;
  13917. stdErrForSuite += testCaseStats.stdErr;
  13918. CumulativeReporterBase::testCaseEnded( testCaseStats );
  13919. }
  13920. void JunitReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  13921. double suiteTime = suiteTimer.getElapsedSeconds();
  13922. CumulativeReporterBase::testGroupEnded( testGroupStats );
  13923. writeGroup( *m_testGroups.back(), suiteTime );
  13924. }
  13925. void JunitReporter::testRunEndedCumulative() {
  13926. xml.endElement();
  13927. }
  13928. void JunitReporter::writeGroup( TestGroupNode const& groupNode, double suiteTime ) {
  13929. XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" );
  13930. TestGroupStats const& stats = groupNode.value;
  13931. xml.writeAttribute( "name", stats.groupInfo.name );
  13932. xml.writeAttribute( "errors", unexpectedExceptions );
  13933. xml.writeAttribute( "failures", stats.totals.assertions.failed-unexpectedExceptions );
  13934. xml.writeAttribute( "tests", stats.totals.assertions.total() );
  13935. xml.writeAttribute( "hostname", "tbd" ); // !TBD
  13936. if( m_config->showDurations() == ShowDurations::Never )
  13937. xml.writeAttribute( "time", "" );
  13938. else
  13939. xml.writeAttribute( "time", formatDuration( suiteTime ) );
  13940. xml.writeAttribute( "timestamp", getCurrentTimestamp() );
  13941. // Write properties if there are any
  13942. if (m_config->hasTestFilters() || m_config->rngSeed() != 0) {
  13943. auto properties = xml.scopedElement("properties");
  13944. if (m_config->hasTestFilters()) {
  13945. xml.scopedElement("property")
  13946. .writeAttribute("name", "filters")
  13947. .writeAttribute("value", serializeFilters(m_config->getTestsOrTags()));
  13948. }
  13949. if (m_config->rngSeed() != 0) {
  13950. xml.scopedElement("property")
  13951. .writeAttribute("name", "random-seed")
  13952. .writeAttribute("value", m_config->rngSeed());
  13953. }
  13954. }
  13955. // Write test cases
  13956. for( auto const& child : groupNode.children )
  13957. writeTestCase( *child );
  13958. xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite ), XmlFormatting::Newline );
  13959. xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite ), XmlFormatting::Newline );
  13960. }
  13961. void JunitReporter::writeTestCase( TestCaseNode const& testCaseNode ) {
  13962. TestCaseStats const& stats = testCaseNode.value;
  13963. // All test cases have exactly one section - which represents the
  13964. // test case itself. That section may have 0-n nested sections
  13965. assert( testCaseNode.children.size() == 1 );
  13966. SectionNode const& rootSection = *testCaseNode.children.front();
  13967. std::string className = stats.testInfo.className;
  13968. if( className.empty() ) {
  13969. className = fileNameTag(stats.testInfo.tags);
  13970. if ( className.empty() )
  13971. className = "global";
  13972. }
  13973. if ( !m_config->name().empty() )
  13974. className = m_config->name() + "." + className;
  13975. writeSection( className, "", rootSection, stats.testInfo.okToFail() );
  13976. }
  13977. void JunitReporter::writeSection( std::string const& className,
  13978. std::string const& rootName,
  13979. SectionNode const& sectionNode,
  13980. bool testOkToFail) {
  13981. std::string name = trim( sectionNode.stats.sectionInfo.name );
  13982. if( !rootName.empty() )
  13983. name = rootName + '/' + name;
  13984. if( !sectionNode.assertions.empty() ||
  13985. !sectionNode.stdOut.empty() ||
  13986. !sectionNode.stdErr.empty() ) {
  13987. XmlWriter::ScopedElement e = xml.scopedElement( "testcase" );
  13988. if( className.empty() ) {
  13989. xml.writeAttribute( "classname", name );
  13990. xml.writeAttribute( "name", "root" );
  13991. }
  13992. else {
  13993. xml.writeAttribute( "classname", className );
  13994. xml.writeAttribute( "name", name );
  13995. }
  13996. xml.writeAttribute( "time", formatDuration( sectionNode.stats.durationInSeconds ) );
  13997. // This is not ideal, but it should be enough to mimic gtest's
  13998. // junit output.
  13999. // Ideally the JUnit reporter would also handle `skipTest`
  14000. // events and write those out appropriately.
  14001. xml.writeAttribute( "status", "run" );
  14002. if (sectionNode.stats.assertions.failedButOk) {
  14003. xml.scopedElement("skipped")
  14004. .writeAttribute("message", "TEST_CASE tagged with !mayfail");
  14005. }
  14006. writeAssertions( sectionNode );
  14007. if( !sectionNode.stdOut.empty() )
  14008. xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), XmlFormatting::Newline );
  14009. if( !sectionNode.stdErr.empty() )
  14010. xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), XmlFormatting::Newline );
  14011. }
  14012. for( auto const& childNode : sectionNode.childSections )
  14013. if( className.empty() )
  14014. writeSection( name, "", *childNode, testOkToFail );
  14015. else
  14016. writeSection( className, name, *childNode, testOkToFail );
  14017. }
  14018. void JunitReporter::writeAssertions( SectionNode const& sectionNode ) {
  14019. for( auto const& assertion : sectionNode.assertions )
  14020. writeAssertion( assertion );
  14021. }
  14022. void JunitReporter::writeAssertion( AssertionStats const& stats ) {
  14023. AssertionResult const& result = stats.assertionResult;
  14024. if( !result.isOk() ) {
  14025. std::string elementName;
  14026. switch( result.getResultType() ) {
  14027. case ResultWas::ThrewException:
  14028. case ResultWas::FatalErrorCondition:
  14029. elementName = "error";
  14030. break;
  14031. case ResultWas::ExplicitFailure:
  14032. case ResultWas::ExpressionFailed:
  14033. case ResultWas::DidntThrowException:
  14034. elementName = "failure";
  14035. break;
  14036. // We should never see these here:
  14037. case ResultWas::Info:
  14038. case ResultWas::Warning:
  14039. case ResultWas::Ok:
  14040. case ResultWas::Unknown:
  14041. case ResultWas::FailureBit:
  14042. case ResultWas::Exception:
  14043. elementName = "internalError";
  14044. break;
  14045. }
  14046. XmlWriter::ScopedElement e = xml.scopedElement( elementName );
  14047. xml.writeAttribute( "message", result.getExpression() );
  14048. xml.writeAttribute( "type", result.getTestMacroName() );
  14049. ReusableStringStream rss;
  14050. if (stats.totals.assertions.total() > 0) {
  14051. rss << "FAILED" << ":\n";
  14052. if (result.hasExpression()) {
  14053. rss << " ";
  14054. rss << result.getExpressionInMacro();
  14055. rss << '\n';
  14056. }
  14057. if (result.hasExpandedExpression()) {
  14058. rss << "with expansion:\n";
  14059. rss << Column(result.getExpandedExpression()).indent(2) << '\n';
  14060. }
  14061. } else {
  14062. rss << '\n';
  14063. }
  14064. if( !result.getMessage().empty() )
  14065. rss << result.getMessage() << '\n';
  14066. for( auto const& msg : stats.infoMessages )
  14067. if( msg.type == ResultWas::Info )
  14068. rss << msg.message << '\n';
  14069. rss << "at " << result.getSourceInfo();
  14070. xml.writeText( rss.str(), XmlFormatting::Newline );
  14071. }
  14072. }
  14073. CATCH_REGISTER_REPORTER( "junit", JunitReporter )
  14074. } // end namespace Catch
  14075. // end catch_reporter_junit.cpp
  14076. // start catch_reporter_listening.cpp
  14077. #include <cassert>
  14078. namespace Catch {
  14079. ListeningReporter::ListeningReporter() {
  14080. // We will assume that listeners will always want all assertions
  14081. m_preferences.shouldReportAllAssertions = true;
  14082. }
  14083. void ListeningReporter::addListener( IStreamingReporterPtr&& listener ) {
  14084. m_listeners.push_back( std::move( listener ) );
  14085. }
  14086. void ListeningReporter::addReporter(IStreamingReporterPtr&& reporter) {
  14087. assert(!m_reporter && "Listening reporter can wrap only 1 real reporter");
  14088. m_reporter = std::move( reporter );
  14089. m_preferences.shouldRedirectStdOut = m_reporter->getPreferences().shouldRedirectStdOut;
  14090. }
  14091. ReporterPreferences ListeningReporter::getPreferences() const {
  14092. return m_preferences;
  14093. }
  14094. std::set<Verbosity> ListeningReporter::getSupportedVerbosities() {
  14095. return std::set<Verbosity>{ };
  14096. }
  14097. void ListeningReporter::noMatchingTestCases( std::string const& spec ) {
  14098. for ( auto const& listener : m_listeners ) {
  14099. listener->noMatchingTestCases( spec );
  14100. }
  14101. m_reporter->noMatchingTestCases( spec );
  14102. }
  14103. void ListeningReporter::reportInvalidArguments(std::string const&arg){
  14104. for ( auto const& listener : m_listeners ) {
  14105. listener->reportInvalidArguments( arg );
  14106. }
  14107. m_reporter->reportInvalidArguments( arg );
  14108. }
  14109. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  14110. void ListeningReporter::benchmarkPreparing( std::string const& name ) {
  14111. for (auto const& listener : m_listeners) {
  14112. listener->benchmarkPreparing(name);
  14113. }
  14114. m_reporter->benchmarkPreparing(name);
  14115. }
  14116. void ListeningReporter::benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) {
  14117. for ( auto const& listener : m_listeners ) {
  14118. listener->benchmarkStarting( benchmarkInfo );
  14119. }
  14120. m_reporter->benchmarkStarting( benchmarkInfo );
  14121. }
  14122. void ListeningReporter::benchmarkEnded( BenchmarkStats<> const& benchmarkStats ) {
  14123. for ( auto const& listener : m_listeners ) {
  14124. listener->benchmarkEnded( benchmarkStats );
  14125. }
  14126. m_reporter->benchmarkEnded( benchmarkStats );
  14127. }
  14128. void ListeningReporter::benchmarkFailed( std::string const& error ) {
  14129. for (auto const& listener : m_listeners) {
  14130. listener->benchmarkFailed(error);
  14131. }
  14132. m_reporter->benchmarkFailed(error);
  14133. }
  14134. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  14135. void ListeningReporter::testRunStarting( TestRunInfo const& testRunInfo ) {
  14136. for ( auto const& listener : m_listeners ) {
  14137. listener->testRunStarting( testRunInfo );
  14138. }
  14139. m_reporter->testRunStarting( testRunInfo );
  14140. }
  14141. void ListeningReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  14142. for ( auto const& listener : m_listeners ) {
  14143. listener->testGroupStarting( groupInfo );
  14144. }
  14145. m_reporter->testGroupStarting( groupInfo );
  14146. }
  14147. void ListeningReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
  14148. for ( auto const& listener : m_listeners ) {
  14149. listener->testCaseStarting( testInfo );
  14150. }
  14151. m_reporter->testCaseStarting( testInfo );
  14152. }
  14153. void ListeningReporter::sectionStarting( SectionInfo const& sectionInfo ) {
  14154. for ( auto const& listener : m_listeners ) {
  14155. listener->sectionStarting( sectionInfo );
  14156. }
  14157. m_reporter->sectionStarting( sectionInfo );
  14158. }
  14159. void ListeningReporter::assertionStarting( AssertionInfo const& assertionInfo ) {
  14160. for ( auto const& listener : m_listeners ) {
  14161. listener->assertionStarting( assertionInfo );
  14162. }
  14163. m_reporter->assertionStarting( assertionInfo );
  14164. }
  14165. // The return value indicates if the messages buffer should be cleared:
  14166. bool ListeningReporter::assertionEnded( AssertionStats const& assertionStats ) {
  14167. for( auto const& listener : m_listeners ) {
  14168. static_cast<void>( listener->assertionEnded( assertionStats ) );
  14169. }
  14170. return m_reporter->assertionEnded( assertionStats );
  14171. }
  14172. void ListeningReporter::sectionEnded( SectionStats const& sectionStats ) {
  14173. for ( auto const& listener : m_listeners ) {
  14174. listener->sectionEnded( sectionStats );
  14175. }
  14176. m_reporter->sectionEnded( sectionStats );
  14177. }
  14178. void ListeningReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  14179. for ( auto const& listener : m_listeners ) {
  14180. listener->testCaseEnded( testCaseStats );
  14181. }
  14182. m_reporter->testCaseEnded( testCaseStats );
  14183. }
  14184. void ListeningReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  14185. for ( auto const& listener : m_listeners ) {
  14186. listener->testGroupEnded( testGroupStats );
  14187. }
  14188. m_reporter->testGroupEnded( testGroupStats );
  14189. }
  14190. void ListeningReporter::testRunEnded( TestRunStats const& testRunStats ) {
  14191. for ( auto const& listener : m_listeners ) {
  14192. listener->testRunEnded( testRunStats );
  14193. }
  14194. m_reporter->testRunEnded( testRunStats );
  14195. }
  14196. void ListeningReporter::skipTest( TestCaseInfo const& testInfo ) {
  14197. for ( auto const& listener : m_listeners ) {
  14198. listener->skipTest( testInfo );
  14199. }
  14200. m_reporter->skipTest( testInfo );
  14201. }
  14202. bool ListeningReporter::isMulti() const {
  14203. return true;
  14204. }
  14205. } // end namespace Catch
  14206. // end catch_reporter_listening.cpp
  14207. // start catch_reporter_xml.cpp
  14208. #if defined(_MSC_VER)
  14209. #pragma warning(push)
  14210. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  14211. // Note that 4062 (not all labels are handled
  14212. // and default is missing) is enabled
  14213. #endif
  14214. namespace Catch {
  14215. XmlReporter::XmlReporter( ReporterConfig const& _config )
  14216. : StreamingReporterBase( _config ),
  14217. m_xml(_config.stream())
  14218. {
  14219. m_reporterPrefs.shouldRedirectStdOut = true;
  14220. m_reporterPrefs.shouldReportAllAssertions = true;
  14221. }
  14222. XmlReporter::~XmlReporter() = default;
  14223. std::string XmlReporter::getDescription() {
  14224. return "Reports test results as an XML document";
  14225. }
  14226. std::string XmlReporter::getStylesheetRef() const {
  14227. return std::string();
  14228. }
  14229. void XmlReporter::writeSourceInfo( SourceLineInfo const& sourceInfo ) {
  14230. m_xml
  14231. .writeAttribute( "filename", sourceInfo.file )
  14232. .writeAttribute( "line", sourceInfo.line );
  14233. }
  14234. void XmlReporter::noMatchingTestCases( std::string const& s ) {
  14235. StreamingReporterBase::noMatchingTestCases( s );
  14236. }
  14237. void XmlReporter::testRunStarting( TestRunInfo const& testInfo ) {
  14238. StreamingReporterBase::testRunStarting( testInfo );
  14239. std::string stylesheetRef = getStylesheetRef();
  14240. if( !stylesheetRef.empty() )
  14241. m_xml.writeStylesheetRef( stylesheetRef );
  14242. m_xml.startElement( "Catch" );
  14243. if( !m_config->name().empty() )
  14244. m_xml.writeAttribute( "name", m_config->name() );
  14245. if (m_config->testSpec().hasFilters())
  14246. m_xml.writeAttribute( "filters", serializeFilters( m_config->getTestsOrTags() ) );
  14247. if( m_config->rngSeed() != 0 )
  14248. m_xml.scopedElement( "Randomness" )
  14249. .writeAttribute( "seed", m_config->rngSeed() );
  14250. }
  14251. void XmlReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  14252. StreamingReporterBase::testGroupStarting( groupInfo );
  14253. m_xml.startElement( "Group" )
  14254. .writeAttribute( "name", groupInfo.name );
  14255. }
  14256. void XmlReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
  14257. StreamingReporterBase::testCaseStarting(testInfo);
  14258. m_xml.startElement( "TestCase" )
  14259. .writeAttribute( "name", trim( testInfo.name ) )
  14260. .writeAttribute( "description", testInfo.description )
  14261. .writeAttribute( "tags", testInfo.tagsAsString() );
  14262. writeSourceInfo( testInfo.lineInfo );
  14263. if ( m_config->showDurations() == ShowDurations::Always )
  14264. m_testCaseTimer.start();
  14265. m_xml.ensureTagClosed();
  14266. }
  14267. void XmlReporter::sectionStarting( SectionInfo const& sectionInfo ) {
  14268. StreamingReporterBase::sectionStarting( sectionInfo );
  14269. if( m_sectionDepth++ > 0 ) {
  14270. m_xml.startElement( "Section" )
  14271. .writeAttribute( "name", trim( sectionInfo.name ) );
  14272. writeSourceInfo( sectionInfo.lineInfo );
  14273. m_xml.ensureTagClosed();
  14274. }
  14275. }
  14276. void XmlReporter::assertionStarting( AssertionInfo const& ) { }
  14277. bool XmlReporter::assertionEnded( AssertionStats const& assertionStats ) {
  14278. AssertionResult const& result = assertionStats.assertionResult;
  14279. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  14280. if( includeResults || result.getResultType() == ResultWas::Warning ) {
  14281. // Print any info messages in <Info> tags.
  14282. for( auto const& msg : assertionStats.infoMessages ) {
  14283. if( msg.type == ResultWas::Info && includeResults ) {
  14284. m_xml.scopedElement( "Info" )
  14285. .writeText( msg.message );
  14286. } else if ( msg.type == ResultWas::Warning ) {
  14287. m_xml.scopedElement( "Warning" )
  14288. .writeText( msg.message );
  14289. }
  14290. }
  14291. }
  14292. // Drop out if result was successful but we're not printing them.
  14293. if( !includeResults && result.getResultType() != ResultWas::Warning )
  14294. return true;
  14295. // Print the expression if there is one.
  14296. if( result.hasExpression() ) {
  14297. m_xml.startElement( "Expression" )
  14298. .writeAttribute( "success", result.succeeded() )
  14299. .writeAttribute( "type", result.getTestMacroName() );
  14300. writeSourceInfo( result.getSourceInfo() );
  14301. m_xml.scopedElement( "Original" )
  14302. .writeText( result.getExpression() );
  14303. m_xml.scopedElement( "Expanded" )
  14304. .writeText( result.getExpandedExpression() );
  14305. }
  14306. // And... Print a result applicable to each result type.
  14307. switch( result.getResultType() ) {
  14308. case ResultWas::ThrewException:
  14309. m_xml.startElement( "Exception" );
  14310. writeSourceInfo( result.getSourceInfo() );
  14311. m_xml.writeText( result.getMessage() );
  14312. m_xml.endElement();
  14313. break;
  14314. case ResultWas::FatalErrorCondition:
  14315. m_xml.startElement( "FatalErrorCondition" );
  14316. writeSourceInfo( result.getSourceInfo() );
  14317. m_xml.writeText( result.getMessage() );
  14318. m_xml.endElement();
  14319. break;
  14320. case ResultWas::Info:
  14321. m_xml.scopedElement( "Info" )
  14322. .writeText( result.getMessage() );
  14323. break;
  14324. case ResultWas::Warning:
  14325. // Warning will already have been written
  14326. break;
  14327. case ResultWas::ExplicitFailure:
  14328. m_xml.startElement( "Failure" );
  14329. writeSourceInfo( result.getSourceInfo() );
  14330. m_xml.writeText( result.getMessage() );
  14331. m_xml.endElement();
  14332. break;
  14333. default:
  14334. break;
  14335. }
  14336. if( result.hasExpression() )
  14337. m_xml.endElement();
  14338. return true;
  14339. }
  14340. void XmlReporter::sectionEnded( SectionStats const& sectionStats ) {
  14341. StreamingReporterBase::sectionEnded( sectionStats );
  14342. if( --m_sectionDepth > 0 ) {
  14343. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResults" );
  14344. e.writeAttribute( "successes", sectionStats.assertions.passed );
  14345. e.writeAttribute( "failures", sectionStats.assertions.failed );
  14346. e.writeAttribute( "expectedFailures", sectionStats.assertions.failedButOk );
  14347. if ( m_config->showDurations() == ShowDurations::Always )
  14348. e.writeAttribute( "durationInSeconds", sectionStats.durationInSeconds );
  14349. m_xml.endElement();
  14350. }
  14351. }
  14352. void XmlReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  14353. StreamingReporterBase::testCaseEnded( testCaseStats );
  14354. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResult" );
  14355. e.writeAttribute( "success", testCaseStats.totals.assertions.allOk() );
  14356. if ( m_config->showDurations() == ShowDurations::Always )
  14357. e.writeAttribute( "durationInSeconds", m_testCaseTimer.getElapsedSeconds() );
  14358. if( !testCaseStats.stdOut.empty() )
  14359. m_xml.scopedElement( "StdOut" ).writeText( trim( testCaseStats.stdOut ), XmlFormatting::Newline );
  14360. if( !testCaseStats.stdErr.empty() )
  14361. m_xml.scopedElement( "StdErr" ).writeText( trim( testCaseStats.stdErr ), XmlFormatting::Newline );
  14362. m_xml.endElement();
  14363. }
  14364. void XmlReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  14365. StreamingReporterBase::testGroupEnded( testGroupStats );
  14366. // TODO: Check testGroupStats.aborting and act accordingly.
  14367. m_xml.scopedElement( "OverallResults" )
  14368. .writeAttribute( "successes", testGroupStats.totals.assertions.passed )
  14369. .writeAttribute( "failures", testGroupStats.totals.assertions.failed )
  14370. .writeAttribute( "expectedFailures", testGroupStats.totals.assertions.failedButOk );
  14371. m_xml.scopedElement( "OverallResultsCases")
  14372. .writeAttribute( "successes", testGroupStats.totals.testCases.passed )
  14373. .writeAttribute( "failures", testGroupStats.totals.testCases.failed )
  14374. .writeAttribute( "expectedFailures", testGroupStats.totals.testCases.failedButOk );
  14375. m_xml.endElement();
  14376. }
  14377. void XmlReporter::testRunEnded( TestRunStats const& testRunStats ) {
  14378. StreamingReporterBase::testRunEnded( testRunStats );
  14379. m_xml.scopedElement( "OverallResults" )
  14380. .writeAttribute( "successes", testRunStats.totals.assertions.passed )
  14381. .writeAttribute( "failures", testRunStats.totals.assertions.failed )
  14382. .writeAttribute( "expectedFailures", testRunStats.totals.assertions.failedButOk );
  14383. m_xml.scopedElement( "OverallResultsCases")
  14384. .writeAttribute( "successes", testRunStats.totals.testCases.passed )
  14385. .writeAttribute( "failures", testRunStats.totals.testCases.failed )
  14386. .writeAttribute( "expectedFailures", testRunStats.totals.testCases.failedButOk );
  14387. m_xml.endElement();
  14388. }
  14389. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  14390. void XmlReporter::benchmarkPreparing(std::string const& name) {
  14391. m_xml.startElement("BenchmarkResults")
  14392. .writeAttribute("name", name);
  14393. }
  14394. void XmlReporter::benchmarkStarting(BenchmarkInfo const &info) {
  14395. m_xml.writeAttribute("samples", info.samples)
  14396. .writeAttribute("resamples", info.resamples)
  14397. .writeAttribute("iterations", info.iterations)
  14398. .writeAttribute("clockResolution", info.clockResolution)
  14399. .writeAttribute("estimatedDuration", info.estimatedDuration)
  14400. .writeComment("All values in nano seconds");
  14401. }
  14402. void XmlReporter::benchmarkEnded(BenchmarkStats<> const& benchmarkStats) {
  14403. m_xml.startElement("mean")
  14404. .writeAttribute("value", benchmarkStats.mean.point.count())
  14405. .writeAttribute("lowerBound", benchmarkStats.mean.lower_bound.count())
  14406. .writeAttribute("upperBound", benchmarkStats.mean.upper_bound.count())
  14407. .writeAttribute("ci", benchmarkStats.mean.confidence_interval);
  14408. m_xml.endElement();
  14409. m_xml.startElement("standardDeviation")
  14410. .writeAttribute("value", benchmarkStats.standardDeviation.point.count())
  14411. .writeAttribute("lowerBound", benchmarkStats.standardDeviation.lower_bound.count())
  14412. .writeAttribute("upperBound", benchmarkStats.standardDeviation.upper_bound.count())
  14413. .writeAttribute("ci", benchmarkStats.standardDeviation.confidence_interval);
  14414. m_xml.endElement();
  14415. m_xml.startElement("outliers")
  14416. .writeAttribute("variance", benchmarkStats.outlierVariance)
  14417. .writeAttribute("lowMild", benchmarkStats.outliers.low_mild)
  14418. .writeAttribute("lowSevere", benchmarkStats.outliers.low_severe)
  14419. .writeAttribute("highMild", benchmarkStats.outliers.high_mild)
  14420. .writeAttribute("highSevere", benchmarkStats.outliers.high_severe);
  14421. m_xml.endElement();
  14422. m_xml.endElement();
  14423. }
  14424. void XmlReporter::benchmarkFailed(std::string const &error) {
  14425. m_xml.scopedElement("failed").
  14426. writeAttribute("message", error);
  14427. m_xml.endElement();
  14428. }
  14429. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  14430. CATCH_REGISTER_REPORTER( "xml", XmlReporter )
  14431. } // end namespace Catch
  14432. #if defined(_MSC_VER)
  14433. #pragma warning(pop)
  14434. #endif
  14435. // end catch_reporter_xml.cpp
  14436. namespace Catch {
  14437. LeakDetector leakDetector;
  14438. }
  14439. #ifdef __clang__
  14440. #pragma clang diagnostic pop
  14441. #endif
  14442. // end catch_impl.hpp
  14443. #endif
  14444. #ifdef CATCH_CONFIG_MAIN
  14445. // start catch_default_main.hpp
  14446. #ifndef __OBJC__
  14447. #if defined(CATCH_CONFIG_WCHAR) && defined(CATCH_PLATFORM_WINDOWS) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN)
  14448. // Standard C/C++ Win32 Unicode wmain entry point
  14449. extern "C" int wmain (int argc, wchar_t * argv[], wchar_t * []) {
  14450. #else
  14451. // Standard C/C++ main entry point
  14452. int main (int argc, char * argv[]) {
  14453. #endif
  14454. return Catch::Session().run( argc, argv );
  14455. }
  14456. #else // __OBJC__
  14457. // Objective-C entry point
  14458. int main (int argc, char * const argv[]) {
  14459. #if !CATCH_ARC_ENABLED
  14460. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  14461. #endif
  14462. Catch::registerTestMethods();
  14463. int result = Catch::Session().run( argc, (char**)argv );
  14464. #if !CATCH_ARC_ENABLED
  14465. [pool drain];
  14466. #endif
  14467. return result;
  14468. }
  14469. #endif // __OBJC__
  14470. // end catch_default_main.hpp
  14471. #endif
  14472. #if !defined(CATCH_CONFIG_IMPL_ONLY)
  14473. #ifdef CLARA_CONFIG_MAIN_NOT_DEFINED
  14474. # undef CLARA_CONFIG_MAIN
  14475. #endif
  14476. #if !defined(CATCH_CONFIG_DISABLE)
  14477. //////
  14478. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  14479. #ifdef CATCH_CONFIG_PREFIX_ALL
  14480. #define CATCH_REQUIRE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  14481. #define CATCH_REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  14482. #define CATCH_REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  14483. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  14484. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  14485. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14486. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  14487. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  14488. #define CATCH_REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  14489. #define CATCH_CHECK( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14490. #define CATCH_CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  14491. #define CATCH_CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14492. #define CATCH_CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14493. #define CATCH_CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  14494. #define CATCH_CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14495. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  14496. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  14497. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14498. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  14499. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14500. #define CATCH_CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14501. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14502. #define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  14503. #define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  14504. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14505. #define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg )
  14506. #define CATCH_UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "CATCH_UNSCOPED_INFO", msg )
  14507. #define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  14508. #define CATCH_CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CATCH_CAPTURE",__VA_ARGS__ )
  14509. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  14510. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14511. #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  14512. #define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  14513. #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  14514. #define CATCH_DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
  14515. #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  14516. #define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14517. #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14518. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  14519. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  14520. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14521. #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ )
  14522. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14523. #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
  14524. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )
  14525. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ )
  14526. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14527. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
  14528. #else
  14529. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
  14530. #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) )
  14531. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  14532. #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
  14533. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )
  14534. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) )
  14535. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  14536. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
  14537. #endif
  14538. #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
  14539. #define CATCH_STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__ , #__VA_ARGS__ ); CATCH_SUCCEED( #__VA_ARGS__ )
  14540. #define CATCH_STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); CATCH_SUCCEED( #__VA_ARGS__ )
  14541. #else
  14542. #define CATCH_STATIC_REQUIRE( ... ) CATCH_REQUIRE( __VA_ARGS__ )
  14543. #define CATCH_STATIC_REQUIRE_FALSE( ... ) CATCH_REQUIRE_FALSE( __VA_ARGS__ )
  14544. #endif
  14545. // "BDD-style" convenience wrappers
  14546. #define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ )
  14547. #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  14548. #define CATCH_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
  14549. #define CATCH_AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
  14550. #define CATCH_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
  14551. #define CATCH_AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
  14552. #define CATCH_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
  14553. #define CATCH_AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
  14554. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  14555. #define CATCH_BENCHMARK(...) \
  14556. 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__,,))
  14557. #define CATCH_BENCHMARK_ADVANCED(name) \
  14558. INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), name)
  14559. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  14560. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  14561. #else
  14562. #define REQUIRE( ... ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  14563. #define REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  14564. #define REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  14565. #define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  14566. #define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  14567. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14568. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  14569. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14570. #define REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  14571. #define CHECK( ... ) INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14572. #define CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  14573. #define CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14574. #define CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14575. #define CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  14576. #define CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14577. #define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  14578. #define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  14579. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14580. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  14581. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14582. #define CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14583. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14584. #define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  14585. #define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  14586. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14587. #define INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg )
  14588. #define UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "UNSCOPED_INFO", msg )
  14589. #define WARN( msg ) INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  14590. #define CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CAPTURE",__VA_ARGS__ )
  14591. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  14592. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14593. #define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  14594. #define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  14595. #define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  14596. #define DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
  14597. #define FAIL( ... ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  14598. #define FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14599. #define SUCCEED( ... ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14600. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  14601. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  14602. #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14603. #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ )
  14604. #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14605. #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
  14606. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )
  14607. #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ )
  14608. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14609. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
  14610. #define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(__VA_ARGS__)
  14611. #define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14612. #else
  14613. #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
  14614. #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) )
  14615. #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  14616. #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
  14617. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )
  14618. #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) )
  14619. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  14620. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
  14621. #define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE( __VA_ARGS__ ) )
  14622. #define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  14623. #endif
  14624. #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
  14625. #define STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__, #__VA_ARGS__ ); SUCCEED( #__VA_ARGS__ )
  14626. #define STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); SUCCEED( "!(" #__VA_ARGS__ ")" )
  14627. #else
  14628. #define STATIC_REQUIRE( ... ) REQUIRE( __VA_ARGS__ )
  14629. #define STATIC_REQUIRE_FALSE( ... ) REQUIRE_FALSE( __VA_ARGS__ )
  14630. #endif
  14631. #endif
  14632. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature )
  14633. // "BDD-style" convenience wrappers
  14634. #define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ )
  14635. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  14636. #define GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
  14637. #define AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
  14638. #define WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
  14639. #define AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
  14640. #define THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
  14641. #define AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
  14642. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  14643. #define BENCHMARK(...) \
  14644. 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__,,))
  14645. #define BENCHMARK_ADVANCED(name) \
  14646. INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), name)
  14647. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  14648. using Catch::Detail::Approx;
  14649. #else // CATCH_CONFIG_DISABLE
  14650. //////
  14651. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  14652. #ifdef CATCH_CONFIG_PREFIX_ALL
  14653. #define CATCH_REQUIRE( ... ) (void)(0)
  14654. #define CATCH_REQUIRE_FALSE( ... ) (void)(0)
  14655. #define CATCH_REQUIRE_THROWS( ... ) (void)(0)
  14656. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  14657. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  14658. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14659. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  14660. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  14661. #define CATCH_REQUIRE_NOTHROW( ... ) (void)(0)
  14662. #define CATCH_CHECK( ... ) (void)(0)
  14663. #define CATCH_CHECK_FALSE( ... ) (void)(0)
  14664. #define CATCH_CHECKED_IF( ... ) if (__VA_ARGS__)
  14665. #define CATCH_CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  14666. #define CATCH_CHECK_NOFAIL( ... ) (void)(0)
  14667. #define CATCH_CHECK_THROWS( ... ) (void)(0)
  14668. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  14669. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  14670. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14671. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  14672. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14673. #define CATCH_CHECK_NOTHROW( ... ) (void)(0)
  14674. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14675. #define CATCH_CHECK_THAT( arg, matcher ) (void)(0)
  14676. #define CATCH_REQUIRE_THAT( arg, matcher ) (void)(0)
  14677. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14678. #define CATCH_INFO( msg ) (void)(0)
  14679. #define CATCH_UNSCOPED_INFO( msg ) (void)(0)
  14680. #define CATCH_WARN( msg ) (void)(0)
  14681. #define CATCH_CAPTURE( msg ) (void)(0)
  14682. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  14683. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  14684. #define CATCH_METHOD_AS_TEST_CASE( method, ... )
  14685. #define CATCH_REGISTER_TEST_CASE( Function, ... ) (void)(0)
  14686. #define CATCH_SECTION( ... )
  14687. #define CATCH_DYNAMIC_SECTION( ... )
  14688. #define CATCH_FAIL( ... ) (void)(0)
  14689. #define CATCH_FAIL_CHECK( ... ) (void)(0)
  14690. #define CATCH_SUCCEED( ... ) (void)(0)
  14691. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  14692. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  14693. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
  14694. #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
  14695. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
  14696. #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ )
  14697. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14698. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14699. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14700. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14701. #else
  14702. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) )
  14703. #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) )
  14704. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) )
  14705. #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) )
  14706. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14707. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14708. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14709. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14710. #endif
  14711. // "BDD-style" convenience wrappers
  14712. #define CATCH_SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  14713. #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 )
  14714. #define CATCH_GIVEN( desc )
  14715. #define CATCH_AND_GIVEN( desc )
  14716. #define CATCH_WHEN( desc )
  14717. #define CATCH_AND_WHEN( desc )
  14718. #define CATCH_THEN( desc )
  14719. #define CATCH_AND_THEN( desc )
  14720. #define CATCH_STATIC_REQUIRE( ... ) (void)(0)
  14721. #define CATCH_STATIC_REQUIRE_FALSE( ... ) (void)(0)
  14722. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  14723. #else
  14724. #define REQUIRE( ... ) (void)(0)
  14725. #define REQUIRE_FALSE( ... ) (void)(0)
  14726. #define REQUIRE_THROWS( ... ) (void)(0)
  14727. #define REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  14728. #define REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  14729. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14730. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  14731. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14732. #define REQUIRE_NOTHROW( ... ) (void)(0)
  14733. #define CHECK( ... ) (void)(0)
  14734. #define CHECK_FALSE( ... ) (void)(0)
  14735. #define CHECKED_IF( ... ) if (__VA_ARGS__)
  14736. #define CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  14737. #define CHECK_NOFAIL( ... ) (void)(0)
  14738. #define CHECK_THROWS( ... ) (void)(0)
  14739. #define CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  14740. #define CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  14741. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14742. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  14743. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14744. #define CHECK_NOTHROW( ... ) (void)(0)
  14745. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14746. #define CHECK_THAT( arg, matcher ) (void)(0)
  14747. #define REQUIRE_THAT( arg, matcher ) (void)(0)
  14748. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14749. #define INFO( msg ) (void)(0)
  14750. #define UNSCOPED_INFO( msg ) (void)(0)
  14751. #define WARN( msg ) (void)(0)
  14752. #define CAPTURE( msg ) (void)(0)
  14753. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  14754. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  14755. #define METHOD_AS_TEST_CASE( method, ... )
  14756. #define REGISTER_TEST_CASE( Function, ... ) (void)(0)
  14757. #define SECTION( ... )
  14758. #define DYNAMIC_SECTION( ... )
  14759. #define FAIL( ... ) (void)(0)
  14760. #define FAIL_CHECK( ... ) (void)(0)
  14761. #define SUCCEED( ... ) (void)(0)
  14762. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  14763. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  14764. #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
  14765. #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
  14766. #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
  14767. #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ )
  14768. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14769. #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14770. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14771. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14772. #else
  14773. #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) )
  14774. #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) )
  14775. #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) )
  14776. #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) )
  14777. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14778. #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14779. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14780. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14781. #endif
  14782. #define STATIC_REQUIRE( ... ) (void)(0)
  14783. #define STATIC_REQUIRE_FALSE( ... ) (void)(0)
  14784. #endif
  14785. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
  14786. // "BDD-style" convenience wrappers
  14787. #define SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) )
  14788. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className )
  14789. #define GIVEN( desc )
  14790. #define AND_GIVEN( desc )
  14791. #define WHEN( desc )
  14792. #define AND_WHEN( desc )
  14793. #define THEN( desc )
  14794. #define AND_THEN( desc )
  14795. using Catch::Detail::Approx;
  14796. #endif
  14797. #endif // ! CATCH_CONFIG_IMPL_ONLY
  14798. // start catch_reenable_warnings.h
  14799. #ifdef __clang__
  14800. # ifdef __ICC // icpc defines the __clang__ macro
  14801. # pragma warning(pop)
  14802. # else
  14803. # pragma clang diagnostic pop
  14804. # endif
  14805. #elif defined __GNUC__
  14806. # pragma GCC diagnostic pop
  14807. #endif
  14808. // end catch_reenable_warnings.h
  14809. // end catch.hpp
  14810. #endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED