catch.hpp 605 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076
  1. /*
  2. * Catch v2.9.2
  3. * Generated: 2019-08-08 13:35:12.279703
  4. * ----------------------------------------------------------
  5. * This file has been merged from multiple headers. Please don't edit it directly
  6. * Copyright (c) 2019 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 9
  16. #define CATCH_VERSION_PATCH 2
  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. #ifdef __APPLE__
  61. # include <TargetConditionals.h>
  62. # if TARGET_OS_OSX == 1
  63. # define CATCH_PLATFORM_MAC
  64. # elif TARGET_OS_IPHONE == 1
  65. # define CATCH_PLATFORM_IPHONE
  66. # endif
  67. #elif defined(linux) || defined(__linux) || defined(__linux__)
  68. # define CATCH_PLATFORM_LINUX
  69. #elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) || defined(__MINGW32__)
  70. # define CATCH_PLATFORM_WINDOWS
  71. #endif
  72. // end catch_platform.h
  73. #ifdef CATCH_IMPL
  74. # ifndef CLARA_CONFIG_MAIN
  75. # define CLARA_CONFIG_MAIN_NOT_DEFINED
  76. # define CLARA_CONFIG_MAIN
  77. # endif
  78. #endif
  79. // start catch_user_interfaces.h
  80. namespace Catch {
  81. unsigned int rngSeed();
  82. }
  83. // end catch_user_interfaces.h
  84. // start catch_tag_alias_autoregistrar.h
  85. // start catch_common.h
  86. // start catch_compiler_capabilities.h
  87. // Detect a number of compiler features - by compiler
  88. // The following features are defined:
  89. //
  90. // CATCH_CONFIG_COUNTER : is the __COUNTER__ macro supported?
  91. // CATCH_CONFIG_WINDOWS_SEH : is Windows SEH supported?
  92. // CATCH_CONFIG_POSIX_SIGNALS : are POSIX signals supported?
  93. // CATCH_CONFIG_DISABLE_EXCEPTIONS : Are exceptions enabled?
  94. // ****************
  95. // Note to maintainers: if new toggles are added please document them
  96. // in configuration.md, too
  97. // ****************
  98. // In general each macro has a _NO_<feature name> form
  99. // (e.g. CATCH_CONFIG_NO_POSIX_SIGNALS) which disables the feature.
  100. // Many features, at point of detection, define an _INTERNAL_ macro, so they
  101. // can be combined, en-mass, with the _NO_ forms later.
  102. #ifdef __cplusplus
  103. # if (__cplusplus >= 201402L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201402L)
  104. # define CATCH_CPP14_OR_GREATER
  105. # endif
  106. # if (__cplusplus >= 201703L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L)
  107. # define CATCH_CPP17_OR_GREATER
  108. # endif
  109. #endif
  110. #if defined(CATCH_CPP17_OR_GREATER)
  111. # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
  112. #endif
  113. #ifdef __clang__
  114. # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  115. _Pragma( "clang diagnostic push" ) \
  116. _Pragma( "clang diagnostic ignored \"-Wexit-time-destructors\"" ) \
  117. _Pragma( "clang diagnostic ignored \"-Wglobal-constructors\"")
  118. # define CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  119. _Pragma( "clang diagnostic pop" )
  120. # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
  121. _Pragma( "clang diagnostic push" ) \
  122. _Pragma( "clang diagnostic ignored \"-Wparentheses\"" )
  123. # define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
  124. _Pragma( "clang diagnostic pop" )
  125. # define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
  126. _Pragma( "clang diagnostic push" ) \
  127. _Pragma( "clang diagnostic ignored \"-Wunused-variable\"" )
  128. # define CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS \
  129. _Pragma( "clang diagnostic pop" )
  130. # define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
  131. _Pragma( "clang diagnostic push" ) \
  132. _Pragma( "clang diagnostic ignored \"-Wgnu-zero-variadic-macro-arguments\"" )
  133. # define CATCH_INTERNAL_UNSUPPRESS_ZERO_VARIADIC_WARNINGS \
  134. _Pragma( "clang diagnostic pop" )
  135. #endif // __clang__
  136. ////////////////////////////////////////////////////////////////////////////////
  137. // Assume that non-Windows platforms support posix signals by default
  138. #if !defined(CATCH_PLATFORM_WINDOWS)
  139. #define CATCH_INTERNAL_CONFIG_POSIX_SIGNALS
  140. #endif
  141. ////////////////////////////////////////////////////////////////////////////////
  142. // We know some environments not to support full POSIX signals
  143. #if defined(__CYGWIN__) || defined(__QNX__) || defined(__EMSCRIPTEN__) || defined(__DJGPP__)
  144. #define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
  145. #endif
  146. #ifdef __OS400__
  147. # define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
  148. # define CATCH_CONFIG_COLOUR_NONE
  149. #endif
  150. ////////////////////////////////////////////////////////////////////////////////
  151. // Android somehow still does not support std::to_string
  152. #if defined(__ANDROID__)
  153. # define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
  154. #endif
  155. ////////////////////////////////////////////////////////////////////////////////
  156. // Not all Windows environments support SEH properly
  157. #if defined(__MINGW32__)
  158. # define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH
  159. #endif
  160. ////////////////////////////////////////////////////////////////////////////////
  161. // PS4
  162. #if defined(__ORBIS__)
  163. # define CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE
  164. #endif
  165. ////////////////////////////////////////////////////////////////////////////////
  166. // Cygwin
  167. #ifdef __CYGWIN__
  168. // Required for some versions of Cygwin to declare gettimeofday
  169. // see: http://stackoverflow.com/questions/36901803/gettimeofday-not-declared-in-this-scope-cygwin
  170. # define _BSD_SOURCE
  171. // some versions of cygwin (most) do not support std::to_string. Use the libstd check.
  172. // https://gcc.gnu.org/onlinedocs/gcc-4.8.2/libstdc++/api/a01053_source.html line 2812-2813
  173. # if !((__cplusplus >= 201103L) && defined(_GLIBCXX_USE_C99) \
  174. && !defined(_GLIBCXX_HAVE_BROKEN_VSWPRINTF))
  175. # define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
  176. # endif
  177. #endif // __CYGWIN__
  178. ////////////////////////////////////////////////////////////////////////////////
  179. // Visual C++
  180. #ifdef _MSC_VER
  181. # if _MSC_VER >= 1900 // Visual Studio 2015 or newer
  182. # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
  183. # endif
  184. // Universal Windows platform does not support SEH
  185. // Or console colours (or console at all...)
  186. # if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP)
  187. # define CATCH_CONFIG_COLOUR_NONE
  188. # else
  189. # define CATCH_INTERNAL_CONFIG_WINDOWS_SEH
  190. # endif
  191. // MSVC traditional preprocessor needs some workaround for __VA_ARGS__
  192. // _MSVC_TRADITIONAL == 0 means new conformant preprocessor
  193. // _MSVC_TRADITIONAL == 1 means old traditional non-conformant preprocessor
  194. # if !defined(_MSVC_TRADITIONAL) || (defined(_MSVC_TRADITIONAL) && _MSVC_TRADITIONAL)
  195. # define CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  196. # endif
  197. #endif // _MSC_VER
  198. #if defined(_REENTRANT) || defined(_MSC_VER)
  199. // Enable async processing, as -pthread is specified or no additional linking is required
  200. # define CATCH_INTERNAL_CONFIG_USE_ASYNC
  201. #endif // _MSC_VER
  202. ////////////////////////////////////////////////////////////////////////////////
  203. // Check if we are compiled with -fno-exceptions or equivalent
  204. #if defined(__EXCEPTIONS) || defined(__cpp_exceptions) || defined(_CPPUNWIND)
  205. # define CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED
  206. #endif
  207. ////////////////////////////////////////////////////////////////////////////////
  208. // DJGPP
  209. #ifdef __DJGPP__
  210. # define CATCH_INTERNAL_CONFIG_NO_WCHAR
  211. #endif // __DJGPP__
  212. ////////////////////////////////////////////////////////////////////////////////
  213. // Embarcadero C++Build
  214. #if defined(__BORLANDC__)
  215. #define CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN
  216. #endif
  217. ////////////////////////////////////////////////////////////////////////////////
  218. // Use of __COUNTER__ is suppressed during code analysis in
  219. // CLion/AppCode 2017.2.x and former, because __COUNTER__ is not properly
  220. // handled by it.
  221. // Otherwise all supported compilers support COUNTER macro,
  222. // but user still might want to turn it off
  223. #if ( !defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L )
  224. #define CATCH_INTERNAL_CONFIG_COUNTER
  225. #endif
  226. ////////////////////////////////////////////////////////////////////////////////
  227. // RTX is a special version of Windows that is real time.
  228. // This means that it is detected as Windows, but does not provide
  229. // the same set of capabilities as real Windows does.
  230. #if defined(UNDER_RTSS) || defined(RTX64_BUILD)
  231. #define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH
  232. #define CATCH_INTERNAL_CONFIG_NO_ASYNC
  233. #define CATCH_CONFIG_COLOUR_NONE
  234. #endif
  235. ////////////////////////////////////////////////////////////////////////////////
  236. // Check if string_view is available and usable
  237. // The check is split apart to work around v140 (VS2015) preprocessor issue...
  238. #if defined(__has_include)
  239. #if __has_include(<string_view>) && defined(CATCH_CPP17_OR_GREATER)
  240. # define CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW
  241. #endif
  242. #endif
  243. ////////////////////////////////////////////////////////////////////////////////
  244. // Check if optional is available and usable
  245. #if defined(__has_include)
  246. # if __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
  247. # define CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL
  248. # endif // __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
  249. #endif // __has_include
  250. ////////////////////////////////////////////////////////////////////////////////
  251. // Check if byte is available and usable
  252. #if defined(__has_include)
  253. # if __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER)
  254. # define CATCH_INTERNAL_CONFIG_CPP17_BYTE
  255. # endif // __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER)
  256. #endif // __has_include
  257. ////////////////////////////////////////////////////////////////////////////////
  258. // Check if variant is available and usable
  259. #if defined(__has_include)
  260. # if __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
  261. # if defined(__clang__) && (__clang_major__ < 8)
  262. // work around clang bug with libstdc++ https://bugs.llvm.org/show_bug.cgi?id=31852
  263. // fix should be in clang 8, workaround in libstdc++ 8.2
  264. # include <ciso646>
  265. # if defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
  266. # define CATCH_CONFIG_NO_CPP17_VARIANT
  267. # else
  268. # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
  269. # endif // defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
  270. # else
  271. # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
  272. # endif // defined(__clang__) && (__clang_major__ < 8)
  273. # endif // __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
  274. #endif // __has_include
  275. #if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER)
  276. # define CATCH_CONFIG_COUNTER
  277. #endif
  278. #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)
  279. # define CATCH_CONFIG_WINDOWS_SEH
  280. #endif
  281. // This is set by default, because we assume that unix compilers are posix-signal-compatible by default.
  282. #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)
  283. # define CATCH_CONFIG_POSIX_SIGNALS
  284. #endif
  285. // This is set by default, because we assume that compilers with no wchar_t support are just rare exceptions.
  286. #if !defined(CATCH_INTERNAL_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_WCHAR)
  287. # define CATCH_CONFIG_WCHAR
  288. #endif
  289. #if !defined(CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_CPP11_TO_STRING)
  290. # define CATCH_CONFIG_CPP11_TO_STRING
  291. #endif
  292. #if defined(CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_NO_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_CPP17_OPTIONAL)
  293. # define CATCH_CONFIG_CPP17_OPTIONAL
  294. #endif
  295. #if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
  296. # define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
  297. #endif
  298. #if defined(CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_NO_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_CPP17_STRING_VIEW)
  299. # define CATCH_CONFIG_CPP17_STRING_VIEW
  300. #endif
  301. #if defined(CATCH_INTERNAL_CONFIG_CPP17_VARIANT) && !defined(CATCH_CONFIG_NO_CPP17_VARIANT) && !defined(CATCH_CONFIG_CPP17_VARIANT)
  302. # define CATCH_CONFIG_CPP17_VARIANT
  303. #endif
  304. #if defined(CATCH_INTERNAL_CONFIG_CPP17_BYTE) && !defined(CATCH_CONFIG_NO_CPP17_BYTE) && !defined(CATCH_CONFIG_CPP17_BYTE)
  305. # define CATCH_CONFIG_CPP17_BYTE
  306. #endif
  307. #if defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
  308. # define CATCH_INTERNAL_CONFIG_NEW_CAPTURE
  309. #endif
  310. #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)
  311. # define CATCH_CONFIG_NEW_CAPTURE
  312. #endif
  313. #if !defined(CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  314. # define CATCH_CONFIG_DISABLE_EXCEPTIONS
  315. #endif
  316. #if defined(CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_NO_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_POLYFILL_ISNAN)
  317. # define CATCH_CONFIG_POLYFILL_ISNAN
  318. #endif
  319. #if defined(CATCH_INTERNAL_CONFIG_USE_ASYNC) && !defined(CATCH_INTERNAL_CONFIG_NO_ASYNC) && !defined(CATCH_CONFIG_NO_USE_ASYNC) && !defined(CATCH_CONFIG_USE_ASYNC)
  320. # define CATCH_CONFIG_USE_ASYNC
  321. #endif
  322. #if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS)
  323. # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS
  324. # define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS
  325. #endif
  326. #if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS)
  327. # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  328. # define CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  329. #endif
  330. #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS)
  331. # define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS
  332. # define CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS
  333. #endif
  334. #if !defined(CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS)
  335. # define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS
  336. # define CATCH_INTERNAL_UNSUPPRESS_ZERO_VARIADIC_WARNINGS
  337. #endif
  338. #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  339. #define CATCH_TRY if ((true))
  340. #define CATCH_CATCH_ALL if ((false))
  341. #define CATCH_CATCH_ANON(type) if ((false))
  342. #else
  343. #define CATCH_TRY try
  344. #define CATCH_CATCH_ALL catch (...)
  345. #define CATCH_CATCH_ANON(type) catch (type)
  346. #endif
  347. #if defined(CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_NO_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR)
  348. #define CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  349. #endif
  350. // end catch_compiler_capabilities.h
  351. #define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line
  352. #define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line )
  353. #ifdef CATCH_CONFIG_COUNTER
  354. # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ )
  355. #else
  356. # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ )
  357. #endif
  358. #include <iosfwd>
  359. #include <string>
  360. #include <cstdint>
  361. // We need a dummy global operator<< so we can bring it into Catch namespace later
  362. struct Catch_global_namespace_dummy {};
  363. std::ostream& operator<<(std::ostream&, Catch_global_namespace_dummy);
  364. namespace Catch {
  365. struct CaseSensitive { enum Choice {
  366. Yes,
  367. No
  368. }; };
  369. class NonCopyable {
  370. NonCopyable( NonCopyable const& ) = delete;
  371. NonCopyable( NonCopyable && ) = delete;
  372. NonCopyable& operator = ( NonCopyable const& ) = delete;
  373. NonCopyable& operator = ( NonCopyable && ) = delete;
  374. protected:
  375. NonCopyable();
  376. virtual ~NonCopyable();
  377. };
  378. struct SourceLineInfo {
  379. SourceLineInfo() = delete;
  380. SourceLineInfo( char const* _file, std::size_t _line ) noexcept
  381. : file( _file ),
  382. line( _line )
  383. {}
  384. SourceLineInfo( SourceLineInfo const& other ) = default;
  385. SourceLineInfo& operator = ( SourceLineInfo const& ) = default;
  386. SourceLineInfo( SourceLineInfo&& ) noexcept = default;
  387. SourceLineInfo& operator = ( SourceLineInfo&& ) noexcept = default;
  388. bool empty() const noexcept;
  389. bool operator == ( SourceLineInfo const& other ) const noexcept;
  390. bool operator < ( SourceLineInfo const& other ) const noexcept;
  391. char const* file;
  392. std::size_t line;
  393. };
  394. std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info );
  395. // Bring in operator<< from global namespace into Catch namespace
  396. // This is necessary because the overload of operator<< above makes
  397. // lookup stop at namespace Catch
  398. using ::operator<<;
  399. // Use this in variadic streaming macros to allow
  400. // >> +StreamEndStop
  401. // as well as
  402. // >> stuff +StreamEndStop
  403. struct StreamEndStop {
  404. std::string operator+() const;
  405. };
  406. template<typename T>
  407. T const& operator + ( T const& value, StreamEndStop ) {
  408. return value;
  409. }
  410. }
  411. #define CATCH_INTERNAL_LINEINFO \
  412. ::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) )
  413. // end catch_common.h
  414. namespace Catch {
  415. struct RegistrarForTagAliases {
  416. RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo );
  417. };
  418. } // end namespace Catch
  419. #define CATCH_REGISTER_TAG_ALIAS( alias, spec ) \
  420. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  421. namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } \
  422. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  423. // end catch_tag_alias_autoregistrar.h
  424. // start catch_test_registry.h
  425. // start catch_interfaces_testcase.h
  426. #include <vector>
  427. namespace Catch {
  428. class TestSpec;
  429. struct ITestInvoker {
  430. virtual void invoke () const = 0;
  431. virtual ~ITestInvoker();
  432. };
  433. class TestCase;
  434. struct IConfig;
  435. struct ITestCaseRegistry {
  436. virtual ~ITestCaseRegistry();
  437. virtual std::vector<TestCase> const& getAllTests() const = 0;
  438. virtual std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const = 0;
  439. };
  440. bool isThrowSafe( TestCase const& testCase, IConfig const& config );
  441. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
  442. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
  443. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
  444. }
  445. // end catch_interfaces_testcase.h
  446. // start catch_stringref.h
  447. #include <cstddef>
  448. #include <string>
  449. #include <iosfwd>
  450. namespace Catch {
  451. /// A non-owning string class (similar to the forthcoming std::string_view)
  452. /// Note that, because a StringRef may be a substring of another string,
  453. /// it may not be null terminated. c_str() must return a null terminated
  454. /// string, however, and so the StringRef will internally take ownership
  455. /// (taking a copy), if necessary. In theory this ownership is not externally
  456. /// visible - but it does mean (substring) StringRefs should not be shared between
  457. /// threads.
  458. class StringRef {
  459. public:
  460. using size_type = std::size_t;
  461. private:
  462. friend struct StringRefTestAccess;
  463. char const* m_start;
  464. size_type m_size;
  465. char* m_data = nullptr;
  466. void takeOwnership();
  467. static constexpr char const* const s_empty = "";
  468. public: // construction/ assignment
  469. StringRef() noexcept
  470. : StringRef( s_empty, 0 )
  471. {}
  472. StringRef( StringRef const& other ) noexcept
  473. : m_start( other.m_start ),
  474. m_size( other.m_size )
  475. {}
  476. StringRef( StringRef&& other ) noexcept
  477. : m_start( other.m_start ),
  478. m_size( other.m_size ),
  479. m_data( other.m_data )
  480. {
  481. other.m_data = nullptr;
  482. }
  483. StringRef( char const* rawChars ) noexcept;
  484. StringRef( char const* rawChars, size_type size ) noexcept
  485. : m_start( rawChars ),
  486. m_size( size )
  487. {}
  488. StringRef( std::string const& stdString ) noexcept
  489. : m_start( stdString.c_str() ),
  490. m_size( stdString.size() )
  491. {}
  492. ~StringRef() noexcept {
  493. delete[] m_data;
  494. }
  495. auto operator = ( StringRef const &other ) noexcept -> StringRef& {
  496. delete[] m_data;
  497. m_data = nullptr;
  498. m_start = other.m_start;
  499. m_size = other.m_size;
  500. return *this;
  501. }
  502. operator std::string() const;
  503. void swap( StringRef& other ) noexcept;
  504. public: // operators
  505. auto operator == ( StringRef const& other ) const noexcept -> bool;
  506. auto operator != ( StringRef const& other ) const noexcept -> bool;
  507. auto operator[] ( size_type index ) const noexcept -> char;
  508. public: // named queries
  509. auto empty() const noexcept -> bool {
  510. return m_size == 0;
  511. }
  512. auto size() const noexcept -> size_type {
  513. return m_size;
  514. }
  515. auto numberOfCharacters() const noexcept -> size_type;
  516. auto c_str() const -> char const*;
  517. public: // substrings and searches
  518. auto substr( size_type start, size_type size ) const noexcept -> StringRef;
  519. // Returns the current start pointer.
  520. // Note that the pointer can change when if the StringRef is a substring
  521. auto currentData() const noexcept -> char const*;
  522. private: // ownership queries - may not be consistent between calls
  523. auto isOwned() const noexcept -> bool;
  524. auto isSubstring() const noexcept -> bool;
  525. };
  526. auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string;
  527. auto operator + ( StringRef const& lhs, char const* rhs ) -> std::string;
  528. auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string;
  529. auto operator += ( std::string& lhs, StringRef const& sr ) -> std::string&;
  530. auto operator << ( std::ostream& os, StringRef const& sr ) -> std::ostream&;
  531. inline auto operator "" _sr( char const* rawChars, std::size_t size ) noexcept -> StringRef {
  532. return StringRef( rawChars, size );
  533. }
  534. } // namespace Catch
  535. inline auto operator "" _catch_sr( char const* rawChars, std::size_t size ) noexcept -> Catch::StringRef {
  536. return Catch::StringRef( rawChars, size );
  537. }
  538. // end catch_stringref.h
  539. // start catch_type_traits.hpp
  540. #include <type_traits>
  541. namespace Catch{
  542. #ifdef CATCH_CPP17_OR_GREATER
  543. template <typename...>
  544. inline constexpr auto is_unique = std::true_type{};
  545. template <typename T, typename... Rest>
  546. inline constexpr auto is_unique<T, Rest...> = std::bool_constant<
  547. (!std::is_same_v<T, Rest> && ...) && is_unique<Rest...>
  548. >{};
  549. #else
  550. template <typename...>
  551. struct is_unique : std::true_type{};
  552. template <typename T0, typename T1, typename... Rest>
  553. struct is_unique<T0, T1, Rest...> : std::integral_constant
  554. <bool,
  555. !std::is_same<T0, T1>::value
  556. && is_unique<T0, Rest...>::value
  557. && is_unique<T1, Rest...>::value
  558. >{};
  559. #endif
  560. }
  561. // end catch_type_traits.hpp
  562. // start catch_preprocessor.hpp
  563. #define CATCH_RECURSION_LEVEL0(...) __VA_ARGS__
  564. #define CATCH_RECURSION_LEVEL1(...) CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(__VA_ARGS__)))
  565. #define CATCH_RECURSION_LEVEL2(...) CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(__VA_ARGS__)))
  566. #define CATCH_RECURSION_LEVEL3(...) CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(__VA_ARGS__)))
  567. #define CATCH_RECURSION_LEVEL4(...) CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(__VA_ARGS__)))
  568. #define CATCH_RECURSION_LEVEL5(...) CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(__VA_ARGS__)))
  569. #ifdef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  570. #define INTERNAL_CATCH_EXPAND_VARGS(...) __VA_ARGS__
  571. // MSVC needs more evaluations
  572. #define CATCH_RECURSION_LEVEL6(...) CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(__VA_ARGS__)))
  573. #define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL6(CATCH_RECURSION_LEVEL6(__VA_ARGS__))
  574. #else
  575. #define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL5(__VA_ARGS__)
  576. #endif
  577. #define CATCH_REC_END(...)
  578. #define CATCH_REC_OUT
  579. #define CATCH_EMPTY()
  580. #define CATCH_DEFER(id) id CATCH_EMPTY()
  581. #define CATCH_REC_GET_END2() 0, CATCH_REC_END
  582. #define CATCH_REC_GET_END1(...) CATCH_REC_GET_END2
  583. #define CATCH_REC_GET_END(...) CATCH_REC_GET_END1
  584. #define CATCH_REC_NEXT0(test, next, ...) next CATCH_REC_OUT
  585. #define CATCH_REC_NEXT1(test, next) CATCH_DEFER ( CATCH_REC_NEXT0 ) ( test, next, 0)
  586. #define CATCH_REC_NEXT(test, next) CATCH_REC_NEXT1(CATCH_REC_GET_END test, next)
  587. #define CATCH_REC_LIST0(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ )
  588. #define CATCH_REC_LIST1(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0) ) ( f, peek, __VA_ARGS__ )
  589. #define CATCH_REC_LIST2(f, x, peek, ...) f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ )
  590. #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__ )
  591. #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__ )
  592. #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__ )
  593. // Applies the function macro `f` to each of the remaining parameters, inserts commas between the results,
  594. // and passes userdata as the first parameter to each invocation,
  595. // e.g. CATCH_REC_LIST_UD(f, x, a, b, c) evaluates to f(x, a), f(x, b), f(x, c)
  596. #define CATCH_REC_LIST_UD(f, userdata, ...) CATCH_RECURSE(CATCH_REC_LIST2_UD(f, userdata, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
  597. #define CATCH_REC_LIST(f, ...) CATCH_RECURSE(CATCH_REC_LIST2(f, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
  598. #define INTERNAL_CATCH_EXPAND1(param) INTERNAL_CATCH_EXPAND2(param)
  599. #define INTERNAL_CATCH_EXPAND2(...) INTERNAL_CATCH_NO## __VA_ARGS__
  600. #define INTERNAL_CATCH_DEF(...) INTERNAL_CATCH_DEF __VA_ARGS__
  601. #define INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
  602. #define INTERNAL_CATCH_STRINGIZE(...) INTERNAL_CATCH_STRINGIZE2(__VA_ARGS__)
  603. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  604. #define INTERNAL_CATCH_STRINGIZE2(...) #__VA_ARGS__
  605. #define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param))
  606. #else
  607. // MSVC is adding extra space and needs another indirection to expand INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
  608. #define INTERNAL_CATCH_STRINGIZE2(...) INTERNAL_CATCH_STRINGIZE3(__VA_ARGS__)
  609. #define INTERNAL_CATCH_STRINGIZE3(...) #__VA_ARGS__
  610. #define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) (INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) + 1)
  611. #endif
  612. #define INTERNAL_CATCH_MAKE_NAMESPACE2(...) ns_##__VA_ARGS__
  613. #define INTERNAL_CATCH_MAKE_NAMESPACE(name) INTERNAL_CATCH_MAKE_NAMESPACE2(name)
  614. #define INTERNAL_CATCH_REMOVE_PARENS(...) INTERNAL_CATCH_EXPAND1(INTERNAL_CATCH_DEF __VA_ARGS__)
  615. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  616. #define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>())
  617. #define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__))
  618. #else
  619. #define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) INTERNAL_CATCH_EXPAND_VARGS(decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>()))
  620. #define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__)))
  621. #endif
  622. #define INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(...)\
  623. CATCH_REC_LIST(INTERNAL_CATCH_MAKE_TYPE_LIST,__VA_ARGS__)
  624. #define INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_0) INTERNAL_CATCH_REMOVE_PARENS(_0)
  625. #define INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_0, _1) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_1)
  626. #define INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_0, _1, _2) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_1, _2)
  627. #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)
  628. #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)
  629. #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)
  630. #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, _4, _5, _6)
  631. #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)
  632. #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)
  633. #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)
  634. #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)
  635. #define INTERNAL_CATCH_VA_NARGS_IMPL(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N
  636. #define INTERNAL_CATCH_TYPE_GEN\
  637. template<typename...> struct TypeList {};\
  638. template<typename...Ts>\
  639. constexpr auto get_wrapper() noexcept -> TypeList<Ts...> { return {}; }\
  640. \
  641. template<template<typename...> class L1, typename...E1, template<typename...> class L2, typename...E2> \
  642. constexpr auto append(L1<E1...>, L2<E2...>) noexcept -> L1<E1...,E2...> { return {}; }\
  643. template< template<typename...> class L1, typename...E1, template<typename...> class L2, typename...E2, typename...Rest>\
  644. constexpr auto append(L1<E1...>, L2<E2...>, Rest...) noexcept -> decltype(append(L1<E1...,E2...>{}, Rest{}...)) { return {}; }\
  645. template< template<typename...> class L1, typename...E1, typename...Rest>\
  646. constexpr auto append(L1<E1...>, TypeList<mpl_::na>, Rest...) noexcept -> L1<E1...> { return {}; }\
  647. \
  648. template< template<typename...> class Container, template<typename...> class List, typename...elems>\
  649. constexpr auto rewrap(List<elems...>) noexcept -> TypeList<Container<elems...>> { return {}; }\
  650. template< template<typename...> class Container, template<typename...> class List, class...Elems, typename...Elements>\
  651. constexpr auto rewrap(List<Elems...>,Elements...) noexcept -> decltype(append(TypeList<Container<Elems...>>{}, rewrap<Container>(Elements{}...))) { return {}; }\
  652. \
  653. template<template <typename...> class Final, template< typename...> class...Containers, typename...Types>\
  654. constexpr auto create(TypeList<Types...>) noexcept -> decltype(append(Final<>{}, rewrap<Containers>(Types{}...)...)) { return {}; }\
  655. template<template <typename...> class Final, template <typename...> class List, typename...Ts>\
  656. constexpr auto convert(List<Ts...>) noexcept -> decltype(append(Final<>{},TypeList<Ts>{}...)) { return {}; }
  657. #define INTERNAL_CATCH_NTTP_1(signature, ...)\
  658. template<INTERNAL_CATCH_REMOVE_PARENS(signature)> struct Nttp{};\
  659. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  660. constexpr auto get_wrapper() noexcept -> Nttp<__VA_ARGS__> { return {}; } \
  661. \
  662. template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  663. constexpr auto rewrap(List<__VA_ARGS__>) noexcept -> TypeList<Container<__VA_ARGS__>> { return {}; }\
  664. template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature), typename...Elements>\
  665. constexpr auto rewrap(List<__VA_ARGS__>,Elements...elems) noexcept -> decltype(append(TypeList<Container<__VA_ARGS__>>{}, rewrap<Container>(elems...))) { return {}; }\
  666. template<template <typename...> class Final, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...Containers, typename...Types>\
  667. constexpr auto create(TypeList<Types...>) noexcept -> decltype(append(Final<>{}, rewrap<Containers>(Types{}...)...)) { return {}; }
  668. #define INTERNAL_CATCH_DECLARE_SIG_TEST0(TestName)
  669. #define INTERNAL_CATCH_DECLARE_SIG_TEST1(TestName, signature)\
  670. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  671. static void TestName()
  672. #define INTERNAL_CATCH_DECLARE_SIG_TEST_X(TestName, signature, ...)\
  673. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  674. static void TestName()
  675. #define INTERNAL_CATCH_DEFINE_SIG_TEST0(TestName)
  676. #define INTERNAL_CATCH_DEFINE_SIG_TEST1(TestName, signature)\
  677. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  678. static void TestName()
  679. #define INTERNAL_CATCH_DEFINE_SIG_TEST_X(TestName, signature,...)\
  680. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  681. static void TestName()
  682. #define INTERNAL_CATCH_NTTP_REGISTER0(TestFunc, signature)\
  683. template<typename Type>\
  684. void reg_test(TypeList<Type>, Catch::NameAndTags nameAndTags)\
  685. {\
  686. Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<Type>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\
  687. }
  688. #define INTERNAL_CATCH_NTTP_REGISTER(TestFunc, signature, ...)\
  689. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  690. void reg_test(Nttp<__VA_ARGS__>, Catch::NameAndTags nameAndTags)\
  691. {\
  692. Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<__VA_ARGS__>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\
  693. }
  694. #define INTERNAL_CATCH_NTTP_REGISTER_METHOD0(TestName, signature, ...)\
  695. template<typename Type>\
  696. void reg_test(TypeList<Type>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\
  697. {\
  698. Catch::AutoReg( Catch::makeTestInvoker(&TestName<Type>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\
  699. }
  700. #define INTERNAL_CATCH_NTTP_REGISTER_METHOD(TestName, signature, ...)\
  701. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  702. void reg_test(Nttp<__VA_ARGS__>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\
  703. {\
  704. Catch::AutoReg( Catch::makeTestInvoker(&TestName<__VA_ARGS__>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\
  705. }
  706. #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0(TestName, ClassName)
  707. #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1(TestName, ClassName, signature)\
  708. template<typename TestType> \
  709. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<TestType> { \
  710. void test();\
  711. }
  712. #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X(TestName, ClassName, signature, ...)\
  713. template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \
  714. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<__VA_ARGS__> { \
  715. void test();\
  716. }
  717. #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0(TestName)
  718. #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1(TestName, signature)\
  719. template<typename TestType> \
  720. void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<TestType>::test()
  721. #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X(TestName, signature, ...)\
  722. template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \
  723. void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<__VA_ARGS__>::test()
  724. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  725. #define INTERNAL_CATCH_NTTP_0
  726. #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)
  727. #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__)
  728. #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__)
  729. #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__)
  730. #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__)
  731. #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__)
  732. #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__)
  733. #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__)
  734. #else
  735. #define INTERNAL_CATCH_NTTP_0(signature)
  736. #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__))
  737. #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__))
  738. #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__))
  739. #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__))
  740. #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__))
  741. #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__))
  742. #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__))
  743. #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__))
  744. #endif
  745. // end catch_preprocessor.hpp
  746. // start catch_meta.hpp
  747. #include <type_traits>
  748. namespace Catch {
  749. template<typename T>
  750. struct always_false : std::false_type {};
  751. template <typename> struct true_given : std::true_type {};
  752. struct is_callable_tester {
  753. template <typename Fun, typename... Args>
  754. true_given<decltype(std::declval<Fun>()(std::declval<Args>()...))> static test(int);
  755. template <typename...>
  756. std::false_type static test(...);
  757. };
  758. template <typename T>
  759. struct is_callable;
  760. template <typename Fun, typename... Args>
  761. struct is_callable<Fun(Args...)> : decltype(is_callable_tester::test<Fun, Args...>(0)) {};
  762. } // namespace Catch
  763. namespace mpl_{
  764. struct na;
  765. }
  766. // end catch_meta.hpp
  767. namespace Catch {
  768. template<typename C>
  769. class TestInvokerAsMethod : public ITestInvoker {
  770. void (C::*m_testAsMethod)();
  771. public:
  772. TestInvokerAsMethod( void (C::*testAsMethod)() ) noexcept : m_testAsMethod( testAsMethod ) {}
  773. void invoke() const override {
  774. C obj;
  775. (obj.*m_testAsMethod)();
  776. }
  777. };
  778. auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker*;
  779. template<typename C>
  780. auto makeTestInvoker( void (C::*testAsMethod)() ) noexcept -> ITestInvoker* {
  781. return new(std::nothrow) TestInvokerAsMethod<C>( testAsMethod );
  782. }
  783. struct NameAndTags {
  784. NameAndTags( StringRef const& name_ = StringRef(), StringRef const& tags_ = StringRef() ) noexcept;
  785. StringRef name;
  786. StringRef tags;
  787. };
  788. struct AutoReg : NonCopyable {
  789. AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept;
  790. ~AutoReg();
  791. };
  792. } // end namespace Catch
  793. #if defined(CATCH_CONFIG_DISABLE)
  794. #define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( TestName, ... ) \
  795. static void TestName()
  796. #define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( TestName, ClassName, ... ) \
  797. namespace{ \
  798. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
  799. void test(); \
  800. }; \
  801. } \
  802. void TestName::test()
  803. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( TestName, TestFunc, Name, Tags, Signature, ... ) \
  804. INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature))
  805. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... ) \
  806. namespace{ \
  807. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
  808. INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
  809. } \
  810. } \
  811. INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))
  812. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  813. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \
  814. 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__ )
  815. #else
  816. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \
  817. 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__ ) )
  818. #endif
  819. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  820. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \
  821. 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__ )
  822. #else
  823. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \
  824. 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__ ) )
  825. #endif
  826. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  827. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \
  828. 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__ )
  829. #else
  830. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \
  831. 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__ ) )
  832. #endif
  833. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  834. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \
  835. 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__ )
  836. #else
  837. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \
  838. 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__ ) )
  839. #endif
  840. #endif
  841. ///////////////////////////////////////////////////////////////////////////////
  842. #define INTERNAL_CATCH_TESTCASE2( TestName, ... ) \
  843. static void TestName(); \
  844. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  845. namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &TestName ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
  846. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  847. static void TestName()
  848. #define INTERNAL_CATCH_TESTCASE( ... ) \
  849. INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), __VA_ARGS__ )
  850. ///////////////////////////////////////////////////////////////////////////////
  851. #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \
  852. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  853. namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &QualifiedMethod ), CATCH_INTERNAL_LINEINFO, "&" #QualifiedMethod, Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
  854. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  855. ///////////////////////////////////////////////////////////////////////////////
  856. #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestName, ClassName, ... )\
  857. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  858. namespace{ \
  859. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
  860. void test(); \
  861. }; \
  862. Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( Catch::makeTestInvoker( &TestName::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
  863. } \
  864. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  865. void TestName::test()
  866. #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \
  867. INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, __VA_ARGS__ )
  868. ///////////////////////////////////////////////////////////////////////////////
  869. #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \
  870. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  871. Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( Function ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
  872. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  873. ///////////////////////////////////////////////////////////////////////////////
  874. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_2(TestName, TestFunc, Name, Tags, Signature, ... )\
  875. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  876. CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
  877. INTERNAL_CATCH_DECLARE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
  878. namespace {\
  879. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\
  880. INTERNAL_CATCH_TYPE_GEN\
  881. INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
  882. INTERNAL_CATCH_NTTP_REG_GEN(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature))\
  883. template<typename...Types> \
  884. struct TestName{\
  885. TestName(){\
  886. int index = 0; \
  887. constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\
  888. using expander = int[];\
  889. (void)expander{(reg_test(Types{}, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++, 0)... };/* NOLINT */ \
  890. }\
  891. };\
  892. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
  893. TestName<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\
  894. return 0;\
  895. }();\
  896. }\
  897. }\
  898. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  899. CATCH_INTERNAL_UNSUPPRESS_ZERO_VARIADIC_WARNINGS \
  900. INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature))
  901. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  902. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
  903. 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__ )
  904. #else
  905. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
  906. 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__ ) )
  907. #endif
  908. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  909. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \
  910. 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__ )
  911. #else
  912. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \
  913. 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__ ) )
  914. #endif
  915. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(TestName, TestFuncName, Name, Tags, Signature, TmplTypes, TypesList) \
  916. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  917. CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
  918. template<typename TestType> static void TestFuncName(); \
  919. namespace {\
  920. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
  921. INTERNAL_CATCH_TYPE_GEN \
  922. INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature)) \
  923. template<typename... Types> \
  924. struct TestName { \
  925. void reg_tests() { \
  926. int index = 0; \
  927. using expander = int[]; \
  928. constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\
  929. constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\
  930. constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\
  931. (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++, 0)... };/* NOLINT */\
  932. } \
  933. }; \
  934. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \
  935. using TestInit = decltype(create<TestName, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>(TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(INTERNAL_CATCH_REMOVE_PARENS(TypesList))>{})); \
  936. TestInit t; \
  937. t.reg_tests(); \
  938. return 0; \
  939. }(); \
  940. } \
  941. } \
  942. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  943. CATCH_INTERNAL_UNSUPPRESS_ZERO_VARIADIC_WARNINGS \
  944. template<typename TestType> \
  945. static void TestFuncName()
  946. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  947. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\
  948. 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__)
  949. #else
  950. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\
  951. 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__ ) )
  952. #endif
  953. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  954. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\
  955. 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__)
  956. #else
  957. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\
  958. 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__ ) )
  959. #endif
  960. #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2(TestName, TestFunc, Name, Tags, TmplList)\
  961. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  962. template<typename TestType> static void TestFunc(); \
  963. namespace {\
  964. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\
  965. INTERNAL_CATCH_TYPE_GEN\
  966. template<typename... Types> \
  967. struct TestName { \
  968. void reg_tests() { \
  969. int index = 0; \
  970. using expander = int[]; \
  971. (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++, 0)... };/* NOLINT */\
  972. } \
  973. };\
  974. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \
  975. using TestInit = decltype(convert<TestName>(std::declval<TmplList>())); \
  976. TestInit t; \
  977. t.reg_tests(); \
  978. return 0; \
  979. }(); \
  980. }}\
  981. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  982. template<typename TestType> \
  983. static void TestFunc()
  984. #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(Name, Tags, TmplList) \
  985. 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 )
  986. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... ) \
  987. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  988. CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
  989. namespace {\
  990. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \
  991. INTERNAL_CATCH_TYPE_GEN\
  992. INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
  993. INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
  994. INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))\
  995. template<typename...Types> \
  996. struct TestNameClass{\
  997. TestNameClass(){\
  998. int index = 0; \
  999. constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\
  1000. using expander = int[];\
  1001. (void)expander{(reg_test(Types{}, #ClassName, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++, 0)... };/* NOLINT */ \
  1002. }\
  1003. };\
  1004. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
  1005. TestNameClass<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\
  1006. return 0;\
  1007. }();\
  1008. }\
  1009. }\
  1010. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS\
  1011. CATCH_INTERNAL_UNSUPPRESS_ZERO_VARIADIC_WARNINGS\
  1012. INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))
  1013. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  1014. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \
  1015. 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__ )
  1016. #else
  1017. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \
  1018. 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__ ) )
  1019. #endif
  1020. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  1021. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \
  1022. 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__ )
  1023. #else
  1024. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \
  1025. 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__ ) )
  1026. #endif
  1027. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2(TestNameClass, TestName, ClassName, Name, Tags, Signature, TmplTypes, TypesList)\
  1028. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  1029. CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
  1030. template<typename TestType> \
  1031. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \
  1032. void test();\
  1033. };\
  1034. namespace {\
  1035. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestNameClass) {\
  1036. INTERNAL_CATCH_TYPE_GEN \
  1037. INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
  1038. template<typename...Types>\
  1039. struct TestNameClass{\
  1040. void reg_tests(){\
  1041. int index = 0;\
  1042. using expander = int[];\
  1043. constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\
  1044. constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\
  1045. constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\
  1046. (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++, 0)... };/* NOLINT */ \
  1047. }\
  1048. };\
  1049. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
  1050. using TestInit = decltype(create<TestNameClass, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>(TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(INTERNAL_CATCH_REMOVE_PARENS(TypesList))>{}));\
  1051. TestInit t;\
  1052. t.reg_tests();\
  1053. return 0;\
  1054. }(); \
  1055. }\
  1056. }\
  1057. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  1058. CATCH_INTERNAL_UNSUPPRESS_ZERO_VARIADIC_WARNINGS \
  1059. template<typename TestType> \
  1060. void TestName<TestType>::test()
  1061. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  1062. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\
  1063. 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__ )
  1064. #else
  1065. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\
  1066. 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__ ) )
  1067. #endif
  1068. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  1069. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\
  1070. 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__ )
  1071. #else
  1072. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\
  1073. 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__ ) )
  1074. #endif
  1075. #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, TmplList) \
  1076. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  1077. template<typename TestType> \
  1078. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \
  1079. void test();\
  1080. };\
  1081. namespace {\
  1082. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \
  1083. INTERNAL_CATCH_TYPE_GEN\
  1084. template<typename...Types>\
  1085. struct TestNameClass{\
  1086. void reg_tests(){\
  1087. int index = 0;\
  1088. using expander = int[];\
  1089. (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++, 0)... };/* NOLINT */ \
  1090. }\
  1091. };\
  1092. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
  1093. using TestInit = decltype(convert<TestNameClass>(std::declval<TmplList>()));\
  1094. TestInit t;\
  1095. t.reg_tests();\
  1096. return 0;\
  1097. }(); \
  1098. }}\
  1099. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  1100. template<typename TestType> \
  1101. void TestName<TestType>::test()
  1102. #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD(ClassName, Name, Tags, TmplList) \
  1103. 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 )
  1104. // end catch_test_registry.h
  1105. // start catch_capture.hpp
  1106. // start catch_assertionhandler.h
  1107. // start catch_assertioninfo.h
  1108. // start catch_result_type.h
  1109. namespace Catch {
  1110. // ResultWas::OfType enum
  1111. struct ResultWas { enum OfType {
  1112. Unknown = -1,
  1113. Ok = 0,
  1114. Info = 1,
  1115. Warning = 2,
  1116. FailureBit = 0x10,
  1117. ExpressionFailed = FailureBit | 1,
  1118. ExplicitFailure = FailureBit | 2,
  1119. Exception = 0x100 | FailureBit,
  1120. ThrewException = Exception | 1,
  1121. DidntThrowException = Exception | 2,
  1122. FatalErrorCondition = 0x200 | FailureBit
  1123. }; };
  1124. bool isOk( ResultWas::OfType resultType );
  1125. bool isJustInfo( int flags );
  1126. // ResultDisposition::Flags enum
  1127. struct ResultDisposition { enum Flags {
  1128. Normal = 0x01,
  1129. ContinueOnFailure = 0x02, // Failures fail test, but execution continues
  1130. FalseTest = 0x04, // Prefix expression with !
  1131. SuppressFail = 0x08 // Failures are reported but do not fail the test
  1132. }; };
  1133. ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs );
  1134. bool shouldContinueOnFailure( int flags );
  1135. inline bool isFalseTest( int flags ) { return ( flags & ResultDisposition::FalseTest ) != 0; }
  1136. bool shouldSuppressFailure( int flags );
  1137. } // end namespace Catch
  1138. // end catch_result_type.h
  1139. namespace Catch {
  1140. struct AssertionInfo
  1141. {
  1142. StringRef macroName;
  1143. SourceLineInfo lineInfo;
  1144. StringRef capturedExpression;
  1145. ResultDisposition::Flags resultDisposition;
  1146. // We want to delete this constructor but a compiler bug in 4.8 means
  1147. // the struct is then treated as non-aggregate
  1148. //AssertionInfo() = delete;
  1149. };
  1150. } // end namespace Catch
  1151. // end catch_assertioninfo.h
  1152. // start catch_decomposer.h
  1153. // start catch_tostring.h
  1154. #include <vector>
  1155. #include <cstddef>
  1156. #include <type_traits>
  1157. #include <string>
  1158. // start catch_stream.h
  1159. #include <iosfwd>
  1160. #include <cstddef>
  1161. #include <ostream>
  1162. namespace Catch {
  1163. std::ostream& cout();
  1164. std::ostream& cerr();
  1165. std::ostream& clog();
  1166. class StringRef;
  1167. struct IStream {
  1168. virtual ~IStream();
  1169. virtual std::ostream& stream() const = 0;
  1170. };
  1171. auto makeStream( StringRef const &filename ) -> IStream const*;
  1172. class ReusableStringStream {
  1173. std::size_t m_index;
  1174. std::ostream* m_oss;
  1175. public:
  1176. ReusableStringStream();
  1177. ~ReusableStringStream();
  1178. auto str() const -> std::string;
  1179. template<typename T>
  1180. auto operator << ( T const& value ) -> ReusableStringStream& {
  1181. *m_oss << value;
  1182. return *this;
  1183. }
  1184. auto get() -> std::ostream& { return *m_oss; }
  1185. };
  1186. }
  1187. // end catch_stream.h
  1188. // start catch_interfaces_enum_values_registry.h
  1189. #include <vector>
  1190. namespace Catch {
  1191. namespace Detail {
  1192. struct EnumInfo {
  1193. StringRef m_name;
  1194. std::vector<std::pair<int, std::string>> m_values;
  1195. ~EnumInfo();
  1196. StringRef lookup( int value ) const;
  1197. };
  1198. } // namespace Detail
  1199. struct IMutableEnumValuesRegistry {
  1200. virtual ~IMutableEnumValuesRegistry();
  1201. virtual Detail::EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::vector<int> const& values ) = 0;
  1202. template<typename E>
  1203. Detail::EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::initializer_list<E> values ) {
  1204. std::vector<int> intValues;
  1205. intValues.reserve( values.size() );
  1206. for( auto enumValue : values )
  1207. intValues.push_back( static_cast<int>( enumValue ) );
  1208. return registerEnum( enumName, allEnums, intValues );
  1209. }
  1210. };
  1211. } // Catch
  1212. // end catch_interfaces_enum_values_registry.h
  1213. #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  1214. #include <string_view>
  1215. #endif
  1216. #ifdef __OBJC__
  1217. // start catch_objc_arc.hpp
  1218. #import <Foundation/Foundation.h>
  1219. #ifdef __has_feature
  1220. #define CATCH_ARC_ENABLED __has_feature(objc_arc)
  1221. #else
  1222. #define CATCH_ARC_ENABLED 0
  1223. #endif
  1224. void arcSafeRelease( NSObject* obj );
  1225. id performOptionalSelector( id obj, SEL sel );
  1226. #if !CATCH_ARC_ENABLED
  1227. inline void arcSafeRelease( NSObject* obj ) {
  1228. [obj release];
  1229. }
  1230. inline id performOptionalSelector( id obj, SEL sel ) {
  1231. if( [obj respondsToSelector: sel] )
  1232. return [obj performSelector: sel];
  1233. return nil;
  1234. }
  1235. #define CATCH_UNSAFE_UNRETAINED
  1236. #define CATCH_ARC_STRONG
  1237. #else
  1238. inline void arcSafeRelease( NSObject* ){}
  1239. inline id performOptionalSelector( id obj, SEL sel ) {
  1240. #ifdef __clang__
  1241. #pragma clang diagnostic push
  1242. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  1243. #endif
  1244. if( [obj respondsToSelector: sel] )
  1245. return [obj performSelector: sel];
  1246. #ifdef __clang__
  1247. #pragma clang diagnostic pop
  1248. #endif
  1249. return nil;
  1250. }
  1251. #define CATCH_UNSAFE_UNRETAINED __unsafe_unretained
  1252. #define CATCH_ARC_STRONG __strong
  1253. #endif
  1254. // end catch_objc_arc.hpp
  1255. #endif
  1256. #ifdef _MSC_VER
  1257. #pragma warning(push)
  1258. #pragma warning(disable:4180) // We attempt to stream a function (address) by const&, which MSVC complains about but is harmless
  1259. #endif
  1260. namespace Catch {
  1261. namespace Detail {
  1262. extern const std::string unprintableString;
  1263. std::string rawMemoryToString( const void *object, std::size_t size );
  1264. template<typename T>
  1265. std::string rawMemoryToString( const T& object ) {
  1266. return rawMemoryToString( &object, sizeof(object) );
  1267. }
  1268. template<typename T>
  1269. class IsStreamInsertable {
  1270. template<typename SS, typename TT>
  1271. static auto test(int)
  1272. -> decltype(std::declval<SS&>() << std::declval<TT>(), std::true_type());
  1273. template<typename, typename>
  1274. static auto test(...)->std::false_type;
  1275. public:
  1276. static const bool value = decltype(test<std::ostream, const T&>(0))::value;
  1277. };
  1278. template<typename E>
  1279. std::string convertUnknownEnumToString( E e );
  1280. template<typename T>
  1281. typename std::enable_if<
  1282. !std::is_enum<T>::value && !std::is_base_of<std::exception, T>::value,
  1283. std::string>::type convertUnstreamable( T const& ) {
  1284. return Detail::unprintableString;
  1285. }
  1286. template<typename T>
  1287. typename std::enable_if<
  1288. !std::is_enum<T>::value && std::is_base_of<std::exception, T>::value,
  1289. std::string>::type convertUnstreamable(T const& ex) {
  1290. return ex.what();
  1291. }
  1292. template<typename T>
  1293. typename std::enable_if<
  1294. std::is_enum<T>::value
  1295. , std::string>::type convertUnstreamable( T const& value ) {
  1296. return convertUnknownEnumToString( value );
  1297. }
  1298. #if defined(_MANAGED)
  1299. //! Convert a CLR string to a utf8 std::string
  1300. template<typename T>
  1301. std::string clrReferenceToString( T^ ref ) {
  1302. if (ref == nullptr)
  1303. return std::string("null");
  1304. auto bytes = System::Text::Encoding::UTF8->GetBytes(ref->ToString());
  1305. cli::pin_ptr<System::Byte> p = &bytes[0];
  1306. return std::string(reinterpret_cast<char const *>(p), bytes->Length);
  1307. }
  1308. #endif
  1309. } // namespace Detail
  1310. // If we decide for C++14, change these to enable_if_ts
  1311. template <typename T, typename = void>
  1312. struct StringMaker {
  1313. template <typename Fake = T>
  1314. static
  1315. typename std::enable_if<::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
  1316. convert(const Fake& value) {
  1317. ReusableStringStream rss;
  1318. // NB: call using the function-like syntax to avoid ambiguity with
  1319. // user-defined templated operator<< under clang.
  1320. rss.operator<<(value);
  1321. return rss.str();
  1322. }
  1323. template <typename Fake = T>
  1324. static
  1325. typename std::enable_if<!::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
  1326. convert( const Fake& value ) {
  1327. #if !defined(CATCH_CONFIG_FALLBACK_STRINGIFIER)
  1328. return Detail::convertUnstreamable(value);
  1329. #else
  1330. return CATCH_CONFIG_FALLBACK_STRINGIFIER(value);
  1331. #endif
  1332. }
  1333. };
  1334. namespace Detail {
  1335. // This function dispatches all stringification requests inside of Catch.
  1336. // Should be preferably called fully qualified, like ::Catch::Detail::stringify
  1337. template <typename T>
  1338. std::string stringify(const T& e) {
  1339. return ::Catch::StringMaker<typename std::remove_cv<typename std::remove_reference<T>::type>::type>::convert(e);
  1340. }
  1341. template<typename E>
  1342. std::string convertUnknownEnumToString( E e ) {
  1343. return ::Catch::Detail::stringify(static_cast<typename std::underlying_type<E>::type>(e));
  1344. }
  1345. #if defined(_MANAGED)
  1346. template <typename T>
  1347. std::string stringify( T^ e ) {
  1348. return ::Catch::StringMaker<T^>::convert(e);
  1349. }
  1350. #endif
  1351. } // namespace Detail
  1352. // Some predefined specializations
  1353. template<>
  1354. struct StringMaker<std::string> {
  1355. static std::string convert(const std::string& str);
  1356. };
  1357. #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  1358. template<>
  1359. struct StringMaker<std::string_view> {
  1360. static std::string convert(std::string_view str);
  1361. };
  1362. #endif
  1363. template<>
  1364. struct StringMaker<char const *> {
  1365. static std::string convert(char const * str);
  1366. };
  1367. template<>
  1368. struct StringMaker<char *> {
  1369. static std::string convert(char * str);
  1370. };
  1371. #ifdef CATCH_CONFIG_WCHAR
  1372. template<>
  1373. struct StringMaker<std::wstring> {
  1374. static std::string convert(const std::wstring& wstr);
  1375. };
  1376. # ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  1377. template<>
  1378. struct StringMaker<std::wstring_view> {
  1379. static std::string convert(std::wstring_view str);
  1380. };
  1381. # endif
  1382. template<>
  1383. struct StringMaker<wchar_t const *> {
  1384. static std::string convert(wchar_t const * str);
  1385. };
  1386. template<>
  1387. struct StringMaker<wchar_t *> {
  1388. static std::string convert(wchar_t * str);
  1389. };
  1390. #endif
  1391. // TBD: Should we use `strnlen` to ensure that we don't go out of the buffer,
  1392. // while keeping string semantics?
  1393. template<int SZ>
  1394. struct StringMaker<char[SZ]> {
  1395. static std::string convert(char const* str) {
  1396. return ::Catch::Detail::stringify(std::string{ str });
  1397. }
  1398. };
  1399. template<int SZ>
  1400. struct StringMaker<signed char[SZ]> {
  1401. static std::string convert(signed char const* str) {
  1402. return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) });
  1403. }
  1404. };
  1405. template<int SZ>
  1406. struct StringMaker<unsigned char[SZ]> {
  1407. static std::string convert(unsigned char const* str) {
  1408. return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) });
  1409. }
  1410. };
  1411. #if defined(CATCH_CONFIG_CPP17_BYTE)
  1412. template<>
  1413. struct StringMaker<std::byte> {
  1414. static std::string convert(std::byte value);
  1415. };
  1416. #endif // defined(CATCH_CONFIG_CPP17_BYTE)
  1417. template<>
  1418. struct StringMaker<int> {
  1419. static std::string convert(int value);
  1420. };
  1421. template<>
  1422. struct StringMaker<long> {
  1423. static std::string convert(long value);
  1424. };
  1425. template<>
  1426. struct StringMaker<long long> {
  1427. static std::string convert(long long value);
  1428. };
  1429. template<>
  1430. struct StringMaker<unsigned int> {
  1431. static std::string convert(unsigned int value);
  1432. };
  1433. template<>
  1434. struct StringMaker<unsigned long> {
  1435. static std::string convert(unsigned long value);
  1436. };
  1437. template<>
  1438. struct StringMaker<unsigned long long> {
  1439. static std::string convert(unsigned long long value);
  1440. };
  1441. template<>
  1442. struct StringMaker<bool> {
  1443. static std::string convert(bool b);
  1444. };
  1445. template<>
  1446. struct StringMaker<char> {
  1447. static std::string convert(char c);
  1448. };
  1449. template<>
  1450. struct StringMaker<signed char> {
  1451. static std::string convert(signed char c);
  1452. };
  1453. template<>
  1454. struct StringMaker<unsigned char> {
  1455. static std::string convert(unsigned char c);
  1456. };
  1457. template<>
  1458. struct StringMaker<std::nullptr_t> {
  1459. static std::string convert(std::nullptr_t);
  1460. };
  1461. template<>
  1462. struct StringMaker<float> {
  1463. static std::string convert(float value);
  1464. static int precision;
  1465. };
  1466. template<>
  1467. struct StringMaker<double> {
  1468. static std::string convert(double value);
  1469. static int precision;
  1470. };
  1471. template <typename T>
  1472. struct StringMaker<T*> {
  1473. template <typename U>
  1474. static std::string convert(U* p) {
  1475. if (p) {
  1476. return ::Catch::Detail::rawMemoryToString(p);
  1477. } else {
  1478. return "nullptr";
  1479. }
  1480. }
  1481. };
  1482. template <typename R, typename C>
  1483. struct StringMaker<R C::*> {
  1484. static std::string convert(R C::* p) {
  1485. if (p) {
  1486. return ::Catch::Detail::rawMemoryToString(p);
  1487. } else {
  1488. return "nullptr";
  1489. }
  1490. }
  1491. };
  1492. #if defined(_MANAGED)
  1493. template <typename T>
  1494. struct StringMaker<T^> {
  1495. static std::string convert( T^ ref ) {
  1496. return ::Catch::Detail::clrReferenceToString(ref);
  1497. }
  1498. };
  1499. #endif
  1500. namespace Detail {
  1501. template<typename InputIterator>
  1502. std::string rangeToString(InputIterator first, InputIterator last) {
  1503. ReusableStringStream rss;
  1504. rss << "{ ";
  1505. if (first != last) {
  1506. rss << ::Catch::Detail::stringify(*first);
  1507. for (++first; first != last; ++first)
  1508. rss << ", " << ::Catch::Detail::stringify(*first);
  1509. }
  1510. rss << " }";
  1511. return rss.str();
  1512. }
  1513. }
  1514. #ifdef __OBJC__
  1515. template<>
  1516. struct StringMaker<NSString*> {
  1517. static std::string convert(NSString * nsstring) {
  1518. if (!nsstring)
  1519. return "nil";
  1520. return std::string("@") + [nsstring UTF8String];
  1521. }
  1522. };
  1523. template<>
  1524. struct StringMaker<NSObject*> {
  1525. static std::string convert(NSObject* nsObject) {
  1526. return ::Catch::Detail::stringify([nsObject description]);
  1527. }
  1528. };
  1529. namespace Detail {
  1530. inline std::string stringify( NSString* nsstring ) {
  1531. return StringMaker<NSString*>::convert( nsstring );
  1532. }
  1533. } // namespace Detail
  1534. #endif // __OBJC__
  1535. } // namespace Catch
  1536. //////////////////////////////////////////////////////
  1537. // Separate std-lib types stringification, so it can be selectively enabled
  1538. // This means that we do not bring in
  1539. #if defined(CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS)
  1540. # define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
  1541. # define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
  1542. # define CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
  1543. # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  1544. # define CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
  1545. #endif
  1546. // Separate std::pair specialization
  1547. #if defined(CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER)
  1548. #include <utility>
  1549. namespace Catch {
  1550. template<typename T1, typename T2>
  1551. struct StringMaker<std::pair<T1, T2> > {
  1552. static std::string convert(const std::pair<T1, T2>& pair) {
  1553. ReusableStringStream rss;
  1554. rss << "{ "
  1555. << ::Catch::Detail::stringify(pair.first)
  1556. << ", "
  1557. << ::Catch::Detail::stringify(pair.second)
  1558. << " }";
  1559. return rss.str();
  1560. }
  1561. };
  1562. }
  1563. #endif // CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
  1564. #if defined(CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_OPTIONAL)
  1565. #include <optional>
  1566. namespace Catch {
  1567. template<typename T>
  1568. struct StringMaker<std::optional<T> > {
  1569. static std::string convert(const std::optional<T>& optional) {
  1570. ReusableStringStream rss;
  1571. if (optional.has_value()) {
  1572. rss << ::Catch::Detail::stringify(*optional);
  1573. } else {
  1574. rss << "{ }";
  1575. }
  1576. return rss.str();
  1577. }
  1578. };
  1579. }
  1580. #endif // CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
  1581. // Separate std::tuple specialization
  1582. #if defined(CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER)
  1583. #include <tuple>
  1584. namespace Catch {
  1585. namespace Detail {
  1586. template<
  1587. typename Tuple,
  1588. std::size_t N = 0,
  1589. bool = (N < std::tuple_size<Tuple>::value)
  1590. >
  1591. struct TupleElementPrinter {
  1592. static void print(const Tuple& tuple, std::ostream& os) {
  1593. os << (N ? ", " : " ")
  1594. << ::Catch::Detail::stringify(std::get<N>(tuple));
  1595. TupleElementPrinter<Tuple, N + 1>::print(tuple, os);
  1596. }
  1597. };
  1598. template<
  1599. typename Tuple,
  1600. std::size_t N
  1601. >
  1602. struct TupleElementPrinter<Tuple, N, false> {
  1603. static void print(const Tuple&, std::ostream&) {}
  1604. };
  1605. }
  1606. template<typename ...Types>
  1607. struct StringMaker<std::tuple<Types...>> {
  1608. static std::string convert(const std::tuple<Types...>& tuple) {
  1609. ReusableStringStream rss;
  1610. rss << '{';
  1611. Detail::TupleElementPrinter<std::tuple<Types...>>::print(tuple, rss.get());
  1612. rss << " }";
  1613. return rss.str();
  1614. }
  1615. };
  1616. }
  1617. #endif // CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
  1618. #if defined(CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_VARIANT)
  1619. #include <variant>
  1620. namespace Catch {
  1621. template<>
  1622. struct StringMaker<std::monostate> {
  1623. static std::string convert(const std::monostate&) {
  1624. return "{ }";
  1625. }
  1626. };
  1627. template<typename... Elements>
  1628. struct StringMaker<std::variant<Elements...>> {
  1629. static std::string convert(const std::variant<Elements...>& variant) {
  1630. if (variant.valueless_by_exception()) {
  1631. return "{valueless variant}";
  1632. } else {
  1633. return std::visit(
  1634. [](const auto& value) {
  1635. return ::Catch::Detail::stringify(value);
  1636. },
  1637. variant
  1638. );
  1639. }
  1640. }
  1641. };
  1642. }
  1643. #endif // CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
  1644. namespace Catch {
  1645. struct not_this_one {}; // Tag type for detecting which begin/ end are being selected
  1646. // Import begin/ end from std here so they are considered alongside the fallback (...) overloads in this namespace
  1647. using std::begin;
  1648. using std::end;
  1649. not_this_one begin( ... );
  1650. not_this_one end( ... );
  1651. template <typename T>
  1652. struct is_range {
  1653. static const bool value =
  1654. !std::is_same<decltype(begin(std::declval<T>())), not_this_one>::value &&
  1655. !std::is_same<decltype(end(std::declval<T>())), not_this_one>::value;
  1656. };
  1657. #if defined(_MANAGED) // Managed types are never ranges
  1658. template <typename T>
  1659. struct is_range<T^> {
  1660. static const bool value = false;
  1661. };
  1662. #endif
  1663. template<typename Range>
  1664. std::string rangeToString( Range const& range ) {
  1665. return ::Catch::Detail::rangeToString( begin( range ), end( range ) );
  1666. }
  1667. // Handle vector<bool> specially
  1668. template<typename Allocator>
  1669. std::string rangeToString( std::vector<bool, Allocator> const& v ) {
  1670. ReusableStringStream rss;
  1671. rss << "{ ";
  1672. bool first = true;
  1673. for( bool b : v ) {
  1674. if( first )
  1675. first = false;
  1676. else
  1677. rss << ", ";
  1678. rss << ::Catch::Detail::stringify( b );
  1679. }
  1680. rss << " }";
  1681. return rss.str();
  1682. }
  1683. template<typename R>
  1684. struct StringMaker<R, typename std::enable_if<is_range<R>::value && !::Catch::Detail::IsStreamInsertable<R>::value>::type> {
  1685. static std::string convert( R const& range ) {
  1686. return rangeToString( range );
  1687. }
  1688. };
  1689. template <typename T, int SZ>
  1690. struct StringMaker<T[SZ]> {
  1691. static std::string convert(T const(&arr)[SZ]) {
  1692. return rangeToString(arr);
  1693. }
  1694. };
  1695. } // namespace Catch
  1696. // Separate std::chrono::duration specialization
  1697. #if defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  1698. #include <ctime>
  1699. #include <ratio>
  1700. #include <chrono>
  1701. namespace Catch {
  1702. template <class Ratio>
  1703. struct ratio_string {
  1704. static std::string symbol();
  1705. };
  1706. template <class Ratio>
  1707. std::string ratio_string<Ratio>::symbol() {
  1708. Catch::ReusableStringStream rss;
  1709. rss << '[' << Ratio::num << '/'
  1710. << Ratio::den << ']';
  1711. return rss.str();
  1712. }
  1713. template <>
  1714. struct ratio_string<std::atto> {
  1715. static std::string symbol();
  1716. };
  1717. template <>
  1718. struct ratio_string<std::femto> {
  1719. static std::string symbol();
  1720. };
  1721. template <>
  1722. struct ratio_string<std::pico> {
  1723. static std::string symbol();
  1724. };
  1725. template <>
  1726. struct ratio_string<std::nano> {
  1727. static std::string symbol();
  1728. };
  1729. template <>
  1730. struct ratio_string<std::micro> {
  1731. static std::string symbol();
  1732. };
  1733. template <>
  1734. struct ratio_string<std::milli> {
  1735. static std::string symbol();
  1736. };
  1737. ////////////
  1738. // std::chrono::duration specializations
  1739. template<typename Value, typename Ratio>
  1740. struct StringMaker<std::chrono::duration<Value, Ratio>> {
  1741. static std::string convert(std::chrono::duration<Value, Ratio> const& duration) {
  1742. ReusableStringStream rss;
  1743. rss << duration.count() << ' ' << ratio_string<Ratio>::symbol() << 's';
  1744. return rss.str();
  1745. }
  1746. };
  1747. template<typename Value>
  1748. struct StringMaker<std::chrono::duration<Value, std::ratio<1>>> {
  1749. static std::string convert(std::chrono::duration<Value, std::ratio<1>> const& duration) {
  1750. ReusableStringStream rss;
  1751. rss << duration.count() << " s";
  1752. return rss.str();
  1753. }
  1754. };
  1755. template<typename Value>
  1756. struct StringMaker<std::chrono::duration<Value, std::ratio<60>>> {
  1757. static std::string convert(std::chrono::duration<Value, std::ratio<60>> const& duration) {
  1758. ReusableStringStream rss;
  1759. rss << duration.count() << " m";
  1760. return rss.str();
  1761. }
  1762. };
  1763. template<typename Value>
  1764. struct StringMaker<std::chrono::duration<Value, std::ratio<3600>>> {
  1765. static std::string convert(std::chrono::duration<Value, std::ratio<3600>> const& duration) {
  1766. ReusableStringStream rss;
  1767. rss << duration.count() << " h";
  1768. return rss.str();
  1769. }
  1770. };
  1771. ////////////
  1772. // std::chrono::time_point specialization
  1773. // Generic time_point cannot be specialized, only std::chrono::time_point<system_clock>
  1774. template<typename Clock, typename Duration>
  1775. struct StringMaker<std::chrono::time_point<Clock, Duration>> {
  1776. static std::string convert(std::chrono::time_point<Clock, Duration> const& time_point) {
  1777. return ::Catch::Detail::stringify(time_point.time_since_epoch()) + " since epoch";
  1778. }
  1779. };
  1780. // std::chrono::time_point<system_clock> specialization
  1781. template<typename Duration>
  1782. struct StringMaker<std::chrono::time_point<std::chrono::system_clock, Duration>> {
  1783. static std::string convert(std::chrono::time_point<std::chrono::system_clock, Duration> const& time_point) {
  1784. auto converted = std::chrono::system_clock::to_time_t(time_point);
  1785. #ifdef _MSC_VER
  1786. std::tm timeInfo = {};
  1787. gmtime_s(&timeInfo, &converted);
  1788. #else
  1789. std::tm* timeInfo = std::gmtime(&converted);
  1790. #endif
  1791. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  1792. char timeStamp[timeStampSize];
  1793. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  1794. #ifdef _MSC_VER
  1795. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  1796. #else
  1797. std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
  1798. #endif
  1799. return std::string(timeStamp);
  1800. }
  1801. };
  1802. }
  1803. #endif // CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  1804. #define INTERNAL_CATCH_REGISTER_ENUM( enumName, ... ) \
  1805. namespace Catch { \
  1806. template<> struct StringMaker<enumName> { \
  1807. static std::string convert( enumName value ) { \
  1808. static const auto& enumInfo = ::Catch::getMutableRegistryHub().getMutableEnumValuesRegistry().registerEnum( #enumName, #__VA_ARGS__, { __VA_ARGS__ } ); \
  1809. return enumInfo.lookup( static_cast<int>( value ) ); \
  1810. } \
  1811. }; \
  1812. }
  1813. #define CATCH_REGISTER_ENUM( enumName, ... ) INTERNAL_CATCH_REGISTER_ENUM( enumName, __VA_ARGS__ )
  1814. #ifdef _MSC_VER
  1815. #pragma warning(pop)
  1816. #endif
  1817. // end catch_tostring.h
  1818. #include <iosfwd>
  1819. #ifdef _MSC_VER
  1820. #pragma warning(push)
  1821. #pragma warning(disable:4389) // '==' : signed/unsigned mismatch
  1822. #pragma warning(disable:4018) // more "signed/unsigned mismatch"
  1823. #pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform)
  1824. #pragma warning(disable:4180) // qualifier applied to function type has no meaning
  1825. #pragma warning(disable:4800) // Forcing result to true or false
  1826. #endif
  1827. namespace Catch {
  1828. struct ITransientExpression {
  1829. auto isBinaryExpression() const -> bool { return m_isBinaryExpression; }
  1830. auto getResult() const -> bool { return m_result; }
  1831. virtual void streamReconstructedExpression( std::ostream &os ) const = 0;
  1832. ITransientExpression( bool isBinaryExpression, bool result )
  1833. : m_isBinaryExpression( isBinaryExpression ),
  1834. m_result( result )
  1835. {}
  1836. // We don't actually need a virtual destructor, but many static analysers
  1837. // complain if it's not here :-(
  1838. virtual ~ITransientExpression();
  1839. bool m_isBinaryExpression;
  1840. bool m_result;
  1841. };
  1842. void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs );
  1843. template<typename LhsT, typename RhsT>
  1844. class BinaryExpr : public ITransientExpression {
  1845. LhsT m_lhs;
  1846. StringRef m_op;
  1847. RhsT m_rhs;
  1848. void streamReconstructedExpression( std::ostream &os ) const override {
  1849. formatReconstructedExpression
  1850. ( os, Catch::Detail::stringify( m_lhs ), m_op, Catch::Detail::stringify( m_rhs ) );
  1851. }
  1852. public:
  1853. BinaryExpr( bool comparisonResult, LhsT lhs, StringRef op, RhsT rhs )
  1854. : ITransientExpression{ true, comparisonResult },
  1855. m_lhs( lhs ),
  1856. m_op( op ),
  1857. m_rhs( rhs )
  1858. {}
  1859. template<typename T>
  1860. auto operator && ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1861. static_assert(always_false<T>::value,
  1862. "chained comparisons are not supported inside assertions, "
  1863. "wrap the expression inside parentheses, or decompose it");
  1864. }
  1865. template<typename T>
  1866. auto operator || ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1867. static_assert(always_false<T>::value,
  1868. "chained comparisons are not supported inside assertions, "
  1869. "wrap the expression inside parentheses, or decompose it");
  1870. }
  1871. template<typename T>
  1872. auto operator == ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1873. static_assert(always_false<T>::value,
  1874. "chained comparisons are not supported inside assertions, "
  1875. "wrap the expression inside parentheses, or decompose it");
  1876. }
  1877. template<typename T>
  1878. auto operator != ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1879. static_assert(always_false<T>::value,
  1880. "chained comparisons are not supported inside assertions, "
  1881. "wrap the expression inside parentheses, or decompose it");
  1882. }
  1883. template<typename T>
  1884. auto operator > ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1885. static_assert(always_false<T>::value,
  1886. "chained comparisons are not supported inside assertions, "
  1887. "wrap the expression inside parentheses, or decompose it");
  1888. }
  1889. template<typename T>
  1890. auto operator < ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1891. static_assert(always_false<T>::value,
  1892. "chained comparisons are not supported inside assertions, "
  1893. "wrap the expression inside parentheses, or decompose it");
  1894. }
  1895. template<typename T>
  1896. auto operator >= ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1897. static_assert(always_false<T>::value,
  1898. "chained comparisons are not supported inside assertions, "
  1899. "wrap the expression inside parentheses, or decompose it");
  1900. }
  1901. template<typename T>
  1902. auto operator <= ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1903. static_assert(always_false<T>::value,
  1904. "chained comparisons are not supported inside assertions, "
  1905. "wrap the expression inside parentheses, or decompose it");
  1906. }
  1907. };
  1908. template<typename LhsT>
  1909. class UnaryExpr : public ITransientExpression {
  1910. LhsT m_lhs;
  1911. void streamReconstructedExpression( std::ostream &os ) const override {
  1912. os << Catch::Detail::stringify( m_lhs );
  1913. }
  1914. public:
  1915. explicit UnaryExpr( LhsT lhs )
  1916. : ITransientExpression{ false, static_cast<bool>(lhs) },
  1917. m_lhs( lhs )
  1918. {}
  1919. };
  1920. // Specialised comparison functions to handle equality comparisons between ints and pointers (NULL deduces as an int)
  1921. template<typename LhsT, typename RhsT>
  1922. auto compareEqual( LhsT const& lhs, RhsT const& rhs ) -> bool { return static_cast<bool>(lhs == rhs); }
  1923. template<typename T>
  1924. auto compareEqual( T* const& lhs, int rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
  1925. template<typename T>
  1926. auto compareEqual( T* const& lhs, long rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
  1927. template<typename T>
  1928. auto compareEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
  1929. template<typename T>
  1930. auto compareEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
  1931. template<typename LhsT, typename RhsT>
  1932. auto compareNotEqual( LhsT const& lhs, RhsT&& rhs ) -> bool { return static_cast<bool>(lhs != rhs); }
  1933. template<typename T>
  1934. auto compareNotEqual( T* const& lhs, int rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
  1935. template<typename T>
  1936. auto compareNotEqual( T* const& lhs, long rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
  1937. template<typename T>
  1938. auto compareNotEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
  1939. template<typename T>
  1940. auto compareNotEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
  1941. template<typename LhsT>
  1942. class ExprLhs {
  1943. LhsT m_lhs;
  1944. public:
  1945. explicit ExprLhs( LhsT lhs ) : m_lhs( lhs ) {}
  1946. template<typename RhsT>
  1947. auto operator == ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1948. return { compareEqual( m_lhs, rhs ), m_lhs, "==", rhs };
  1949. }
  1950. auto operator == ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
  1951. return { m_lhs == rhs, m_lhs, "==", rhs };
  1952. }
  1953. template<typename RhsT>
  1954. auto operator != ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1955. return { compareNotEqual( m_lhs, rhs ), m_lhs, "!=", rhs };
  1956. }
  1957. auto operator != ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
  1958. return { m_lhs != rhs, m_lhs, "!=", rhs };
  1959. }
  1960. template<typename RhsT>
  1961. auto operator > ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1962. return { static_cast<bool>(m_lhs > rhs), m_lhs, ">", rhs };
  1963. }
  1964. template<typename RhsT>
  1965. auto operator < ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1966. return { static_cast<bool>(m_lhs < rhs), m_lhs, "<", rhs };
  1967. }
  1968. template<typename RhsT>
  1969. auto operator >= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1970. return { static_cast<bool>(m_lhs >= rhs), m_lhs, ">=", rhs };
  1971. }
  1972. template<typename RhsT>
  1973. auto operator <= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1974. return { static_cast<bool>(m_lhs <= rhs), m_lhs, "<=", rhs };
  1975. }
  1976. template<typename RhsT>
  1977. auto operator && ( RhsT const& ) -> BinaryExpr<LhsT, RhsT const&> const {
  1978. static_assert(always_false<RhsT>::value,
  1979. "operator&& is not supported inside assertions, "
  1980. "wrap the expression inside parentheses, or decompose it");
  1981. }
  1982. template<typename RhsT>
  1983. auto operator || ( RhsT const& ) -> BinaryExpr<LhsT, RhsT const&> const {
  1984. static_assert(always_false<RhsT>::value,
  1985. "operator|| is not supported inside assertions, "
  1986. "wrap the expression inside parentheses, or decompose it");
  1987. }
  1988. auto makeUnaryExpr() const -> UnaryExpr<LhsT> {
  1989. return UnaryExpr<LhsT>{ m_lhs };
  1990. }
  1991. };
  1992. void handleExpression( ITransientExpression const& expr );
  1993. template<typename T>
  1994. void handleExpression( ExprLhs<T> const& expr ) {
  1995. handleExpression( expr.makeUnaryExpr() );
  1996. }
  1997. struct Decomposer {
  1998. template<typename T>
  1999. auto operator <= ( T const& lhs ) -> ExprLhs<T const&> {
  2000. return ExprLhs<T const&>{ lhs };
  2001. }
  2002. auto operator <=( bool value ) -> ExprLhs<bool> {
  2003. return ExprLhs<bool>{ value };
  2004. }
  2005. };
  2006. } // end namespace Catch
  2007. #ifdef _MSC_VER
  2008. #pragma warning(pop)
  2009. #endif
  2010. // end catch_decomposer.h
  2011. // start catch_interfaces_capture.h
  2012. #include <string>
  2013. #include <chrono>
  2014. namespace Catch {
  2015. class AssertionResult;
  2016. struct AssertionInfo;
  2017. struct SectionInfo;
  2018. struct SectionEndInfo;
  2019. struct MessageInfo;
  2020. struct MessageBuilder;
  2021. struct Counts;
  2022. struct AssertionReaction;
  2023. struct SourceLineInfo;
  2024. struct ITransientExpression;
  2025. struct IGeneratorTracker;
  2026. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  2027. struct BenchmarkInfo;
  2028. template <typename Duration = std::chrono::duration<double, std::nano>>
  2029. struct BenchmarkStats;
  2030. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  2031. struct IResultCapture {
  2032. virtual ~IResultCapture();
  2033. virtual bool sectionStarted( SectionInfo const& sectionInfo,
  2034. Counts& assertions ) = 0;
  2035. virtual void sectionEnded( SectionEndInfo const& endInfo ) = 0;
  2036. virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) = 0;
  2037. virtual auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& = 0;
  2038. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  2039. virtual void benchmarkPreparing( std::string const& name ) = 0;
  2040. virtual void benchmarkStarting( BenchmarkInfo const& info ) = 0;
  2041. virtual void benchmarkEnded( BenchmarkStats<> const& stats ) = 0;
  2042. virtual void benchmarkFailed( std::string const& error ) = 0;
  2043. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  2044. virtual void pushScopedMessage( MessageInfo const& message ) = 0;
  2045. virtual void popScopedMessage( MessageInfo const& message ) = 0;
  2046. virtual void emplaceUnscopedMessage( MessageBuilder const& builder ) = 0;
  2047. virtual void handleFatalErrorCondition( StringRef message ) = 0;
  2048. virtual void handleExpr
  2049. ( AssertionInfo const& info,
  2050. ITransientExpression const& expr,
  2051. AssertionReaction& reaction ) = 0;
  2052. virtual void handleMessage
  2053. ( AssertionInfo const& info,
  2054. ResultWas::OfType resultType,
  2055. StringRef const& message,
  2056. AssertionReaction& reaction ) = 0;
  2057. virtual void handleUnexpectedExceptionNotThrown
  2058. ( AssertionInfo const& info,
  2059. AssertionReaction& reaction ) = 0;
  2060. virtual void handleUnexpectedInflightException
  2061. ( AssertionInfo const& info,
  2062. std::string const& message,
  2063. AssertionReaction& reaction ) = 0;
  2064. virtual void handleIncomplete
  2065. ( AssertionInfo const& info ) = 0;
  2066. virtual void handleNonExpr
  2067. ( AssertionInfo const &info,
  2068. ResultWas::OfType resultType,
  2069. AssertionReaction &reaction ) = 0;
  2070. virtual bool lastAssertionPassed() = 0;
  2071. virtual void assertionPassed() = 0;
  2072. // Deprecated, do not use:
  2073. virtual std::string getCurrentTestName() const = 0;
  2074. virtual const AssertionResult* getLastResult() const = 0;
  2075. virtual void exceptionEarlyReported() = 0;
  2076. };
  2077. IResultCapture& getResultCapture();
  2078. }
  2079. // end catch_interfaces_capture.h
  2080. namespace Catch {
  2081. struct TestFailureException{};
  2082. struct AssertionResultData;
  2083. struct IResultCapture;
  2084. class RunContext;
  2085. class LazyExpression {
  2086. friend class AssertionHandler;
  2087. friend struct AssertionStats;
  2088. friend class RunContext;
  2089. ITransientExpression const* m_transientExpression = nullptr;
  2090. bool m_isNegated;
  2091. public:
  2092. LazyExpression( bool isNegated );
  2093. LazyExpression( LazyExpression const& other );
  2094. LazyExpression& operator = ( LazyExpression const& ) = delete;
  2095. explicit operator bool() const;
  2096. friend auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream&;
  2097. };
  2098. struct AssertionReaction {
  2099. bool shouldDebugBreak = false;
  2100. bool shouldThrow = false;
  2101. };
  2102. class AssertionHandler {
  2103. AssertionInfo m_assertionInfo;
  2104. AssertionReaction m_reaction;
  2105. bool m_completed = false;
  2106. IResultCapture& m_resultCapture;
  2107. public:
  2108. AssertionHandler
  2109. ( StringRef const& macroName,
  2110. SourceLineInfo const& lineInfo,
  2111. StringRef capturedExpression,
  2112. ResultDisposition::Flags resultDisposition );
  2113. ~AssertionHandler() {
  2114. if ( !m_completed ) {
  2115. m_resultCapture.handleIncomplete( m_assertionInfo );
  2116. }
  2117. }
  2118. template<typename T>
  2119. void handleExpr( ExprLhs<T> const& expr ) {
  2120. handleExpr( expr.makeUnaryExpr() );
  2121. }
  2122. void handleExpr( ITransientExpression const& expr );
  2123. void handleMessage(ResultWas::OfType resultType, StringRef const& message);
  2124. void handleExceptionThrownAsExpected();
  2125. void handleUnexpectedExceptionNotThrown();
  2126. void handleExceptionNotThrownAsExpected();
  2127. void handleThrowingCallSkipped();
  2128. void handleUnexpectedInflightException();
  2129. void complete();
  2130. void setCompleted();
  2131. // query
  2132. auto allowThrows() const -> bool;
  2133. };
  2134. void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString );
  2135. } // namespace Catch
  2136. // end catch_assertionhandler.h
  2137. // start catch_message.h
  2138. #include <string>
  2139. #include <vector>
  2140. namespace Catch {
  2141. struct MessageInfo {
  2142. MessageInfo( StringRef const& _macroName,
  2143. SourceLineInfo const& _lineInfo,
  2144. ResultWas::OfType _type );
  2145. StringRef macroName;
  2146. std::string message;
  2147. SourceLineInfo lineInfo;
  2148. ResultWas::OfType type;
  2149. unsigned int sequence;
  2150. bool operator == ( MessageInfo const& other ) const;
  2151. bool operator < ( MessageInfo const& other ) const;
  2152. private:
  2153. static unsigned int globalCount;
  2154. };
  2155. struct MessageStream {
  2156. template<typename T>
  2157. MessageStream& operator << ( T const& value ) {
  2158. m_stream << value;
  2159. return *this;
  2160. }
  2161. ReusableStringStream m_stream;
  2162. };
  2163. struct MessageBuilder : MessageStream {
  2164. MessageBuilder( StringRef const& macroName,
  2165. SourceLineInfo const& lineInfo,
  2166. ResultWas::OfType type );
  2167. template<typename T>
  2168. MessageBuilder& operator << ( T const& value ) {
  2169. m_stream << value;
  2170. return *this;
  2171. }
  2172. MessageInfo m_info;
  2173. };
  2174. class ScopedMessage {
  2175. public:
  2176. explicit ScopedMessage( MessageBuilder const& builder );
  2177. ScopedMessage( ScopedMessage& duplicate ) = delete;
  2178. ScopedMessage( ScopedMessage&& old );
  2179. ~ScopedMessage();
  2180. MessageInfo m_info;
  2181. bool m_moved;
  2182. };
  2183. class Capturer {
  2184. std::vector<MessageInfo> m_messages;
  2185. IResultCapture& m_resultCapture = getResultCapture();
  2186. size_t m_captured = 0;
  2187. public:
  2188. Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names );
  2189. ~Capturer();
  2190. void captureValue( size_t index, std::string const& value );
  2191. template<typename T>
  2192. void captureValues( size_t index, T const& value ) {
  2193. captureValue( index, Catch::Detail::stringify( value ) );
  2194. }
  2195. template<typename T, typename... Ts>
  2196. void captureValues( size_t index, T const& value, Ts const&... values ) {
  2197. captureValue( index, Catch::Detail::stringify(value) );
  2198. captureValues( index+1, values... );
  2199. }
  2200. };
  2201. } // end namespace Catch
  2202. // end catch_message.h
  2203. #if !defined(CATCH_CONFIG_DISABLE)
  2204. #if !defined(CATCH_CONFIG_DISABLE_STRINGIFICATION)
  2205. #define CATCH_INTERNAL_STRINGIFY(...) #__VA_ARGS__
  2206. #else
  2207. #define CATCH_INTERNAL_STRINGIFY(...) "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION"
  2208. #endif
  2209. #if defined(CATCH_CONFIG_FAST_COMPILE) || defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  2210. ///////////////////////////////////////////////////////////////////////////////
  2211. // Another way to speed-up compilation is to omit local try-catch for REQUIRE*
  2212. // macros.
  2213. #define INTERNAL_CATCH_TRY
  2214. #define INTERNAL_CATCH_CATCH( capturer )
  2215. #else // CATCH_CONFIG_FAST_COMPILE
  2216. #define INTERNAL_CATCH_TRY try
  2217. #define INTERNAL_CATCH_CATCH( handler ) catch(...) { handler.handleUnexpectedInflightException(); }
  2218. #endif
  2219. #define INTERNAL_CATCH_REACT( handler ) handler.complete();
  2220. ///////////////////////////////////////////////////////////////////////////////
  2221. #define INTERNAL_CATCH_TEST( macroName, resultDisposition, ... ) \
  2222. do { \
  2223. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
  2224. INTERNAL_CATCH_TRY { \
  2225. CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
  2226. catchAssertionHandler.handleExpr( Catch::Decomposer() <= __VA_ARGS__ ); \
  2227. CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
  2228. } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
  2229. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2230. } while( (void)0, (false) && static_cast<bool>( !!(__VA_ARGS__) ) ) // the expression here is never evaluated at runtime but it forces the compiler to give it a look
  2231. // The double negation silences MSVC's C4800 warning, the static_cast forces short-circuit evaluation if the type has overloaded &&.
  2232. ///////////////////////////////////////////////////////////////////////////////
  2233. #define INTERNAL_CATCH_IF( macroName, resultDisposition, ... ) \
  2234. INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
  2235. if( Catch::getResultCapture().lastAssertionPassed() )
  2236. ///////////////////////////////////////////////////////////////////////////////
  2237. #define INTERNAL_CATCH_ELSE( macroName, resultDisposition, ... ) \
  2238. INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
  2239. if( !Catch::getResultCapture().lastAssertionPassed() )
  2240. ///////////////////////////////////////////////////////////////////////////////
  2241. #define INTERNAL_CATCH_NO_THROW( macroName, resultDisposition, ... ) \
  2242. do { \
  2243. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
  2244. try { \
  2245. static_cast<void>(__VA_ARGS__); \
  2246. catchAssertionHandler.handleExceptionNotThrownAsExpected(); \
  2247. } \
  2248. catch( ... ) { \
  2249. catchAssertionHandler.handleUnexpectedInflightException(); \
  2250. } \
  2251. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2252. } while( false )
  2253. ///////////////////////////////////////////////////////////////////////////////
  2254. #define INTERNAL_CATCH_THROWS( macroName, resultDisposition, ... ) \
  2255. do { \
  2256. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition); \
  2257. if( catchAssertionHandler.allowThrows() ) \
  2258. try { \
  2259. static_cast<void>(__VA_ARGS__); \
  2260. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  2261. } \
  2262. catch( ... ) { \
  2263. catchAssertionHandler.handleExceptionThrownAsExpected(); \
  2264. } \
  2265. else \
  2266. catchAssertionHandler.handleThrowingCallSkipped(); \
  2267. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2268. } while( false )
  2269. ///////////////////////////////////////////////////////////////////////////////
  2270. #define INTERNAL_CATCH_THROWS_AS( macroName, exceptionType, resultDisposition, expr ) \
  2271. do { \
  2272. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType), resultDisposition ); \
  2273. if( catchAssertionHandler.allowThrows() ) \
  2274. try { \
  2275. static_cast<void>(expr); \
  2276. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  2277. } \
  2278. catch( exceptionType const& ) { \
  2279. catchAssertionHandler.handleExceptionThrownAsExpected(); \
  2280. } \
  2281. catch( ... ) { \
  2282. catchAssertionHandler.handleUnexpectedInflightException(); \
  2283. } \
  2284. else \
  2285. catchAssertionHandler.handleThrowingCallSkipped(); \
  2286. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2287. } while( false )
  2288. ///////////////////////////////////////////////////////////////////////////////
  2289. #define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, ... ) \
  2290. do { \
  2291. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::StringRef(), resultDisposition ); \
  2292. catchAssertionHandler.handleMessage( messageType, ( Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop() ).m_stream.str() ); \
  2293. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2294. } while( false )
  2295. ///////////////////////////////////////////////////////////////////////////////
  2296. #define INTERNAL_CATCH_CAPTURE( varName, macroName, ... ) \
  2297. auto varName = Catch::Capturer( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info, #__VA_ARGS__ ); \
  2298. varName.captureValues( 0, __VA_ARGS__ )
  2299. ///////////////////////////////////////////////////////////////////////////////
  2300. #define INTERNAL_CATCH_INFO( macroName, log ) \
  2301. Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage )( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log );
  2302. ///////////////////////////////////////////////////////////////////////////////
  2303. #define INTERNAL_CATCH_UNSCOPED_INFO( macroName, log ) \
  2304. Catch::getResultCapture().emplaceUnscopedMessage( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log )
  2305. ///////////////////////////////////////////////////////////////////////////////
  2306. // Although this is matcher-based, it can be used with just a string
  2307. #define INTERNAL_CATCH_THROWS_STR_MATCHES( macroName, resultDisposition, matcher, ... ) \
  2308. do { \
  2309. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  2310. if( catchAssertionHandler.allowThrows() ) \
  2311. try { \
  2312. static_cast<void>(__VA_ARGS__); \
  2313. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  2314. } \
  2315. catch( ... ) { \
  2316. Catch::handleExceptionMatchExpr( catchAssertionHandler, matcher, #matcher##_catch_sr ); \
  2317. } \
  2318. else \
  2319. catchAssertionHandler.handleThrowingCallSkipped(); \
  2320. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2321. } while( false )
  2322. #endif // CATCH_CONFIG_DISABLE
  2323. // end catch_capture.hpp
  2324. // start catch_section.h
  2325. // start catch_section_info.h
  2326. // start catch_totals.h
  2327. #include <cstddef>
  2328. namespace Catch {
  2329. struct Counts {
  2330. Counts operator - ( Counts const& other ) const;
  2331. Counts& operator += ( Counts const& other );
  2332. std::size_t total() const;
  2333. bool allPassed() const;
  2334. bool allOk() const;
  2335. std::size_t passed = 0;
  2336. std::size_t failed = 0;
  2337. std::size_t failedButOk = 0;
  2338. };
  2339. struct Totals {
  2340. Totals operator - ( Totals const& other ) const;
  2341. Totals& operator += ( Totals const& other );
  2342. Totals delta( Totals const& prevTotals ) const;
  2343. int error = 0;
  2344. Counts assertions;
  2345. Counts testCases;
  2346. };
  2347. }
  2348. // end catch_totals.h
  2349. #include <string>
  2350. namespace Catch {
  2351. struct SectionInfo {
  2352. SectionInfo
  2353. ( SourceLineInfo const& _lineInfo,
  2354. std::string const& _name );
  2355. // Deprecated
  2356. SectionInfo
  2357. ( SourceLineInfo const& _lineInfo,
  2358. std::string const& _name,
  2359. std::string const& ) : SectionInfo( _lineInfo, _name ) {}
  2360. std::string name;
  2361. std::string description; // !Deprecated: this will always be empty
  2362. SourceLineInfo lineInfo;
  2363. };
  2364. struct SectionEndInfo {
  2365. SectionInfo sectionInfo;
  2366. Counts prevAssertions;
  2367. double durationInSeconds;
  2368. };
  2369. } // end namespace Catch
  2370. // end catch_section_info.h
  2371. // start catch_timer.h
  2372. #include <cstdint>
  2373. namespace Catch {
  2374. auto getCurrentNanosecondsSinceEpoch() -> uint64_t;
  2375. auto getEstimatedClockResolution() -> uint64_t;
  2376. class Timer {
  2377. uint64_t m_nanoseconds = 0;
  2378. public:
  2379. void start();
  2380. auto getElapsedNanoseconds() const -> uint64_t;
  2381. auto getElapsedMicroseconds() const -> uint64_t;
  2382. auto getElapsedMilliseconds() const -> unsigned int;
  2383. auto getElapsedSeconds() const -> double;
  2384. };
  2385. } // namespace Catch
  2386. // end catch_timer.h
  2387. #include <string>
  2388. namespace Catch {
  2389. class Section : NonCopyable {
  2390. public:
  2391. Section( SectionInfo const& info );
  2392. ~Section();
  2393. // This indicates whether the section should be executed or not
  2394. explicit operator bool() const;
  2395. private:
  2396. SectionInfo m_info;
  2397. std::string m_name;
  2398. Counts m_assertions;
  2399. bool m_sectionIncluded;
  2400. Timer m_timer;
  2401. };
  2402. } // end namespace Catch
  2403. #define INTERNAL_CATCH_SECTION( ... ) \
  2404. CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
  2405. if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) ) \
  2406. CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS
  2407. #define INTERNAL_CATCH_DYNAMIC_SECTION( ... ) \
  2408. CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
  2409. if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, (Catch::ReusableStringStream() << __VA_ARGS__).str() ) ) \
  2410. CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS
  2411. // end catch_section.h
  2412. // start catch_interfaces_exception.h
  2413. // start catch_interfaces_registry_hub.h
  2414. #include <string>
  2415. #include <memory>
  2416. namespace Catch {
  2417. class TestCase;
  2418. struct ITestCaseRegistry;
  2419. struct IExceptionTranslatorRegistry;
  2420. struct IExceptionTranslator;
  2421. struct IReporterRegistry;
  2422. struct IReporterFactory;
  2423. struct ITagAliasRegistry;
  2424. struct IMutableEnumValuesRegistry;
  2425. class StartupExceptionRegistry;
  2426. using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
  2427. struct IRegistryHub {
  2428. virtual ~IRegistryHub();
  2429. virtual IReporterRegistry const& getReporterRegistry() const = 0;
  2430. virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0;
  2431. virtual ITagAliasRegistry const& getTagAliasRegistry() const = 0;
  2432. virtual IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const = 0;
  2433. virtual StartupExceptionRegistry const& getStartupExceptionRegistry() const = 0;
  2434. };
  2435. struct IMutableRegistryHub {
  2436. virtual ~IMutableRegistryHub();
  2437. virtual void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) = 0;
  2438. virtual void registerListener( IReporterFactoryPtr const& factory ) = 0;
  2439. virtual void registerTest( TestCase const& testInfo ) = 0;
  2440. virtual void registerTranslator( const IExceptionTranslator* translator ) = 0;
  2441. virtual void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) = 0;
  2442. virtual void registerStartupException() noexcept = 0;
  2443. virtual IMutableEnumValuesRegistry& getMutableEnumValuesRegistry() = 0;
  2444. };
  2445. IRegistryHub const& getRegistryHub();
  2446. IMutableRegistryHub& getMutableRegistryHub();
  2447. void cleanUp();
  2448. std::string translateActiveException();
  2449. }
  2450. // end catch_interfaces_registry_hub.h
  2451. #if defined(CATCH_CONFIG_DISABLE)
  2452. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( translatorName, signature) \
  2453. static std::string translatorName( signature )
  2454. #endif
  2455. #include <exception>
  2456. #include <string>
  2457. #include <vector>
  2458. namespace Catch {
  2459. using exceptionTranslateFunction = std::string(*)();
  2460. struct IExceptionTranslator;
  2461. using ExceptionTranslators = std::vector<std::unique_ptr<IExceptionTranslator const>>;
  2462. struct IExceptionTranslator {
  2463. virtual ~IExceptionTranslator();
  2464. virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const = 0;
  2465. };
  2466. struct IExceptionTranslatorRegistry {
  2467. virtual ~IExceptionTranslatorRegistry();
  2468. virtual std::string translateActiveException() const = 0;
  2469. };
  2470. class ExceptionTranslatorRegistrar {
  2471. template<typename T>
  2472. class ExceptionTranslator : public IExceptionTranslator {
  2473. public:
  2474. ExceptionTranslator( std::string(*translateFunction)( T& ) )
  2475. : m_translateFunction( translateFunction )
  2476. {}
  2477. std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const override {
  2478. try {
  2479. if( it == itEnd )
  2480. std::rethrow_exception(std::current_exception());
  2481. else
  2482. return (*it)->translate( it+1, itEnd );
  2483. }
  2484. catch( T& ex ) {
  2485. return m_translateFunction( ex );
  2486. }
  2487. }
  2488. protected:
  2489. std::string(*m_translateFunction)( T& );
  2490. };
  2491. public:
  2492. template<typename T>
  2493. ExceptionTranslatorRegistrar( std::string(*translateFunction)( T& ) ) {
  2494. getMutableRegistryHub().registerTranslator
  2495. ( new ExceptionTranslator<T>( translateFunction ) );
  2496. }
  2497. };
  2498. }
  2499. ///////////////////////////////////////////////////////////////////////////////
  2500. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION2( translatorName, signature ) \
  2501. static std::string translatorName( signature ); \
  2502. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  2503. namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &translatorName ); } \
  2504. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  2505. static std::string translatorName( signature )
  2506. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
  2507. // end catch_interfaces_exception.h
  2508. // start catch_approx.h
  2509. #include <type_traits>
  2510. namespace Catch {
  2511. namespace Detail {
  2512. class Approx {
  2513. private:
  2514. bool equalityComparisonImpl(double other) const;
  2515. // Validates the new margin (margin >= 0)
  2516. // out-of-line to avoid including stdexcept in the header
  2517. void setMargin(double margin);
  2518. // Validates the new epsilon (0 < epsilon < 1)
  2519. // out-of-line to avoid including stdexcept in the header
  2520. void setEpsilon(double epsilon);
  2521. public:
  2522. explicit Approx ( double value );
  2523. static Approx custom();
  2524. Approx operator-() const;
  2525. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2526. Approx operator()( T const& value ) {
  2527. Approx approx( static_cast<double>(value) );
  2528. approx.m_epsilon = m_epsilon;
  2529. approx.m_margin = m_margin;
  2530. approx.m_scale = m_scale;
  2531. return approx;
  2532. }
  2533. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2534. explicit Approx( T const& value ): Approx(static_cast<double>(value))
  2535. {}
  2536. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2537. friend bool operator == ( const T& lhs, Approx const& rhs ) {
  2538. auto lhs_v = static_cast<double>(lhs);
  2539. return rhs.equalityComparisonImpl(lhs_v);
  2540. }
  2541. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2542. friend bool operator == ( Approx const& lhs, const T& rhs ) {
  2543. return operator==( rhs, lhs );
  2544. }
  2545. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2546. friend bool operator != ( T const& lhs, Approx const& rhs ) {
  2547. return !operator==( lhs, rhs );
  2548. }
  2549. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2550. friend bool operator != ( Approx const& lhs, T const& rhs ) {
  2551. return !operator==( rhs, lhs );
  2552. }
  2553. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2554. friend bool operator <= ( T const& lhs, Approx const& rhs ) {
  2555. return static_cast<double>(lhs) < rhs.m_value || lhs == rhs;
  2556. }
  2557. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2558. friend bool operator <= ( Approx const& lhs, T const& rhs ) {
  2559. return lhs.m_value < static_cast<double>(rhs) || lhs == rhs;
  2560. }
  2561. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2562. friend bool operator >= ( T const& lhs, Approx const& rhs ) {
  2563. return static_cast<double>(lhs) > rhs.m_value || lhs == rhs;
  2564. }
  2565. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2566. friend bool operator >= ( Approx const& lhs, T const& rhs ) {
  2567. return lhs.m_value > static_cast<double>(rhs) || lhs == rhs;
  2568. }
  2569. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2570. Approx& epsilon( T const& newEpsilon ) {
  2571. double epsilonAsDouble = static_cast<double>(newEpsilon);
  2572. setEpsilon(epsilonAsDouble);
  2573. return *this;
  2574. }
  2575. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2576. Approx& margin( T const& newMargin ) {
  2577. double marginAsDouble = static_cast<double>(newMargin);
  2578. setMargin(marginAsDouble);
  2579. return *this;
  2580. }
  2581. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2582. Approx& scale( T const& newScale ) {
  2583. m_scale = static_cast<double>(newScale);
  2584. return *this;
  2585. }
  2586. std::string toString() const;
  2587. private:
  2588. double m_epsilon;
  2589. double m_margin;
  2590. double m_scale;
  2591. double m_value;
  2592. };
  2593. } // end namespace Detail
  2594. namespace literals {
  2595. Detail::Approx operator "" _a(long double val);
  2596. Detail::Approx operator "" _a(unsigned long long val);
  2597. } // end namespace literals
  2598. template<>
  2599. struct StringMaker<Catch::Detail::Approx> {
  2600. static std::string convert(Catch::Detail::Approx const& value);
  2601. };
  2602. } // end namespace Catch
  2603. // end catch_approx.h
  2604. // start catch_string_manip.h
  2605. #include <string>
  2606. #include <iosfwd>
  2607. #include <vector>
  2608. namespace Catch {
  2609. bool startsWith( std::string const& s, std::string const& prefix );
  2610. bool startsWith( std::string const& s, char prefix );
  2611. bool endsWith( std::string const& s, std::string const& suffix );
  2612. bool endsWith( std::string const& s, char suffix );
  2613. bool contains( std::string const& s, std::string const& infix );
  2614. void toLowerInPlace( std::string& s );
  2615. std::string toLower( std::string const& s );
  2616. std::string trim( std::string const& str );
  2617. // !!! Be aware, returns refs into original string - make sure original string outlives them
  2618. std::vector<StringRef> splitStringRef( StringRef str, char delimiter );
  2619. bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis );
  2620. struct pluralise {
  2621. pluralise( std::size_t count, std::string const& label );
  2622. friend std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser );
  2623. std::size_t m_count;
  2624. std::string m_label;
  2625. };
  2626. }
  2627. // end catch_string_manip.h
  2628. #ifndef CATCH_CONFIG_DISABLE_MATCHERS
  2629. // start catch_capture_matchers.h
  2630. // start catch_matchers.h
  2631. #include <string>
  2632. #include <vector>
  2633. namespace Catch {
  2634. namespace Matchers {
  2635. namespace Impl {
  2636. template<typename ArgT> struct MatchAllOf;
  2637. template<typename ArgT> struct MatchAnyOf;
  2638. template<typename ArgT> struct MatchNotOf;
  2639. class MatcherUntypedBase {
  2640. public:
  2641. MatcherUntypedBase() = default;
  2642. MatcherUntypedBase ( MatcherUntypedBase const& ) = default;
  2643. MatcherUntypedBase& operator = ( MatcherUntypedBase const& ) = delete;
  2644. std::string toString() const;
  2645. protected:
  2646. virtual ~MatcherUntypedBase();
  2647. virtual std::string describe() const = 0;
  2648. mutable std::string m_cachedToString;
  2649. };
  2650. #ifdef __clang__
  2651. # pragma clang diagnostic push
  2652. # pragma clang diagnostic ignored "-Wnon-virtual-dtor"
  2653. #endif
  2654. template<typename ObjectT>
  2655. struct MatcherMethod {
  2656. virtual bool match( ObjectT const& arg ) const = 0;
  2657. };
  2658. #if defined(__OBJC__)
  2659. // Hack to fix Catch GH issue #1661. Could use id for generic Object support.
  2660. // use of const for Object pointers is very uncommon and under ARC it causes some kind of signature mismatch that breaks compilation
  2661. template<>
  2662. struct MatcherMethod<NSString*> {
  2663. virtual bool match( NSString* arg ) const = 0;
  2664. };
  2665. #endif
  2666. #ifdef __clang__
  2667. # pragma clang diagnostic pop
  2668. #endif
  2669. template<typename T>
  2670. struct MatcherBase : MatcherUntypedBase, MatcherMethod<T> {
  2671. MatchAllOf<T> operator && ( MatcherBase const& other ) const;
  2672. MatchAnyOf<T> operator || ( MatcherBase const& other ) const;
  2673. MatchNotOf<T> operator ! () const;
  2674. };
  2675. template<typename ArgT>
  2676. struct MatchAllOf : MatcherBase<ArgT> {
  2677. bool match( ArgT const& arg ) const override {
  2678. for( auto matcher : m_matchers ) {
  2679. if (!matcher->match(arg))
  2680. return false;
  2681. }
  2682. return true;
  2683. }
  2684. std::string describe() const override {
  2685. std::string description;
  2686. description.reserve( 4 + m_matchers.size()*32 );
  2687. description += "( ";
  2688. bool first = true;
  2689. for( auto matcher : m_matchers ) {
  2690. if( first )
  2691. first = false;
  2692. else
  2693. description += " and ";
  2694. description += matcher->toString();
  2695. }
  2696. description += " )";
  2697. return description;
  2698. }
  2699. MatchAllOf<ArgT>& operator && ( MatcherBase<ArgT> const& other ) {
  2700. m_matchers.push_back( &other );
  2701. return *this;
  2702. }
  2703. std::vector<MatcherBase<ArgT> const*> m_matchers;
  2704. };
  2705. template<typename ArgT>
  2706. struct MatchAnyOf : MatcherBase<ArgT> {
  2707. bool match( ArgT const& arg ) const override {
  2708. for( auto matcher : m_matchers ) {
  2709. if (matcher->match(arg))
  2710. return true;
  2711. }
  2712. return false;
  2713. }
  2714. std::string describe() const override {
  2715. std::string description;
  2716. description.reserve( 4 + m_matchers.size()*32 );
  2717. description += "( ";
  2718. bool first = true;
  2719. for( auto matcher : m_matchers ) {
  2720. if( first )
  2721. first = false;
  2722. else
  2723. description += " or ";
  2724. description += matcher->toString();
  2725. }
  2726. description += " )";
  2727. return description;
  2728. }
  2729. MatchAnyOf<ArgT>& operator || ( MatcherBase<ArgT> const& other ) {
  2730. m_matchers.push_back( &other );
  2731. return *this;
  2732. }
  2733. std::vector<MatcherBase<ArgT> const*> m_matchers;
  2734. };
  2735. template<typename ArgT>
  2736. struct MatchNotOf : MatcherBase<ArgT> {
  2737. MatchNotOf( MatcherBase<ArgT> const& underlyingMatcher ) : m_underlyingMatcher( underlyingMatcher ) {}
  2738. bool match( ArgT const& arg ) const override {
  2739. return !m_underlyingMatcher.match( arg );
  2740. }
  2741. std::string describe() const override {
  2742. return "not " + m_underlyingMatcher.toString();
  2743. }
  2744. MatcherBase<ArgT> const& m_underlyingMatcher;
  2745. };
  2746. template<typename T>
  2747. MatchAllOf<T> MatcherBase<T>::operator && ( MatcherBase const& other ) const {
  2748. return MatchAllOf<T>() && *this && other;
  2749. }
  2750. template<typename T>
  2751. MatchAnyOf<T> MatcherBase<T>::operator || ( MatcherBase const& other ) const {
  2752. return MatchAnyOf<T>() || *this || other;
  2753. }
  2754. template<typename T>
  2755. MatchNotOf<T> MatcherBase<T>::operator ! () const {
  2756. return MatchNotOf<T>( *this );
  2757. }
  2758. } // namespace Impl
  2759. } // namespace Matchers
  2760. using namespace Matchers;
  2761. using Matchers::Impl::MatcherBase;
  2762. } // namespace Catch
  2763. // end catch_matchers.h
  2764. // start catch_matchers_floating.h
  2765. #include <type_traits>
  2766. #include <cmath>
  2767. namespace Catch {
  2768. namespace Matchers {
  2769. namespace Floating {
  2770. enum class FloatingPointKind : uint8_t;
  2771. struct WithinAbsMatcher : MatcherBase<double> {
  2772. WithinAbsMatcher(double target, double margin);
  2773. bool match(double const& matchee) const override;
  2774. std::string describe() const override;
  2775. private:
  2776. double m_target;
  2777. double m_margin;
  2778. };
  2779. struct WithinUlpsMatcher : MatcherBase<double> {
  2780. WithinUlpsMatcher(double target, int ulps, FloatingPointKind baseType);
  2781. bool match(double const& matchee) const override;
  2782. std::string describe() const override;
  2783. private:
  2784. double m_target;
  2785. int m_ulps;
  2786. FloatingPointKind m_type;
  2787. };
  2788. } // namespace Floating
  2789. // The following functions create the actual matcher objects.
  2790. // This allows the types to be inferred
  2791. Floating::WithinUlpsMatcher WithinULP(double target, int maxUlpDiff);
  2792. Floating::WithinUlpsMatcher WithinULP(float target, int maxUlpDiff);
  2793. Floating::WithinAbsMatcher WithinAbs(double target, double margin);
  2794. } // namespace Matchers
  2795. } // namespace Catch
  2796. // end catch_matchers_floating.h
  2797. // start catch_matchers_generic.hpp
  2798. #include <functional>
  2799. #include <string>
  2800. namespace Catch {
  2801. namespace Matchers {
  2802. namespace Generic {
  2803. namespace Detail {
  2804. std::string finalizeDescription(const std::string& desc);
  2805. }
  2806. template <typename T>
  2807. class PredicateMatcher : public MatcherBase<T> {
  2808. std::function<bool(T const&)> m_predicate;
  2809. std::string m_description;
  2810. public:
  2811. PredicateMatcher(std::function<bool(T const&)> const& elem, std::string const& descr)
  2812. :m_predicate(std::move(elem)),
  2813. m_description(Detail::finalizeDescription(descr))
  2814. {}
  2815. bool match( T const& item ) const override {
  2816. return m_predicate(item);
  2817. }
  2818. std::string describe() const override {
  2819. return m_description;
  2820. }
  2821. };
  2822. } // namespace Generic
  2823. // The following functions create the actual matcher objects.
  2824. // The user has to explicitly specify type to the function, because
  2825. // inferring std::function<bool(T const&)> is hard (but possible) and
  2826. // requires a lot of TMP.
  2827. template<typename T>
  2828. Generic::PredicateMatcher<T> Predicate(std::function<bool(T const&)> const& predicate, std::string const& description = "") {
  2829. return Generic::PredicateMatcher<T>(predicate, description);
  2830. }
  2831. } // namespace Matchers
  2832. } // namespace Catch
  2833. // end catch_matchers_generic.hpp
  2834. // start catch_matchers_string.h
  2835. #include <string>
  2836. namespace Catch {
  2837. namespace Matchers {
  2838. namespace StdString {
  2839. struct CasedString
  2840. {
  2841. CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity );
  2842. std::string adjustString( std::string const& str ) const;
  2843. std::string caseSensitivitySuffix() const;
  2844. CaseSensitive::Choice m_caseSensitivity;
  2845. std::string m_str;
  2846. };
  2847. struct StringMatcherBase : MatcherBase<std::string> {
  2848. StringMatcherBase( std::string const& operation, CasedString const& comparator );
  2849. std::string describe() const override;
  2850. CasedString m_comparator;
  2851. std::string m_operation;
  2852. };
  2853. struct EqualsMatcher : StringMatcherBase {
  2854. EqualsMatcher( CasedString const& comparator );
  2855. bool match( std::string const& source ) const override;
  2856. };
  2857. struct ContainsMatcher : StringMatcherBase {
  2858. ContainsMatcher( CasedString const& comparator );
  2859. bool match( std::string const& source ) const override;
  2860. };
  2861. struct StartsWithMatcher : StringMatcherBase {
  2862. StartsWithMatcher( CasedString const& comparator );
  2863. bool match( std::string const& source ) const override;
  2864. };
  2865. struct EndsWithMatcher : StringMatcherBase {
  2866. EndsWithMatcher( CasedString const& comparator );
  2867. bool match( std::string const& source ) const override;
  2868. };
  2869. struct RegexMatcher : MatcherBase<std::string> {
  2870. RegexMatcher( std::string regex, CaseSensitive::Choice caseSensitivity );
  2871. bool match( std::string const& matchee ) const override;
  2872. std::string describe() const override;
  2873. private:
  2874. std::string m_regex;
  2875. CaseSensitive::Choice m_caseSensitivity;
  2876. };
  2877. } // namespace StdString
  2878. // The following functions create the actual matcher objects.
  2879. // This allows the types to be inferred
  2880. StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2881. StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2882. StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2883. StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2884. StdString::RegexMatcher Matches( std::string const& regex, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2885. } // namespace Matchers
  2886. } // namespace Catch
  2887. // end catch_matchers_string.h
  2888. // start catch_matchers_vector.h
  2889. #include <algorithm>
  2890. namespace Catch {
  2891. namespace Matchers {
  2892. namespace Vector {
  2893. template<typename T>
  2894. struct ContainsElementMatcher : MatcherBase<std::vector<T>> {
  2895. ContainsElementMatcher(T const &comparator) : m_comparator( comparator) {}
  2896. bool match(std::vector<T> const &v) const override {
  2897. for (auto const& el : v) {
  2898. if (el == m_comparator) {
  2899. return true;
  2900. }
  2901. }
  2902. return false;
  2903. }
  2904. std::string describe() const override {
  2905. return "Contains: " + ::Catch::Detail::stringify( m_comparator );
  2906. }
  2907. T const& m_comparator;
  2908. };
  2909. template<typename T>
  2910. struct ContainsMatcher : MatcherBase<std::vector<T>> {
  2911. ContainsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}
  2912. bool match(std::vector<T> const &v) const override {
  2913. // !TBD: see note in EqualsMatcher
  2914. if (m_comparator.size() > v.size())
  2915. return false;
  2916. for (auto const& comparator : m_comparator) {
  2917. auto present = false;
  2918. for (const auto& el : v) {
  2919. if (el == comparator) {
  2920. present = true;
  2921. break;
  2922. }
  2923. }
  2924. if (!present) {
  2925. return false;
  2926. }
  2927. }
  2928. return true;
  2929. }
  2930. std::string describe() const override {
  2931. return "Contains: " + ::Catch::Detail::stringify( m_comparator );
  2932. }
  2933. std::vector<T> const& m_comparator;
  2934. };
  2935. template<typename T>
  2936. struct EqualsMatcher : MatcherBase<std::vector<T>> {
  2937. EqualsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}
  2938. bool match(std::vector<T> const &v) const override {
  2939. // !TBD: This currently works if all elements can be compared using !=
  2940. // - a more general approach would be via a compare template that defaults
  2941. // to using !=. but could be specialised for, e.g. std::vector<T> etc
  2942. // - then just call that directly
  2943. if (m_comparator.size() != v.size())
  2944. return false;
  2945. for (std::size_t i = 0; i < v.size(); ++i)
  2946. if (m_comparator[i] != v[i])
  2947. return false;
  2948. return true;
  2949. }
  2950. std::string describe() const override {
  2951. return "Equals: " + ::Catch::Detail::stringify( m_comparator );
  2952. }
  2953. std::vector<T> const& m_comparator;
  2954. };
  2955. template<typename T>
  2956. struct ApproxMatcher : MatcherBase<std::vector<T>> {
  2957. ApproxMatcher(std::vector<T> const& comparator) : m_comparator( comparator ) {}
  2958. bool match(std::vector<T> const &v) const override {
  2959. if (m_comparator.size() != v.size())
  2960. return false;
  2961. for (std::size_t i = 0; i < v.size(); ++i)
  2962. if (m_comparator[i] != approx(v[i]))
  2963. return false;
  2964. return true;
  2965. }
  2966. std::string describe() const override {
  2967. return "is approx: " + ::Catch::Detail::stringify( m_comparator );
  2968. }
  2969. template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2970. ApproxMatcher& epsilon( T const& newEpsilon ) {
  2971. approx.epsilon(newEpsilon);
  2972. return *this;
  2973. }
  2974. template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2975. ApproxMatcher& margin( T const& newMargin ) {
  2976. approx.margin(newMargin);
  2977. return *this;
  2978. }
  2979. template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2980. ApproxMatcher& scale( T const& newScale ) {
  2981. approx.scale(newScale);
  2982. return *this;
  2983. }
  2984. std::vector<T> const& m_comparator;
  2985. mutable Catch::Detail::Approx approx = Catch::Detail::Approx::custom();
  2986. };
  2987. template<typename T>
  2988. struct UnorderedEqualsMatcher : MatcherBase<std::vector<T>> {
  2989. UnorderedEqualsMatcher(std::vector<T> const& target) : m_target(target) {}
  2990. bool match(std::vector<T> const& vec) const override {
  2991. // Note: This is a reimplementation of std::is_permutation,
  2992. // because I don't want to include <algorithm> inside the common path
  2993. if (m_target.size() != vec.size()) {
  2994. return false;
  2995. }
  2996. return std::is_permutation(m_target.begin(), m_target.end(), vec.begin());
  2997. }
  2998. std::string describe() const override {
  2999. return "UnorderedEquals: " + ::Catch::Detail::stringify(m_target);
  3000. }
  3001. private:
  3002. std::vector<T> const& m_target;
  3003. };
  3004. } // namespace Vector
  3005. // The following functions create the actual matcher objects.
  3006. // This allows the types to be inferred
  3007. template<typename T>
  3008. Vector::ContainsMatcher<T> Contains( std::vector<T> const& comparator ) {
  3009. return Vector::ContainsMatcher<T>( comparator );
  3010. }
  3011. template<typename T>
  3012. Vector::ContainsElementMatcher<T> VectorContains( T const& comparator ) {
  3013. return Vector::ContainsElementMatcher<T>( comparator );
  3014. }
  3015. template<typename T>
  3016. Vector::EqualsMatcher<T> Equals( std::vector<T> const& comparator ) {
  3017. return Vector::EqualsMatcher<T>( comparator );
  3018. }
  3019. template<typename T>
  3020. Vector::ApproxMatcher<T> Approx( std::vector<T> const& comparator ) {
  3021. return Vector::ApproxMatcher<T>( comparator );
  3022. }
  3023. template<typename T>
  3024. Vector::UnorderedEqualsMatcher<T> UnorderedEquals(std::vector<T> const& target) {
  3025. return Vector::UnorderedEqualsMatcher<T>(target);
  3026. }
  3027. } // namespace Matchers
  3028. } // namespace Catch
  3029. // end catch_matchers_vector.h
  3030. namespace Catch {
  3031. template<typename ArgT, typename MatcherT>
  3032. class MatchExpr : public ITransientExpression {
  3033. ArgT const& m_arg;
  3034. MatcherT m_matcher;
  3035. StringRef m_matcherString;
  3036. public:
  3037. MatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString )
  3038. : ITransientExpression{ true, matcher.match( arg ) },
  3039. m_arg( arg ),
  3040. m_matcher( matcher ),
  3041. m_matcherString( matcherString )
  3042. {}
  3043. void streamReconstructedExpression( std::ostream &os ) const override {
  3044. auto matcherAsString = m_matcher.toString();
  3045. os << Catch::Detail::stringify( m_arg ) << ' ';
  3046. if( matcherAsString == Detail::unprintableString )
  3047. os << m_matcherString;
  3048. else
  3049. os << matcherAsString;
  3050. }
  3051. };
  3052. using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
  3053. void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString );
  3054. template<typename ArgT, typename MatcherT>
  3055. auto makeMatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString ) -> MatchExpr<ArgT, MatcherT> {
  3056. return MatchExpr<ArgT, MatcherT>( arg, matcher, matcherString );
  3057. }
  3058. } // namespace Catch
  3059. ///////////////////////////////////////////////////////////////////////////////
  3060. #define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \
  3061. do { \
  3062. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  3063. INTERNAL_CATCH_TRY { \
  3064. catchAssertionHandler.handleExpr( Catch::makeMatchExpr( arg, matcher, #matcher##_catch_sr ) ); \
  3065. } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
  3066. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  3067. } while( false )
  3068. ///////////////////////////////////////////////////////////////////////////////
  3069. #define INTERNAL_CATCH_THROWS_MATCHES( macroName, exceptionType, resultDisposition, matcher, ... ) \
  3070. do { \
  3071. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(exceptionType) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  3072. if( catchAssertionHandler.allowThrows() ) \
  3073. try { \
  3074. static_cast<void>(__VA_ARGS__ ); \
  3075. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  3076. } \
  3077. catch( exceptionType const& ex ) { \
  3078. catchAssertionHandler.handleExpr( Catch::makeMatchExpr( ex, matcher, #matcher##_catch_sr ) ); \
  3079. } \
  3080. catch( ... ) { \
  3081. catchAssertionHandler.handleUnexpectedInflightException(); \
  3082. } \
  3083. else \
  3084. catchAssertionHandler.handleThrowingCallSkipped(); \
  3085. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  3086. } while( false )
  3087. // end catch_capture_matchers.h
  3088. #endif
  3089. // start catch_generators.hpp
  3090. // start catch_interfaces_generatortracker.h
  3091. #include <memory>
  3092. namespace Catch {
  3093. namespace Generators {
  3094. class GeneratorUntypedBase {
  3095. public:
  3096. GeneratorUntypedBase() = default;
  3097. virtual ~GeneratorUntypedBase();
  3098. // Attempts to move the generator to the next element
  3099. //
  3100. // Returns true iff the move succeeded (and a valid element
  3101. // can be retrieved).
  3102. virtual bool next() = 0;
  3103. };
  3104. using GeneratorBasePtr = std::unique_ptr<GeneratorUntypedBase>;
  3105. } // namespace Generators
  3106. struct IGeneratorTracker {
  3107. virtual ~IGeneratorTracker();
  3108. virtual auto hasGenerator() const -> bool = 0;
  3109. virtual auto getGenerator() const -> Generators::GeneratorBasePtr const& = 0;
  3110. virtual void setGenerator( Generators::GeneratorBasePtr&& generator ) = 0;
  3111. };
  3112. } // namespace Catch
  3113. // end catch_interfaces_generatortracker.h
  3114. // start catch_enforce.h
  3115. #include <exception>
  3116. namespace Catch {
  3117. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  3118. template <typename Ex>
  3119. [[noreturn]]
  3120. void throw_exception(Ex const& e) {
  3121. throw e;
  3122. }
  3123. #else // ^^ Exceptions are enabled // Exceptions are disabled vv
  3124. [[noreturn]]
  3125. void throw_exception(std::exception const& e);
  3126. #endif
  3127. [[noreturn]]
  3128. void throw_logic_error(std::string const& msg);
  3129. [[noreturn]]
  3130. void throw_domain_error(std::string const& msg);
  3131. [[noreturn]]
  3132. void throw_runtime_error(std::string const& msg);
  3133. } // namespace Catch;
  3134. #define CATCH_MAKE_MSG(...) \
  3135. (Catch::ReusableStringStream() << __VA_ARGS__).str()
  3136. #define CATCH_INTERNAL_ERROR(...) \
  3137. Catch::throw_logic_error(CATCH_MAKE_MSG( CATCH_INTERNAL_LINEINFO << ": Internal Catch2 error: " << __VA_ARGS__));
  3138. #define CATCH_ERROR(...) \
  3139. Catch::throw_domain_error(CATCH_MAKE_MSG( __VA_ARGS__ ));
  3140. #define CATCH_RUNTIME_ERROR(...) \
  3141. Catch::throw_runtime_error(CATCH_MAKE_MSG( __VA_ARGS__ ));
  3142. #define CATCH_ENFORCE( condition, ... ) \
  3143. do{ if( !(condition) ) CATCH_ERROR( __VA_ARGS__ ); } while(false)
  3144. // end catch_enforce.h
  3145. #include <memory>
  3146. #include <vector>
  3147. #include <cassert>
  3148. #include <utility>
  3149. #include <exception>
  3150. namespace Catch {
  3151. class GeneratorException : public std::exception {
  3152. const char* const m_msg = "";
  3153. public:
  3154. GeneratorException(const char* msg):
  3155. m_msg(msg)
  3156. {}
  3157. const char* what() const noexcept override final;
  3158. };
  3159. namespace Generators {
  3160. // !TBD move this into its own location?
  3161. namespace pf{
  3162. template<typename T, typename... Args>
  3163. std::unique_ptr<T> make_unique( Args&&... args ) {
  3164. return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
  3165. }
  3166. }
  3167. template<typename T>
  3168. struct IGenerator : GeneratorUntypedBase {
  3169. virtual ~IGenerator() = default;
  3170. // Returns the current element of the generator
  3171. //
  3172. // \Precondition The generator is either freshly constructed,
  3173. // or the last call to `next()` returned true
  3174. virtual T const& get() const = 0;
  3175. using type = T;
  3176. };
  3177. template<typename T>
  3178. class SingleValueGenerator final : public IGenerator<T> {
  3179. T m_value;
  3180. public:
  3181. SingleValueGenerator(T const& value) : m_value( value ) {}
  3182. SingleValueGenerator(T&& value) : m_value(std::move(value)) {}
  3183. T const& get() const override {
  3184. return m_value;
  3185. }
  3186. bool next() override {
  3187. return false;
  3188. }
  3189. };
  3190. template<typename T>
  3191. class FixedValuesGenerator final : public IGenerator<T> {
  3192. static_assert(!std::is_same<T, bool>::value,
  3193. "ValuesGenerator does not support bools because of std::vector<bool>"
  3194. "specialization, use SingleValue Generator instead.");
  3195. std::vector<T> m_values;
  3196. size_t m_idx = 0;
  3197. public:
  3198. FixedValuesGenerator( std::initializer_list<T> values ) : m_values( values ) {}
  3199. T const& get() const override {
  3200. return m_values[m_idx];
  3201. }
  3202. bool next() override {
  3203. ++m_idx;
  3204. return m_idx < m_values.size();
  3205. }
  3206. };
  3207. template <typename T>
  3208. class GeneratorWrapper final {
  3209. std::unique_ptr<IGenerator<T>> m_generator;
  3210. public:
  3211. GeneratorWrapper(std::unique_ptr<IGenerator<T>> generator):
  3212. m_generator(std::move(generator))
  3213. {}
  3214. T const& get() const {
  3215. return m_generator->get();
  3216. }
  3217. bool next() {
  3218. return m_generator->next();
  3219. }
  3220. };
  3221. template <typename T>
  3222. GeneratorWrapper<T> value(T&& value) {
  3223. return GeneratorWrapper<T>(pf::make_unique<SingleValueGenerator<T>>(std::forward<T>(value)));
  3224. }
  3225. template <typename T>
  3226. GeneratorWrapper<T> values(std::initializer_list<T> values) {
  3227. return GeneratorWrapper<T>(pf::make_unique<FixedValuesGenerator<T>>(values));
  3228. }
  3229. template<typename T>
  3230. class Generators : public IGenerator<T> {
  3231. std::vector<GeneratorWrapper<T>> m_generators;
  3232. size_t m_current = 0;
  3233. void populate(GeneratorWrapper<T>&& generator) {
  3234. m_generators.emplace_back(std::move(generator));
  3235. }
  3236. void populate(T&& val) {
  3237. m_generators.emplace_back(value(std::move(val)));
  3238. }
  3239. template<typename U>
  3240. void populate(U&& val) {
  3241. populate(T(std::move(val)));
  3242. }
  3243. template<typename U, typename... Gs>
  3244. void populate(U&& valueOrGenerator, Gs... moreGenerators) {
  3245. populate(std::forward<U>(valueOrGenerator));
  3246. populate(std::forward<Gs>(moreGenerators)...);
  3247. }
  3248. public:
  3249. template <typename... Gs>
  3250. Generators(Gs... moreGenerators) {
  3251. m_generators.reserve(sizeof...(Gs));
  3252. populate(std::forward<Gs>(moreGenerators)...);
  3253. }
  3254. T const& get() const override {
  3255. return m_generators[m_current].get();
  3256. }
  3257. bool next() override {
  3258. if (m_current >= m_generators.size()) {
  3259. return false;
  3260. }
  3261. const bool current_status = m_generators[m_current].next();
  3262. if (!current_status) {
  3263. ++m_current;
  3264. }
  3265. return m_current < m_generators.size();
  3266. }
  3267. };
  3268. template<typename... Ts>
  3269. GeneratorWrapper<std::tuple<Ts...>> table( std::initializer_list<std::tuple<typename std::decay<Ts>::type...>> tuples ) {
  3270. return values<std::tuple<Ts...>>( tuples );
  3271. }
  3272. // Tag type to signal that a generator sequence should convert arguments to a specific type
  3273. template <typename T>
  3274. struct as {};
  3275. template<typename T, typename... Gs>
  3276. auto makeGenerators( GeneratorWrapper<T>&& generator, Gs... moreGenerators ) -> Generators<T> {
  3277. return Generators<T>(std::move(generator), std::forward<Gs>(moreGenerators)...);
  3278. }
  3279. template<typename T>
  3280. auto makeGenerators( GeneratorWrapper<T>&& generator ) -> Generators<T> {
  3281. return Generators<T>(std::move(generator));
  3282. }
  3283. template<typename T, typename... Gs>
  3284. auto makeGenerators( T&& val, Gs... moreGenerators ) -> Generators<T> {
  3285. return makeGenerators( value( std::forward<T>( val ) ), std::forward<Gs>( moreGenerators )... );
  3286. }
  3287. template<typename T, typename U, typename... Gs>
  3288. auto makeGenerators( as<T>, U&& val, Gs... moreGenerators ) -> Generators<T> {
  3289. return makeGenerators( value( T( std::forward<U>( val ) ) ), std::forward<Gs>( moreGenerators )... );
  3290. }
  3291. auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker&;
  3292. template<typename L>
  3293. // Note: The type after -> is weird, because VS2015 cannot parse
  3294. // the expression used in the typedef inside, when it is in
  3295. // return type. Yeah.
  3296. auto generate( SourceLineInfo const& lineInfo, L const& generatorExpression ) -> decltype(std::declval<decltype(generatorExpression())>().get()) {
  3297. using UnderlyingType = typename decltype(generatorExpression())::type;
  3298. IGeneratorTracker& tracker = acquireGeneratorTracker( lineInfo );
  3299. if (!tracker.hasGenerator()) {
  3300. tracker.setGenerator(pf::make_unique<Generators<UnderlyingType>>(generatorExpression()));
  3301. }
  3302. auto const& generator = static_cast<IGenerator<UnderlyingType> const&>( *tracker.getGenerator() );
  3303. return generator.get();
  3304. }
  3305. } // namespace Generators
  3306. } // namespace Catch
  3307. #define GENERATE( ... ) \
  3308. Catch::Generators::generate( CATCH_INTERNAL_LINEINFO, [ ]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } )
  3309. #define GENERATE_COPY( ... ) \
  3310. Catch::Generators::generate( CATCH_INTERNAL_LINEINFO, [=]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } )
  3311. #define GENERATE_REF( ... ) \
  3312. Catch::Generators::generate( CATCH_INTERNAL_LINEINFO, [&]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } )
  3313. // end catch_generators.hpp
  3314. // start catch_generators_generic.hpp
  3315. namespace Catch {
  3316. namespace Generators {
  3317. template <typename T>
  3318. class TakeGenerator : public IGenerator<T> {
  3319. GeneratorWrapper<T> m_generator;
  3320. size_t m_returned = 0;
  3321. size_t m_target;
  3322. public:
  3323. TakeGenerator(size_t target, GeneratorWrapper<T>&& generator):
  3324. m_generator(std::move(generator)),
  3325. m_target(target)
  3326. {
  3327. assert(target != 0 && "Empty generators are not allowed");
  3328. }
  3329. T const& get() const override {
  3330. return m_generator.get();
  3331. }
  3332. bool next() override {
  3333. ++m_returned;
  3334. if (m_returned >= m_target) {
  3335. return false;
  3336. }
  3337. const auto success = m_generator.next();
  3338. // If the underlying generator does not contain enough values
  3339. // then we cut short as well
  3340. if (!success) {
  3341. m_returned = m_target;
  3342. }
  3343. return success;
  3344. }
  3345. };
  3346. template <typename T>
  3347. GeneratorWrapper<T> take(size_t target, GeneratorWrapper<T>&& generator) {
  3348. return GeneratorWrapper<T>(pf::make_unique<TakeGenerator<T>>(target, std::move(generator)));
  3349. }
  3350. template <typename T, typename Predicate>
  3351. class FilterGenerator : public IGenerator<T> {
  3352. GeneratorWrapper<T> m_generator;
  3353. Predicate m_predicate;
  3354. public:
  3355. template <typename P = Predicate>
  3356. FilterGenerator(P&& pred, GeneratorWrapper<T>&& generator):
  3357. m_generator(std::move(generator)),
  3358. m_predicate(std::forward<P>(pred))
  3359. {
  3360. if (!m_predicate(m_generator.get())) {
  3361. // It might happen that there are no values that pass the
  3362. // filter. In that case we throw an exception.
  3363. auto has_initial_value = next();
  3364. if (!has_initial_value) {
  3365. Catch::throw_exception(GeneratorException("No valid value found in filtered generator"));
  3366. }
  3367. }
  3368. }
  3369. T const& get() const override {
  3370. return m_generator.get();
  3371. }
  3372. bool next() override {
  3373. bool success = m_generator.next();
  3374. if (!success) {
  3375. return false;
  3376. }
  3377. while (!m_predicate(m_generator.get()) && (success = m_generator.next()) == true);
  3378. return success;
  3379. }
  3380. };
  3381. template <typename T, typename Predicate>
  3382. GeneratorWrapper<T> filter(Predicate&& pred, GeneratorWrapper<T>&& generator) {
  3383. return GeneratorWrapper<T>(std::unique_ptr<IGenerator<T>>(pf::make_unique<FilterGenerator<T, Predicate>>(std::forward<Predicate>(pred), std::move(generator))));
  3384. }
  3385. template <typename T>
  3386. class RepeatGenerator : public IGenerator<T> {
  3387. static_assert(!std::is_same<T, bool>::value,
  3388. "RepeatGenerator currently does not support bools"
  3389. "because of std::vector<bool> specialization");
  3390. GeneratorWrapper<T> m_generator;
  3391. mutable std::vector<T> m_returned;
  3392. size_t m_target_repeats;
  3393. size_t m_current_repeat = 0;
  3394. size_t m_repeat_index = 0;
  3395. public:
  3396. RepeatGenerator(size_t repeats, GeneratorWrapper<T>&& generator):
  3397. m_generator(std::move(generator)),
  3398. m_target_repeats(repeats)
  3399. {
  3400. assert(m_target_repeats > 0 && "Repeat generator must repeat at least once");
  3401. }
  3402. T const& get() const override {
  3403. if (m_current_repeat == 0) {
  3404. m_returned.push_back(m_generator.get());
  3405. return m_returned.back();
  3406. }
  3407. return m_returned[m_repeat_index];
  3408. }
  3409. bool next() override {
  3410. // There are 2 basic cases:
  3411. // 1) We are still reading the generator
  3412. // 2) We are reading our own cache
  3413. // In the first case, we need to poke the underlying generator.
  3414. // If it happily moves, we are left in that state, otherwise it is time to start reading from our cache
  3415. if (m_current_repeat == 0) {
  3416. const auto success = m_generator.next();
  3417. if (!success) {
  3418. ++m_current_repeat;
  3419. }
  3420. return m_current_repeat < m_target_repeats;
  3421. }
  3422. // In the second case, we need to move indices forward and check that we haven't run up against the end
  3423. ++m_repeat_index;
  3424. if (m_repeat_index == m_returned.size()) {
  3425. m_repeat_index = 0;
  3426. ++m_current_repeat;
  3427. }
  3428. return m_current_repeat < m_target_repeats;
  3429. }
  3430. };
  3431. template <typename T>
  3432. GeneratorWrapper<T> repeat(size_t repeats, GeneratorWrapper<T>&& generator) {
  3433. return GeneratorWrapper<T>(pf::make_unique<RepeatGenerator<T>>(repeats, std::move(generator)));
  3434. }
  3435. template <typename T, typename U, typename Func>
  3436. class MapGenerator : public IGenerator<T> {
  3437. // TBD: provide static assert for mapping function, for friendly error message
  3438. GeneratorWrapper<U> m_generator;
  3439. Func m_function;
  3440. // To avoid returning dangling reference, we have to save the values
  3441. T m_cache;
  3442. public:
  3443. template <typename F2 = Func>
  3444. MapGenerator(F2&& function, GeneratorWrapper<U>&& generator) :
  3445. m_generator(std::move(generator)),
  3446. m_function(std::forward<F2>(function)),
  3447. m_cache(m_function(m_generator.get()))
  3448. {}
  3449. T const& get() const override {
  3450. return m_cache;
  3451. }
  3452. bool next() override {
  3453. const auto success = m_generator.next();
  3454. if (success) {
  3455. m_cache = m_function(m_generator.get());
  3456. }
  3457. return success;
  3458. }
  3459. };
  3460. #if defined(__cpp_lib_is_invocable) && __cpp_lib_is_invocable >= 201703
  3461. // std::result_of is deprecated in C++17 and removed in C++20. Hence, it is
  3462. // replaced with std::invoke_result here. Also *_t format is preferred over
  3463. // typename *::type format.
  3464. template <typename Func, typename U>
  3465. using MapFunctionReturnType = std::remove_reference_t<std::remove_cv_t<std::invoke_result_t<Func, U>>>;
  3466. #else
  3467. template <typename Func, typename U>
  3468. using MapFunctionReturnType = typename std::remove_reference<typename std::remove_cv<typename std::result_of<Func(U)>::type>::type>::type;
  3469. #endif
  3470. template <typename Func, typename U, typename T = MapFunctionReturnType<Func, U>>
  3471. GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) {
  3472. return GeneratorWrapper<T>(
  3473. pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(function), std::move(generator))
  3474. );
  3475. }
  3476. template <typename T, typename U, typename Func>
  3477. GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) {
  3478. return GeneratorWrapper<T>(
  3479. pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(function), std::move(generator))
  3480. );
  3481. }
  3482. template <typename T>
  3483. class ChunkGenerator final : public IGenerator<std::vector<T>> {
  3484. std::vector<T> m_chunk;
  3485. size_t m_chunk_size;
  3486. GeneratorWrapper<T> m_generator;
  3487. bool m_used_up = false;
  3488. public:
  3489. ChunkGenerator(size_t size, GeneratorWrapper<T> generator) :
  3490. m_chunk_size(size), m_generator(std::move(generator))
  3491. {
  3492. m_chunk.reserve(m_chunk_size);
  3493. if (m_chunk_size != 0) {
  3494. m_chunk.push_back(m_generator.get());
  3495. for (size_t i = 1; i < m_chunk_size; ++i) {
  3496. if (!m_generator.next()) {
  3497. Catch::throw_exception(GeneratorException("Not enough values to initialize the first chunk"));
  3498. }
  3499. m_chunk.push_back(m_generator.get());
  3500. }
  3501. }
  3502. }
  3503. std::vector<T> const& get() const override {
  3504. return m_chunk;
  3505. }
  3506. bool next() override {
  3507. m_chunk.clear();
  3508. for (size_t idx = 0; idx < m_chunk_size; ++idx) {
  3509. if (!m_generator.next()) {
  3510. return false;
  3511. }
  3512. m_chunk.push_back(m_generator.get());
  3513. }
  3514. return true;
  3515. }
  3516. };
  3517. template <typename T>
  3518. GeneratorWrapper<std::vector<T>> chunk(size_t size, GeneratorWrapper<T>&& generator) {
  3519. return GeneratorWrapper<std::vector<T>>(
  3520. pf::make_unique<ChunkGenerator<T>>(size, std::move(generator))
  3521. );
  3522. }
  3523. } // namespace Generators
  3524. } // namespace Catch
  3525. // end catch_generators_generic.hpp
  3526. // start catch_generators_specific.hpp
  3527. // start catch_context.h
  3528. #include <memory>
  3529. namespace Catch {
  3530. struct IResultCapture;
  3531. struct IRunner;
  3532. struct IConfig;
  3533. struct IMutableContext;
  3534. using IConfigPtr = std::shared_ptr<IConfig const>;
  3535. struct IContext
  3536. {
  3537. virtual ~IContext();
  3538. virtual IResultCapture* getResultCapture() = 0;
  3539. virtual IRunner* getRunner() = 0;
  3540. virtual IConfigPtr const& getConfig() const = 0;
  3541. };
  3542. struct IMutableContext : IContext
  3543. {
  3544. virtual ~IMutableContext();
  3545. virtual void setResultCapture( IResultCapture* resultCapture ) = 0;
  3546. virtual void setRunner( IRunner* runner ) = 0;
  3547. virtual void setConfig( IConfigPtr const& config ) = 0;
  3548. private:
  3549. static IMutableContext *currentContext;
  3550. friend IMutableContext& getCurrentMutableContext();
  3551. friend void cleanUpContext();
  3552. static void createContext();
  3553. };
  3554. inline IMutableContext& getCurrentMutableContext()
  3555. {
  3556. if( !IMutableContext::currentContext )
  3557. IMutableContext::createContext();
  3558. return *IMutableContext::currentContext;
  3559. }
  3560. inline IContext& getCurrentContext()
  3561. {
  3562. return getCurrentMutableContext();
  3563. }
  3564. void cleanUpContext();
  3565. }
  3566. // end catch_context.h
  3567. // start catch_interfaces_config.h
  3568. // start catch_option.hpp
  3569. namespace Catch {
  3570. // An optional type
  3571. template<typename T>
  3572. class Option {
  3573. public:
  3574. Option() : nullableValue( nullptr ) {}
  3575. Option( T const& _value )
  3576. : nullableValue( new( storage ) T( _value ) )
  3577. {}
  3578. Option( Option const& _other )
  3579. : nullableValue( _other ? new( storage ) T( *_other ) : nullptr )
  3580. {}
  3581. ~Option() {
  3582. reset();
  3583. }
  3584. Option& operator= ( Option const& _other ) {
  3585. if( &_other != this ) {
  3586. reset();
  3587. if( _other )
  3588. nullableValue = new( storage ) T( *_other );
  3589. }
  3590. return *this;
  3591. }
  3592. Option& operator = ( T const& _value ) {
  3593. reset();
  3594. nullableValue = new( storage ) T( _value );
  3595. return *this;
  3596. }
  3597. void reset() {
  3598. if( nullableValue )
  3599. nullableValue->~T();
  3600. nullableValue = nullptr;
  3601. }
  3602. T& operator*() { return *nullableValue; }
  3603. T const& operator*() const { return *nullableValue; }
  3604. T* operator->() { return nullableValue; }
  3605. const T* operator->() const { return nullableValue; }
  3606. T valueOr( T const& defaultValue ) const {
  3607. return nullableValue ? *nullableValue : defaultValue;
  3608. }
  3609. bool some() const { return nullableValue != nullptr; }
  3610. bool none() const { return nullableValue == nullptr; }
  3611. bool operator !() const { return nullableValue == nullptr; }
  3612. explicit operator bool() const {
  3613. return some();
  3614. }
  3615. private:
  3616. T *nullableValue;
  3617. alignas(alignof(T)) char storage[sizeof(T)];
  3618. };
  3619. } // end namespace Catch
  3620. // end catch_option.hpp
  3621. #include <iosfwd>
  3622. #include <string>
  3623. #include <vector>
  3624. #include <memory>
  3625. namespace Catch {
  3626. enum class Verbosity {
  3627. Quiet = 0,
  3628. Normal,
  3629. High
  3630. };
  3631. struct WarnAbout { enum What {
  3632. Nothing = 0x00,
  3633. NoAssertions = 0x01,
  3634. NoTests = 0x02
  3635. }; };
  3636. struct ShowDurations { enum OrNot {
  3637. DefaultForReporter,
  3638. Always,
  3639. Never
  3640. }; };
  3641. struct RunTests { enum InWhatOrder {
  3642. InDeclarationOrder,
  3643. InLexicographicalOrder,
  3644. InRandomOrder
  3645. }; };
  3646. struct UseColour { enum YesOrNo {
  3647. Auto,
  3648. Yes,
  3649. No
  3650. }; };
  3651. struct WaitForKeypress { enum When {
  3652. Never,
  3653. BeforeStart = 1,
  3654. BeforeExit = 2,
  3655. BeforeStartAndExit = BeforeStart | BeforeExit
  3656. }; };
  3657. class TestSpec;
  3658. struct IConfig : NonCopyable {
  3659. virtual ~IConfig();
  3660. virtual bool allowThrows() const = 0;
  3661. virtual std::ostream& stream() const = 0;
  3662. virtual std::string name() const = 0;
  3663. virtual bool includeSuccessfulResults() const = 0;
  3664. virtual bool shouldDebugBreak() const = 0;
  3665. virtual bool warnAboutMissingAssertions() const = 0;
  3666. virtual bool warnAboutNoTests() const = 0;
  3667. virtual int abortAfter() const = 0;
  3668. virtual bool showInvisibles() const = 0;
  3669. virtual ShowDurations::OrNot showDurations() const = 0;
  3670. virtual TestSpec const& testSpec() const = 0;
  3671. virtual bool hasTestFilters() const = 0;
  3672. virtual std::vector<std::string> const& getTestsOrTags() const = 0;
  3673. virtual RunTests::InWhatOrder runOrder() const = 0;
  3674. virtual unsigned int rngSeed() const = 0;
  3675. virtual UseColour::YesOrNo useColour() const = 0;
  3676. virtual std::vector<std::string> const& getSectionsToRun() const = 0;
  3677. virtual Verbosity verbosity() const = 0;
  3678. virtual bool benchmarkNoAnalysis() const = 0;
  3679. virtual int benchmarkSamples() const = 0;
  3680. virtual double benchmarkConfidenceInterval() const = 0;
  3681. virtual unsigned int benchmarkResamples() const = 0;
  3682. };
  3683. using IConfigPtr = std::shared_ptr<IConfig const>;
  3684. }
  3685. // end catch_interfaces_config.h
  3686. #include <random>
  3687. namespace Catch {
  3688. namespace Generators {
  3689. template <typename Float>
  3690. class RandomFloatingGenerator final : public IGenerator<Float> {
  3691. // FIXME: What is the right seed?
  3692. std::minstd_rand m_rand;
  3693. std::uniform_real_distribution<Float> m_dist;
  3694. Float m_current_number;
  3695. public:
  3696. RandomFloatingGenerator(Float a, Float b):
  3697. m_rand(getCurrentContext().getConfig()->rngSeed()),
  3698. m_dist(a, b) {
  3699. static_cast<void>(next());
  3700. }
  3701. Float const& get() const override {
  3702. return m_current_number;
  3703. }
  3704. bool next() override {
  3705. m_current_number = m_dist(m_rand);
  3706. return true;
  3707. }
  3708. };
  3709. template <typename Integer>
  3710. class RandomIntegerGenerator final : public IGenerator<Integer> {
  3711. std::minstd_rand m_rand;
  3712. std::uniform_int_distribution<Integer> m_dist;
  3713. Integer m_current_number;
  3714. public:
  3715. RandomIntegerGenerator(Integer a, Integer b):
  3716. m_rand(getCurrentContext().getConfig()->rngSeed()),
  3717. m_dist(a, b) {
  3718. static_cast<void>(next());
  3719. }
  3720. Integer const& get() const override {
  3721. return m_current_number;
  3722. }
  3723. bool next() override {
  3724. m_current_number = m_dist(m_rand);
  3725. return true;
  3726. }
  3727. };
  3728. // TODO: Ideally this would be also constrained against the various char types,
  3729. // but I don't expect users to run into that in practice.
  3730. template <typename T>
  3731. typename std::enable_if<std::is_integral<T>::value && !std::is_same<T, bool>::value,
  3732. GeneratorWrapper<T>>::type
  3733. random(T a, T b) {
  3734. return GeneratorWrapper<T>(
  3735. pf::make_unique<RandomIntegerGenerator<T>>(a, b)
  3736. );
  3737. }
  3738. template <typename T>
  3739. typename std::enable_if<std::is_floating_point<T>::value,
  3740. GeneratorWrapper<T>>::type
  3741. random(T a, T b) {
  3742. return GeneratorWrapper<T>(
  3743. pf::make_unique<RandomFloatingGenerator<T>>(a, b)
  3744. );
  3745. }
  3746. template <typename T>
  3747. class RangeGenerator final : public IGenerator<T> {
  3748. T m_current;
  3749. T m_end;
  3750. T m_step;
  3751. bool m_positive;
  3752. public:
  3753. RangeGenerator(T const& start, T const& end, T const& step):
  3754. m_current(start),
  3755. m_end(end),
  3756. m_step(step),
  3757. m_positive(m_step > T(0))
  3758. {
  3759. assert(m_current != m_end && "Range start and end cannot be equal");
  3760. assert(m_step != T(0) && "Step size cannot be zero");
  3761. assert(((m_positive && m_current <= m_end) || (!m_positive && m_current >= m_end)) && "Step moves away from end");
  3762. }
  3763. RangeGenerator(T const& start, T const& end):
  3764. RangeGenerator(start, end, (start < end) ? T(1) : T(-1))
  3765. {}
  3766. T const& get() const override {
  3767. return m_current;
  3768. }
  3769. bool next() override {
  3770. m_current += m_step;
  3771. return (m_positive) ? (m_current < m_end) : (m_current > m_end);
  3772. }
  3773. };
  3774. template <typename T>
  3775. GeneratorWrapper<T> range(T const& start, T const& end, T const& step) {
  3776. static_assert(std::is_integral<T>::value && !std::is_same<T, bool>::value, "Type must be an integer");
  3777. return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end, step));
  3778. }
  3779. template <typename T>
  3780. GeneratorWrapper<T> range(T const& start, T const& end) {
  3781. static_assert(std::is_integral<T>::value && !std::is_same<T, bool>::value, "Type must be an integer");
  3782. return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end));
  3783. }
  3784. } // namespace Generators
  3785. } // namespace Catch
  3786. // end catch_generators_specific.hpp
  3787. // These files are included here so the single_include script doesn't put them
  3788. // in the conditionally compiled sections
  3789. // start catch_test_case_info.h
  3790. #include <string>
  3791. #include <vector>
  3792. #include <memory>
  3793. #ifdef __clang__
  3794. #pragma clang diagnostic push
  3795. #pragma clang diagnostic ignored "-Wpadded"
  3796. #endif
  3797. namespace Catch {
  3798. struct ITestInvoker;
  3799. struct TestCaseInfo {
  3800. enum SpecialProperties{
  3801. None = 0,
  3802. IsHidden = 1 << 1,
  3803. ShouldFail = 1 << 2,
  3804. MayFail = 1 << 3,
  3805. Throws = 1 << 4,
  3806. NonPortable = 1 << 5,
  3807. Benchmark = 1 << 6
  3808. };
  3809. TestCaseInfo( std::string const& _name,
  3810. std::string const& _className,
  3811. std::string const& _description,
  3812. std::vector<std::string> const& _tags,
  3813. SourceLineInfo const& _lineInfo );
  3814. friend void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags );
  3815. bool isHidden() const;
  3816. bool throws() const;
  3817. bool okToFail() const;
  3818. bool expectedToFail() const;
  3819. std::string tagsAsString() const;
  3820. std::string name;
  3821. std::string className;
  3822. std::string description;
  3823. std::vector<std::string> tags;
  3824. std::vector<std::string> lcaseTags;
  3825. SourceLineInfo lineInfo;
  3826. SpecialProperties properties;
  3827. };
  3828. class TestCase : public TestCaseInfo {
  3829. public:
  3830. TestCase( ITestInvoker* testCase, TestCaseInfo&& info );
  3831. TestCase withName( std::string const& _newName ) const;
  3832. void invoke() const;
  3833. TestCaseInfo const& getTestCaseInfo() const;
  3834. bool operator == ( TestCase const& other ) const;
  3835. bool operator < ( TestCase const& other ) const;
  3836. private:
  3837. std::shared_ptr<ITestInvoker> test;
  3838. };
  3839. TestCase makeTestCase( ITestInvoker* testCase,
  3840. std::string const& className,
  3841. NameAndTags const& nameAndTags,
  3842. SourceLineInfo const& lineInfo );
  3843. }
  3844. #ifdef __clang__
  3845. #pragma clang diagnostic pop
  3846. #endif
  3847. // end catch_test_case_info.h
  3848. // start catch_interfaces_runner.h
  3849. namespace Catch {
  3850. struct IRunner {
  3851. virtual ~IRunner();
  3852. virtual bool aborting() const = 0;
  3853. };
  3854. }
  3855. // end catch_interfaces_runner.h
  3856. #ifdef __OBJC__
  3857. // start catch_objc.hpp
  3858. #import <objc/runtime.h>
  3859. #include <string>
  3860. // NB. Any general catch headers included here must be included
  3861. // in catch.hpp first to make sure they are included by the single
  3862. // header for non obj-usage
  3863. ///////////////////////////////////////////////////////////////////////////////
  3864. // This protocol is really only here for (self) documenting purposes, since
  3865. // all its methods are optional.
  3866. @protocol OcFixture
  3867. @optional
  3868. -(void) setUp;
  3869. -(void) tearDown;
  3870. @end
  3871. namespace Catch {
  3872. class OcMethod : public ITestInvoker {
  3873. public:
  3874. OcMethod( Class cls, SEL sel ) : m_cls( cls ), m_sel( sel ) {}
  3875. virtual void invoke() const {
  3876. id obj = [[m_cls alloc] init];
  3877. performOptionalSelector( obj, @selector(setUp) );
  3878. performOptionalSelector( obj, m_sel );
  3879. performOptionalSelector( obj, @selector(tearDown) );
  3880. arcSafeRelease( obj );
  3881. }
  3882. private:
  3883. virtual ~OcMethod() {}
  3884. Class m_cls;
  3885. SEL m_sel;
  3886. };
  3887. namespace Detail{
  3888. inline std::string getAnnotation( Class cls,
  3889. std::string const& annotationName,
  3890. std::string const& testCaseName ) {
  3891. NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()];
  3892. SEL sel = NSSelectorFromString( selStr );
  3893. arcSafeRelease( selStr );
  3894. id value = performOptionalSelector( cls, sel );
  3895. if( value )
  3896. return [(NSString*)value UTF8String];
  3897. return "";
  3898. }
  3899. }
  3900. inline std::size_t registerTestMethods() {
  3901. std::size_t noTestMethods = 0;
  3902. int noClasses = objc_getClassList( nullptr, 0 );
  3903. Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc( sizeof(Class) * noClasses);
  3904. objc_getClassList( classes, noClasses );
  3905. for( int c = 0; c < noClasses; c++ ) {
  3906. Class cls = classes[c];
  3907. {
  3908. u_int count;
  3909. Method* methods = class_copyMethodList( cls, &count );
  3910. for( u_int m = 0; m < count ; m++ ) {
  3911. SEL selector = method_getName(methods[m]);
  3912. std::string methodName = sel_getName(selector);
  3913. if( startsWith( methodName, "Catch_TestCase_" ) ) {
  3914. std::string testCaseName = methodName.substr( 15 );
  3915. std::string name = Detail::getAnnotation( cls, "Name", testCaseName );
  3916. std::string desc = Detail::getAnnotation( cls, "Description", testCaseName );
  3917. const char* className = class_getName( cls );
  3918. getMutableRegistryHub().registerTest( makeTestCase( new OcMethod( cls, selector ), className, NameAndTags( name.c_str(), desc.c_str() ), SourceLineInfo("",0) ) );
  3919. noTestMethods++;
  3920. }
  3921. }
  3922. free(methods);
  3923. }
  3924. }
  3925. return noTestMethods;
  3926. }
  3927. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  3928. namespace Matchers {
  3929. namespace Impl {
  3930. namespace NSStringMatchers {
  3931. struct StringHolder : MatcherBase<NSString*>{
  3932. StringHolder( NSString* substr ) : m_substr( [substr copy] ){}
  3933. StringHolder( StringHolder const& other ) : m_substr( [other.m_substr copy] ){}
  3934. StringHolder() {
  3935. arcSafeRelease( m_substr );
  3936. }
  3937. bool match( NSString* str ) const override {
  3938. return false;
  3939. }
  3940. NSString* CATCH_ARC_STRONG m_substr;
  3941. };
  3942. struct Equals : StringHolder {
  3943. Equals( NSString* substr ) : StringHolder( substr ){}
  3944. bool match( NSString* str ) const override {
  3945. return (str != nil || m_substr == nil ) &&
  3946. [str isEqualToString:m_substr];
  3947. }
  3948. std::string describe() const override {
  3949. return "equals string: " + Catch::Detail::stringify( m_substr );
  3950. }
  3951. };
  3952. struct Contains : StringHolder {
  3953. Contains( NSString* substr ) : StringHolder( substr ){}
  3954. bool match( NSString* str ) const override {
  3955. return (str != nil || m_substr == nil ) &&
  3956. [str rangeOfString:m_substr].location != NSNotFound;
  3957. }
  3958. std::string describe() const override {
  3959. return "contains string: " + Catch::Detail::stringify( m_substr );
  3960. }
  3961. };
  3962. struct StartsWith : StringHolder {
  3963. StartsWith( NSString* substr ) : StringHolder( substr ){}
  3964. bool match( NSString* str ) const override {
  3965. return (str != nil || m_substr == nil ) &&
  3966. [str rangeOfString:m_substr].location == 0;
  3967. }
  3968. std::string describe() const override {
  3969. return "starts with: " + Catch::Detail::stringify( m_substr );
  3970. }
  3971. };
  3972. struct EndsWith : StringHolder {
  3973. EndsWith( NSString* substr ) : StringHolder( substr ){}
  3974. bool match( NSString* str ) const override {
  3975. return (str != nil || m_substr == nil ) &&
  3976. [str rangeOfString:m_substr].location == [str length] - [m_substr length];
  3977. }
  3978. std::string describe() const override {
  3979. return "ends with: " + Catch::Detail::stringify( m_substr );
  3980. }
  3981. };
  3982. } // namespace NSStringMatchers
  3983. } // namespace Impl
  3984. inline Impl::NSStringMatchers::Equals
  3985. Equals( NSString* substr ){ return Impl::NSStringMatchers::Equals( substr ); }
  3986. inline Impl::NSStringMatchers::Contains
  3987. Contains( NSString* substr ){ return Impl::NSStringMatchers::Contains( substr ); }
  3988. inline Impl::NSStringMatchers::StartsWith
  3989. StartsWith( NSString* substr ){ return Impl::NSStringMatchers::StartsWith( substr ); }
  3990. inline Impl::NSStringMatchers::EndsWith
  3991. EndsWith( NSString* substr ){ return Impl::NSStringMatchers::EndsWith( substr ); }
  3992. } // namespace Matchers
  3993. using namespace Matchers;
  3994. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  3995. } // namespace Catch
  3996. ///////////////////////////////////////////////////////////////////////////////
  3997. #define OC_MAKE_UNIQUE_NAME( root, uniqueSuffix ) root##uniqueSuffix
  3998. #define OC_TEST_CASE2( name, desc, uniqueSuffix ) \
  3999. +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Name_test_, uniqueSuffix ) \
  4000. { \
  4001. return @ name; \
  4002. } \
  4003. +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Description_test_, uniqueSuffix ) \
  4004. { \
  4005. return @ desc; \
  4006. } \
  4007. -(void) OC_MAKE_UNIQUE_NAME( Catch_TestCase_test_, uniqueSuffix )
  4008. #define OC_TEST_CASE( name, desc ) OC_TEST_CASE2( name, desc, __LINE__ )
  4009. // end catch_objc.hpp
  4010. #endif
  4011. // Benchmarking needs the externally-facing parts of reporters to work
  4012. #if defined(CATCH_CONFIG_EXTERNAL_INTERFACES) || defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  4013. // start catch_external_interfaces.h
  4014. // start catch_reporter_bases.hpp
  4015. // start catch_interfaces_reporter.h
  4016. // start catch_config.hpp
  4017. // start catch_test_spec_parser.h
  4018. #ifdef __clang__
  4019. #pragma clang diagnostic push
  4020. #pragma clang diagnostic ignored "-Wpadded"
  4021. #endif
  4022. // start catch_test_spec.h
  4023. #ifdef __clang__
  4024. #pragma clang diagnostic push
  4025. #pragma clang diagnostic ignored "-Wpadded"
  4026. #endif
  4027. // start catch_wildcard_pattern.h
  4028. namespace Catch
  4029. {
  4030. class WildcardPattern {
  4031. enum WildcardPosition {
  4032. NoWildcard = 0,
  4033. WildcardAtStart = 1,
  4034. WildcardAtEnd = 2,
  4035. WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd
  4036. };
  4037. public:
  4038. WildcardPattern( std::string const& pattern, CaseSensitive::Choice caseSensitivity );
  4039. virtual ~WildcardPattern() = default;
  4040. virtual bool matches( std::string const& str ) const;
  4041. private:
  4042. std::string adjustCase( std::string const& str ) const;
  4043. CaseSensitive::Choice m_caseSensitivity;
  4044. WildcardPosition m_wildcard = NoWildcard;
  4045. std::string m_pattern;
  4046. };
  4047. }
  4048. // end catch_wildcard_pattern.h
  4049. #include <string>
  4050. #include <vector>
  4051. #include <memory>
  4052. namespace Catch {
  4053. struct IConfig;
  4054. class TestSpec {
  4055. class Pattern {
  4056. public:
  4057. explicit Pattern( std::string const& name );
  4058. virtual ~Pattern();
  4059. virtual bool matches( TestCaseInfo const& testCase ) const = 0;
  4060. std::string const& name() const;
  4061. private:
  4062. std::string const m_name;
  4063. };
  4064. using PatternPtr = std::shared_ptr<Pattern>;
  4065. class NamePattern : public Pattern {
  4066. public:
  4067. explicit NamePattern( std::string const& name, std::string const& filterString );
  4068. bool matches( TestCaseInfo const& testCase ) const override;
  4069. private:
  4070. WildcardPattern m_wildcardPattern;
  4071. };
  4072. class TagPattern : public Pattern {
  4073. public:
  4074. explicit TagPattern( std::string const& tag, std::string const& filterString );
  4075. bool matches( TestCaseInfo const& testCase ) const override;
  4076. private:
  4077. std::string m_tag;
  4078. };
  4079. class ExcludedPattern : public Pattern {
  4080. public:
  4081. explicit ExcludedPattern( PatternPtr const& underlyingPattern );
  4082. bool matches( TestCaseInfo const& testCase ) const override;
  4083. private:
  4084. PatternPtr m_underlyingPattern;
  4085. };
  4086. struct Filter {
  4087. std::vector<PatternPtr> m_patterns;
  4088. bool matches( TestCaseInfo const& testCase ) const;
  4089. std::string name() const;
  4090. };
  4091. public:
  4092. struct FilterMatch {
  4093. std::string name;
  4094. std::vector<TestCase const*> tests;
  4095. };
  4096. using Matches = std::vector<FilterMatch>;
  4097. bool hasFilters() const;
  4098. bool matches( TestCaseInfo const& testCase ) const;
  4099. Matches matchesByFilter( std::vector<TestCase> const& testCases, IConfig const& config ) const;
  4100. private:
  4101. std::vector<Filter> m_filters;
  4102. friend class TestSpecParser;
  4103. };
  4104. }
  4105. #ifdef __clang__
  4106. #pragma clang diagnostic pop
  4107. #endif
  4108. // end catch_test_spec.h
  4109. // start catch_interfaces_tag_alias_registry.h
  4110. #include <string>
  4111. namespace Catch {
  4112. struct TagAlias;
  4113. struct ITagAliasRegistry {
  4114. virtual ~ITagAliasRegistry();
  4115. // Nullptr if not present
  4116. virtual TagAlias const* find( std::string const& alias ) const = 0;
  4117. virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const = 0;
  4118. static ITagAliasRegistry const& get();
  4119. };
  4120. } // end namespace Catch
  4121. // end catch_interfaces_tag_alias_registry.h
  4122. namespace Catch {
  4123. class TestSpecParser {
  4124. enum Mode{ None, Name, QuotedName, Tag, EscapedName };
  4125. Mode m_mode = None;
  4126. bool m_exclusion = false;
  4127. std::size_t m_pos = 0;
  4128. std::string m_arg;
  4129. std::string m_substring;
  4130. std::string m_patternName;
  4131. std::vector<std::size_t> m_escapeChars;
  4132. TestSpec::Filter m_currentFilter;
  4133. TestSpec m_testSpec;
  4134. ITagAliasRegistry const* m_tagAliases = nullptr;
  4135. public:
  4136. TestSpecParser( ITagAliasRegistry const& tagAliases );
  4137. TestSpecParser& parse( std::string const& arg );
  4138. TestSpec testSpec();
  4139. private:
  4140. void visitChar( char c );
  4141. void startNewMode( Mode mode );
  4142. bool processNoneChar( char c );
  4143. void processNameChar( char c );
  4144. bool processOtherChar( char c );
  4145. void endMode();
  4146. void escape();
  4147. bool isControlChar( char c ) const;
  4148. template<typename T>
  4149. void addPattern() {
  4150. std::string token = m_patternName;
  4151. for( std::size_t i = 0; i < m_escapeChars.size(); ++i )
  4152. token = token.substr( 0, m_escapeChars[i] - i ) + token.substr( m_escapeChars[i] -i +1 );
  4153. m_escapeChars.clear();
  4154. if( startsWith( token, "exclude:" ) ) {
  4155. m_exclusion = true;
  4156. token = token.substr( 8 );
  4157. }
  4158. if( !token.empty() ) {
  4159. TestSpec::PatternPtr pattern = std::make_shared<T>( token, m_substring );
  4160. if( m_exclusion )
  4161. pattern = std::make_shared<TestSpec::ExcludedPattern>( pattern );
  4162. m_currentFilter.m_patterns.push_back( pattern );
  4163. }
  4164. m_substring.clear();
  4165. m_patternName.clear();
  4166. m_exclusion = false;
  4167. m_mode = None;
  4168. }
  4169. void addFilter();
  4170. };
  4171. TestSpec parseTestSpec( std::string const& arg );
  4172. } // namespace Catch
  4173. #ifdef __clang__
  4174. #pragma clang diagnostic pop
  4175. #endif
  4176. // end catch_test_spec_parser.h
  4177. // Libstdc++ doesn't like incomplete classes for unique_ptr
  4178. #include <memory>
  4179. #include <vector>
  4180. #include <string>
  4181. #ifndef CATCH_CONFIG_CONSOLE_WIDTH
  4182. #define CATCH_CONFIG_CONSOLE_WIDTH 80
  4183. #endif
  4184. namespace Catch {
  4185. struct IStream;
  4186. struct ConfigData {
  4187. bool listTests = false;
  4188. bool listTags = false;
  4189. bool listReporters = false;
  4190. bool listTestNamesOnly = false;
  4191. bool showSuccessfulTests = false;
  4192. bool shouldDebugBreak = false;
  4193. bool noThrow = false;
  4194. bool showHelp = false;
  4195. bool showInvisibles = false;
  4196. bool filenamesAsTags = false;
  4197. bool libIdentify = false;
  4198. int abortAfter = -1;
  4199. unsigned int rngSeed = 0;
  4200. bool benchmarkNoAnalysis = false;
  4201. unsigned int benchmarkSamples = 100;
  4202. double benchmarkConfidenceInterval = 0.95;
  4203. unsigned int benchmarkResamples = 100000;
  4204. Verbosity verbosity = Verbosity::Normal;
  4205. WarnAbout::What warnings = WarnAbout::Nothing;
  4206. ShowDurations::OrNot showDurations = ShowDurations::DefaultForReporter;
  4207. RunTests::InWhatOrder runOrder = RunTests::InDeclarationOrder;
  4208. UseColour::YesOrNo useColour = UseColour::Auto;
  4209. WaitForKeypress::When waitForKeypress = WaitForKeypress::Never;
  4210. std::string outputFilename;
  4211. std::string name;
  4212. std::string processName;
  4213. #ifndef CATCH_CONFIG_DEFAULT_REPORTER
  4214. #define CATCH_CONFIG_DEFAULT_REPORTER "console"
  4215. #endif
  4216. std::string reporterName = CATCH_CONFIG_DEFAULT_REPORTER;
  4217. #undef CATCH_CONFIG_DEFAULT_REPORTER
  4218. std::vector<std::string> testsOrTags;
  4219. std::vector<std::string> sectionsToRun;
  4220. };
  4221. class Config : public IConfig {
  4222. public:
  4223. Config() = default;
  4224. Config( ConfigData const& data );
  4225. virtual ~Config() = default;
  4226. std::string const& getFilename() const;
  4227. bool listTests() const;
  4228. bool listTestNamesOnly() const;
  4229. bool listTags() const;
  4230. bool listReporters() const;
  4231. std::string getProcessName() const;
  4232. std::string const& getReporterName() const;
  4233. std::vector<std::string> const& getTestsOrTags() const override;
  4234. std::vector<std::string> const& getSectionsToRun() const override;
  4235. TestSpec const& testSpec() const override;
  4236. bool hasTestFilters() const override;
  4237. bool showHelp() const;
  4238. // IConfig interface
  4239. bool allowThrows() const override;
  4240. std::ostream& stream() const override;
  4241. std::string name() const override;
  4242. bool includeSuccessfulResults() const override;
  4243. bool warnAboutMissingAssertions() const override;
  4244. bool warnAboutNoTests() const override;
  4245. ShowDurations::OrNot showDurations() const override;
  4246. RunTests::InWhatOrder runOrder() const override;
  4247. unsigned int rngSeed() const override;
  4248. UseColour::YesOrNo useColour() const override;
  4249. bool shouldDebugBreak() const override;
  4250. int abortAfter() const override;
  4251. bool showInvisibles() const override;
  4252. Verbosity verbosity() const override;
  4253. bool benchmarkNoAnalysis() const override;
  4254. int benchmarkSamples() const override;
  4255. double benchmarkConfidenceInterval() const override;
  4256. unsigned int benchmarkResamples() const override;
  4257. private:
  4258. IStream const* openStream();
  4259. ConfigData m_data;
  4260. std::unique_ptr<IStream const> m_stream;
  4261. TestSpec m_testSpec;
  4262. bool m_hasTestFilters = false;
  4263. };
  4264. } // end namespace Catch
  4265. // end catch_config.hpp
  4266. // start catch_assertionresult.h
  4267. #include <string>
  4268. namespace Catch {
  4269. struct AssertionResultData
  4270. {
  4271. AssertionResultData() = delete;
  4272. AssertionResultData( ResultWas::OfType _resultType, LazyExpression const& _lazyExpression );
  4273. std::string message;
  4274. mutable std::string reconstructedExpression;
  4275. LazyExpression lazyExpression;
  4276. ResultWas::OfType resultType;
  4277. std::string reconstructExpression() const;
  4278. };
  4279. class AssertionResult {
  4280. public:
  4281. AssertionResult() = delete;
  4282. AssertionResult( AssertionInfo const& info, AssertionResultData const& data );
  4283. bool isOk() const;
  4284. bool succeeded() const;
  4285. ResultWas::OfType getResultType() const;
  4286. bool hasExpression() const;
  4287. bool hasMessage() const;
  4288. std::string getExpression() const;
  4289. std::string getExpressionInMacro() const;
  4290. bool hasExpandedExpression() const;
  4291. std::string getExpandedExpression() const;
  4292. std::string getMessage() const;
  4293. SourceLineInfo getSourceInfo() const;
  4294. StringRef getTestMacroName() const;
  4295. //protected:
  4296. AssertionInfo m_info;
  4297. AssertionResultData m_resultData;
  4298. };
  4299. } // end namespace Catch
  4300. // end catch_assertionresult.h
  4301. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  4302. // start catch_estimate.hpp
  4303. // Statistics estimates
  4304. namespace Catch {
  4305. namespace Benchmark {
  4306. template <typename Duration>
  4307. struct Estimate {
  4308. Duration point;
  4309. Duration lower_bound;
  4310. Duration upper_bound;
  4311. double confidence_interval;
  4312. template <typename Duration2>
  4313. operator Estimate<Duration2>() const {
  4314. return { point, lower_bound, upper_bound, confidence_interval };
  4315. }
  4316. };
  4317. } // namespace Benchmark
  4318. } // namespace Catch
  4319. // end catch_estimate.hpp
  4320. // start catch_outlier_classification.hpp
  4321. // Outlier information
  4322. namespace Catch {
  4323. namespace Benchmark {
  4324. struct OutlierClassification {
  4325. int samples_seen = 0;
  4326. int low_severe = 0; // more than 3 times IQR below Q1
  4327. int low_mild = 0; // 1.5 to 3 times IQR below Q1
  4328. int high_mild = 0; // 1.5 to 3 times IQR above Q3
  4329. int high_severe = 0; // more than 3 times IQR above Q3
  4330. int total() const {
  4331. return low_severe + low_mild + high_mild + high_severe;
  4332. }
  4333. };
  4334. } // namespace Benchmark
  4335. } // namespace Catch
  4336. // end catch_outlier_classification.hpp
  4337. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  4338. #include <string>
  4339. #include <iosfwd>
  4340. #include <map>
  4341. #include <set>
  4342. #include <memory>
  4343. #include <algorithm>
  4344. namespace Catch {
  4345. struct ReporterConfig {
  4346. explicit ReporterConfig( IConfigPtr const& _fullConfig );
  4347. ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream );
  4348. std::ostream& stream() const;
  4349. IConfigPtr fullConfig() const;
  4350. private:
  4351. std::ostream* m_stream;
  4352. IConfigPtr m_fullConfig;
  4353. };
  4354. struct ReporterPreferences {
  4355. bool shouldRedirectStdOut = false;
  4356. bool shouldReportAllAssertions = false;
  4357. };
  4358. template<typename T>
  4359. struct LazyStat : Option<T> {
  4360. LazyStat& operator=( T const& _value ) {
  4361. Option<T>::operator=( _value );
  4362. used = false;
  4363. return *this;
  4364. }
  4365. void reset() {
  4366. Option<T>::reset();
  4367. used = false;
  4368. }
  4369. bool used = false;
  4370. };
  4371. struct TestRunInfo {
  4372. TestRunInfo( std::string const& _name );
  4373. std::string name;
  4374. };
  4375. struct GroupInfo {
  4376. GroupInfo( std::string const& _name,
  4377. std::size_t _groupIndex,
  4378. std::size_t _groupsCount );
  4379. std::string name;
  4380. std::size_t groupIndex;
  4381. std::size_t groupsCounts;
  4382. };
  4383. struct AssertionStats {
  4384. AssertionStats( AssertionResult const& _assertionResult,
  4385. std::vector<MessageInfo> const& _infoMessages,
  4386. Totals const& _totals );
  4387. AssertionStats( AssertionStats const& ) = default;
  4388. AssertionStats( AssertionStats && ) = default;
  4389. AssertionStats& operator = ( AssertionStats const& ) = delete;
  4390. AssertionStats& operator = ( AssertionStats && ) = delete;
  4391. virtual ~AssertionStats();
  4392. AssertionResult assertionResult;
  4393. std::vector<MessageInfo> infoMessages;
  4394. Totals totals;
  4395. };
  4396. struct SectionStats {
  4397. SectionStats( SectionInfo const& _sectionInfo,
  4398. Counts const& _assertions,
  4399. double _durationInSeconds,
  4400. bool _missingAssertions );
  4401. SectionStats( SectionStats const& ) = default;
  4402. SectionStats( SectionStats && ) = default;
  4403. SectionStats& operator = ( SectionStats const& ) = default;
  4404. SectionStats& operator = ( SectionStats && ) = default;
  4405. virtual ~SectionStats();
  4406. SectionInfo sectionInfo;
  4407. Counts assertions;
  4408. double durationInSeconds;
  4409. bool missingAssertions;
  4410. };
  4411. struct TestCaseStats {
  4412. TestCaseStats( TestCaseInfo const& _testInfo,
  4413. Totals const& _totals,
  4414. std::string const& _stdOut,
  4415. std::string const& _stdErr,
  4416. bool _aborting );
  4417. TestCaseStats( TestCaseStats const& ) = default;
  4418. TestCaseStats( TestCaseStats && ) = default;
  4419. TestCaseStats& operator = ( TestCaseStats const& ) = default;
  4420. TestCaseStats& operator = ( TestCaseStats && ) = default;
  4421. virtual ~TestCaseStats();
  4422. TestCaseInfo testInfo;
  4423. Totals totals;
  4424. std::string stdOut;
  4425. std::string stdErr;
  4426. bool aborting;
  4427. };
  4428. struct TestGroupStats {
  4429. TestGroupStats( GroupInfo const& _groupInfo,
  4430. Totals const& _totals,
  4431. bool _aborting );
  4432. TestGroupStats( GroupInfo const& _groupInfo );
  4433. TestGroupStats( TestGroupStats const& ) = default;
  4434. TestGroupStats( TestGroupStats && ) = default;
  4435. TestGroupStats& operator = ( TestGroupStats const& ) = default;
  4436. TestGroupStats& operator = ( TestGroupStats && ) = default;
  4437. virtual ~TestGroupStats();
  4438. GroupInfo groupInfo;
  4439. Totals totals;
  4440. bool aborting;
  4441. };
  4442. struct TestRunStats {
  4443. TestRunStats( TestRunInfo const& _runInfo,
  4444. Totals const& _totals,
  4445. bool _aborting );
  4446. TestRunStats( TestRunStats const& ) = default;
  4447. TestRunStats( TestRunStats && ) = default;
  4448. TestRunStats& operator = ( TestRunStats const& ) = default;
  4449. TestRunStats& operator = ( TestRunStats && ) = default;
  4450. virtual ~TestRunStats();
  4451. TestRunInfo runInfo;
  4452. Totals totals;
  4453. bool aborting;
  4454. };
  4455. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  4456. struct BenchmarkInfo {
  4457. std::string name;
  4458. double estimatedDuration;
  4459. int iterations;
  4460. int samples;
  4461. unsigned int resamples;
  4462. double clockResolution;
  4463. double clockCost;
  4464. };
  4465. template <class Duration>
  4466. struct BenchmarkStats {
  4467. BenchmarkInfo info;
  4468. std::vector<Duration> samples;
  4469. Benchmark::Estimate<Duration> mean;
  4470. Benchmark::Estimate<Duration> standardDeviation;
  4471. Benchmark::OutlierClassification outliers;
  4472. double outlierVariance;
  4473. template <typename Duration2>
  4474. operator BenchmarkStats<Duration2>() const {
  4475. std::vector<Duration2> samples2;
  4476. samples2.reserve(samples.size());
  4477. std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration d) { return Duration2(d); });
  4478. return {
  4479. info,
  4480. std::move(samples2),
  4481. mean,
  4482. standardDeviation,
  4483. outliers,
  4484. outlierVariance,
  4485. };
  4486. }
  4487. };
  4488. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  4489. struct IStreamingReporter {
  4490. virtual ~IStreamingReporter() = default;
  4491. // Implementing class must also provide the following static methods:
  4492. // static std::string getDescription();
  4493. // static std::set<Verbosity> getSupportedVerbosities()
  4494. virtual ReporterPreferences getPreferences() const = 0;
  4495. virtual void noMatchingTestCases( std::string const& spec ) = 0;
  4496. virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0;
  4497. virtual void testGroupStarting( GroupInfo const& groupInfo ) = 0;
  4498. virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0;
  4499. virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0;
  4500. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  4501. virtual void benchmarkPreparing( std::string const& ) {}
  4502. virtual void benchmarkStarting( BenchmarkInfo const& ) {}
  4503. virtual void benchmarkEnded( BenchmarkStats<> const& ) {}
  4504. virtual void benchmarkFailed( std::string const& ) {}
  4505. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  4506. virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0;
  4507. // The return value indicates if the messages buffer should be cleared:
  4508. virtual bool assertionEnded( AssertionStats const& assertionStats ) = 0;
  4509. virtual void sectionEnded( SectionStats const& sectionStats ) = 0;
  4510. virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0;
  4511. virtual void testGroupEnded( TestGroupStats const& testGroupStats ) = 0;
  4512. virtual void testRunEnded( TestRunStats const& testRunStats ) = 0;
  4513. virtual void skipTest( TestCaseInfo const& testInfo ) = 0;
  4514. // Default empty implementation provided
  4515. virtual void fatalErrorEncountered( StringRef name );
  4516. virtual bool isMulti() const;
  4517. };
  4518. using IStreamingReporterPtr = std::unique_ptr<IStreamingReporter>;
  4519. struct IReporterFactory {
  4520. virtual ~IReporterFactory();
  4521. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const = 0;
  4522. virtual std::string getDescription() const = 0;
  4523. };
  4524. using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
  4525. struct IReporterRegistry {
  4526. using FactoryMap = std::map<std::string, IReporterFactoryPtr>;
  4527. using Listeners = std::vector<IReporterFactoryPtr>;
  4528. virtual ~IReporterRegistry();
  4529. virtual IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const = 0;
  4530. virtual FactoryMap const& getFactories() const = 0;
  4531. virtual Listeners const& getListeners() const = 0;
  4532. };
  4533. } // end namespace Catch
  4534. // end catch_interfaces_reporter.h
  4535. #include <algorithm>
  4536. #include <cstring>
  4537. #include <cfloat>
  4538. #include <cstdio>
  4539. #include <cassert>
  4540. #include <memory>
  4541. #include <ostream>
  4542. namespace Catch {
  4543. void prepareExpandedExpression(AssertionResult& result);
  4544. // Returns double formatted as %.3f (format expected on output)
  4545. std::string getFormattedDuration( double duration );
  4546. std::string serializeFilters( std::vector<std::string> const& container );
  4547. template<typename DerivedT>
  4548. struct StreamingReporterBase : IStreamingReporter {
  4549. StreamingReporterBase( ReporterConfig const& _config )
  4550. : m_config( _config.fullConfig() ),
  4551. stream( _config.stream() )
  4552. {
  4553. m_reporterPrefs.shouldRedirectStdOut = false;
  4554. if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
  4555. CATCH_ERROR( "Verbosity level not supported by this reporter" );
  4556. }
  4557. ReporterPreferences getPreferences() const override {
  4558. return m_reporterPrefs;
  4559. }
  4560. static std::set<Verbosity> getSupportedVerbosities() {
  4561. return { Verbosity::Normal };
  4562. }
  4563. ~StreamingReporterBase() override = default;
  4564. void noMatchingTestCases(std::string const&) override {}
  4565. void testRunStarting(TestRunInfo const& _testRunInfo) override {
  4566. currentTestRunInfo = _testRunInfo;
  4567. }
  4568. void testGroupStarting(GroupInfo const& _groupInfo) override {
  4569. currentGroupInfo = _groupInfo;
  4570. }
  4571. void testCaseStarting(TestCaseInfo const& _testInfo) override {
  4572. currentTestCaseInfo = _testInfo;
  4573. }
  4574. void sectionStarting(SectionInfo const& _sectionInfo) override {
  4575. m_sectionStack.push_back(_sectionInfo);
  4576. }
  4577. void sectionEnded(SectionStats const& /* _sectionStats */) override {
  4578. m_sectionStack.pop_back();
  4579. }
  4580. void testCaseEnded(TestCaseStats const& /* _testCaseStats */) override {
  4581. currentTestCaseInfo.reset();
  4582. }
  4583. void testGroupEnded(TestGroupStats const& /* _testGroupStats */) override {
  4584. currentGroupInfo.reset();
  4585. }
  4586. void testRunEnded(TestRunStats const& /* _testRunStats */) override {
  4587. currentTestCaseInfo.reset();
  4588. currentGroupInfo.reset();
  4589. currentTestRunInfo.reset();
  4590. }
  4591. void skipTest(TestCaseInfo const&) override {
  4592. // Don't do anything with this by default.
  4593. // It can optionally be overridden in the derived class.
  4594. }
  4595. IConfigPtr m_config;
  4596. std::ostream& stream;
  4597. LazyStat<TestRunInfo> currentTestRunInfo;
  4598. LazyStat<GroupInfo> currentGroupInfo;
  4599. LazyStat<TestCaseInfo> currentTestCaseInfo;
  4600. std::vector<SectionInfo> m_sectionStack;
  4601. ReporterPreferences m_reporterPrefs;
  4602. };
  4603. template<typename DerivedT>
  4604. struct CumulativeReporterBase : IStreamingReporter {
  4605. template<typename T, typename ChildNodeT>
  4606. struct Node {
  4607. explicit Node( T const& _value ) : value( _value ) {}
  4608. virtual ~Node() {}
  4609. using ChildNodes = std::vector<std::shared_ptr<ChildNodeT>>;
  4610. T value;
  4611. ChildNodes children;
  4612. };
  4613. struct SectionNode {
  4614. explicit SectionNode(SectionStats const& _stats) : stats(_stats) {}
  4615. virtual ~SectionNode() = default;
  4616. bool operator == (SectionNode const& other) const {
  4617. return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;
  4618. }
  4619. bool operator == (std::shared_ptr<SectionNode> const& other) const {
  4620. return operator==(*other);
  4621. }
  4622. SectionStats stats;
  4623. using ChildSections = std::vector<std::shared_ptr<SectionNode>>;
  4624. using Assertions = std::vector<AssertionStats>;
  4625. ChildSections childSections;
  4626. Assertions assertions;
  4627. std::string stdOut;
  4628. std::string stdErr;
  4629. };
  4630. struct BySectionInfo {
  4631. BySectionInfo( SectionInfo const& other ) : m_other( other ) {}
  4632. BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {}
  4633. bool operator() (std::shared_ptr<SectionNode> const& node) const {
  4634. return ((node->stats.sectionInfo.name == m_other.name) &&
  4635. (node->stats.sectionInfo.lineInfo == m_other.lineInfo));
  4636. }
  4637. void operator=(BySectionInfo const&) = delete;
  4638. private:
  4639. SectionInfo const& m_other;
  4640. };
  4641. using TestCaseNode = Node<TestCaseStats, SectionNode>;
  4642. using TestGroupNode = Node<TestGroupStats, TestCaseNode>;
  4643. using TestRunNode = Node<TestRunStats, TestGroupNode>;
  4644. CumulativeReporterBase( ReporterConfig const& _config )
  4645. : m_config( _config.fullConfig() ),
  4646. stream( _config.stream() )
  4647. {
  4648. m_reporterPrefs.shouldRedirectStdOut = false;
  4649. if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
  4650. CATCH_ERROR( "Verbosity level not supported by this reporter" );
  4651. }
  4652. ~CumulativeReporterBase() override = default;
  4653. ReporterPreferences getPreferences() const override {
  4654. return m_reporterPrefs;
  4655. }
  4656. static std::set<Verbosity> getSupportedVerbosities() {
  4657. return { Verbosity::Normal };
  4658. }
  4659. void testRunStarting( TestRunInfo const& ) override {}
  4660. void testGroupStarting( GroupInfo const& ) override {}
  4661. void testCaseStarting( TestCaseInfo const& ) override {}
  4662. void sectionStarting( SectionInfo const& sectionInfo ) override {
  4663. SectionStats incompleteStats( sectionInfo, Counts(), 0, false );
  4664. std::shared_ptr<SectionNode> node;
  4665. if( m_sectionStack.empty() ) {
  4666. if( !m_rootSection )
  4667. m_rootSection = std::make_shared<SectionNode>( incompleteStats );
  4668. node = m_rootSection;
  4669. }
  4670. else {
  4671. SectionNode& parentNode = *m_sectionStack.back();
  4672. auto it =
  4673. std::find_if( parentNode.childSections.begin(),
  4674. parentNode.childSections.end(),
  4675. BySectionInfo( sectionInfo ) );
  4676. if( it == parentNode.childSections.end() ) {
  4677. node = std::make_shared<SectionNode>( incompleteStats );
  4678. parentNode.childSections.push_back( node );
  4679. }
  4680. else
  4681. node = *it;
  4682. }
  4683. m_sectionStack.push_back( node );
  4684. m_deepestSection = std::move(node);
  4685. }
  4686. void assertionStarting(AssertionInfo const&) override {}
  4687. bool assertionEnded(AssertionStats const& assertionStats) override {
  4688. assert(!m_sectionStack.empty());
  4689. // AssertionResult holds a pointer to a temporary DecomposedExpression,
  4690. // which getExpandedExpression() calls to build the expression string.
  4691. // Our section stack copy of the assertionResult will likely outlive the
  4692. // temporary, so it must be expanded or discarded now to avoid calling
  4693. // a destroyed object later.
  4694. prepareExpandedExpression(const_cast<AssertionResult&>( assertionStats.assertionResult ) );
  4695. SectionNode& sectionNode = *m_sectionStack.back();
  4696. sectionNode.assertions.push_back(assertionStats);
  4697. return true;
  4698. }
  4699. void sectionEnded(SectionStats const& sectionStats) override {
  4700. assert(!m_sectionStack.empty());
  4701. SectionNode& node = *m_sectionStack.back();
  4702. node.stats = sectionStats;
  4703. m_sectionStack.pop_back();
  4704. }
  4705. void testCaseEnded(TestCaseStats const& testCaseStats) override {
  4706. auto node = std::make_shared<TestCaseNode>(testCaseStats);
  4707. assert(m_sectionStack.size() == 0);
  4708. node->children.push_back(m_rootSection);
  4709. m_testCases.push_back(node);
  4710. m_rootSection.reset();
  4711. assert(m_deepestSection);
  4712. m_deepestSection->stdOut = testCaseStats.stdOut;
  4713. m_deepestSection->stdErr = testCaseStats.stdErr;
  4714. }
  4715. void testGroupEnded(TestGroupStats const& testGroupStats) override {
  4716. auto node = std::make_shared<TestGroupNode>(testGroupStats);
  4717. node->children.swap(m_testCases);
  4718. m_testGroups.push_back(node);
  4719. }
  4720. void testRunEnded(TestRunStats const& testRunStats) override {
  4721. auto node = std::make_shared<TestRunNode>(testRunStats);
  4722. node->children.swap(m_testGroups);
  4723. m_testRuns.push_back(node);
  4724. testRunEndedCumulative();
  4725. }
  4726. virtual void testRunEndedCumulative() = 0;
  4727. void skipTest(TestCaseInfo const&) override {}
  4728. IConfigPtr m_config;
  4729. std::ostream& stream;
  4730. std::vector<AssertionStats> m_assertions;
  4731. std::vector<std::vector<std::shared_ptr<SectionNode>>> m_sections;
  4732. std::vector<std::shared_ptr<TestCaseNode>> m_testCases;
  4733. std::vector<std::shared_ptr<TestGroupNode>> m_testGroups;
  4734. std::vector<std::shared_ptr<TestRunNode>> m_testRuns;
  4735. std::shared_ptr<SectionNode> m_rootSection;
  4736. std::shared_ptr<SectionNode> m_deepestSection;
  4737. std::vector<std::shared_ptr<SectionNode>> m_sectionStack;
  4738. ReporterPreferences m_reporterPrefs;
  4739. };
  4740. template<char C>
  4741. char const* getLineOfChars() {
  4742. static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
  4743. if( !*line ) {
  4744. std::memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 );
  4745. line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0;
  4746. }
  4747. return line;
  4748. }
  4749. struct TestEventListenerBase : StreamingReporterBase<TestEventListenerBase> {
  4750. TestEventListenerBase( ReporterConfig const& _config );
  4751. static std::set<Verbosity> getSupportedVerbosities();
  4752. void assertionStarting(AssertionInfo const&) override;
  4753. bool assertionEnded(AssertionStats const&) override;
  4754. };
  4755. } // end namespace Catch
  4756. // end catch_reporter_bases.hpp
  4757. // start catch_console_colour.h
  4758. namespace Catch {
  4759. struct Colour {
  4760. enum Code {
  4761. None = 0,
  4762. White,
  4763. Red,
  4764. Green,
  4765. Blue,
  4766. Cyan,
  4767. Yellow,
  4768. Grey,
  4769. Bright = 0x10,
  4770. BrightRed = Bright | Red,
  4771. BrightGreen = Bright | Green,
  4772. LightGrey = Bright | Grey,
  4773. BrightWhite = Bright | White,
  4774. BrightYellow = Bright | Yellow,
  4775. // By intention
  4776. FileName = LightGrey,
  4777. Warning = BrightYellow,
  4778. ResultError = BrightRed,
  4779. ResultSuccess = BrightGreen,
  4780. ResultExpectedFailure = Warning,
  4781. Error = BrightRed,
  4782. Success = Green,
  4783. OriginalExpression = Cyan,
  4784. ReconstructedExpression = BrightYellow,
  4785. SecondaryText = LightGrey,
  4786. Headers = White
  4787. };
  4788. // Use constructed object for RAII guard
  4789. Colour( Code _colourCode );
  4790. Colour( Colour&& other ) noexcept;
  4791. Colour& operator=( Colour&& other ) noexcept;
  4792. ~Colour();
  4793. // Use static method for one-shot changes
  4794. static void use( Code _colourCode );
  4795. private:
  4796. bool m_moved = false;
  4797. };
  4798. std::ostream& operator << ( std::ostream& os, Colour const& );
  4799. } // end namespace Catch
  4800. // end catch_console_colour.h
  4801. // start catch_reporter_registrars.hpp
  4802. namespace Catch {
  4803. template<typename T>
  4804. class ReporterRegistrar {
  4805. class ReporterFactory : public IReporterFactory {
  4806. IStreamingReporterPtr create( ReporterConfig const& config ) const override {
  4807. return std::unique_ptr<T>( new T( config ) );
  4808. }
  4809. std::string getDescription() const override {
  4810. return T::getDescription();
  4811. }
  4812. };
  4813. public:
  4814. explicit ReporterRegistrar( std::string const& name ) {
  4815. getMutableRegistryHub().registerReporter( name, std::make_shared<ReporterFactory>() );
  4816. }
  4817. };
  4818. template<typename T>
  4819. class ListenerRegistrar {
  4820. class ListenerFactory : public IReporterFactory {
  4821. IStreamingReporterPtr create( ReporterConfig const& config ) const override {
  4822. return std::unique_ptr<T>( new T( config ) );
  4823. }
  4824. std::string getDescription() const override {
  4825. return std::string();
  4826. }
  4827. };
  4828. public:
  4829. ListenerRegistrar() {
  4830. getMutableRegistryHub().registerListener( std::make_shared<ListenerFactory>() );
  4831. }
  4832. };
  4833. }
  4834. #if !defined(CATCH_CONFIG_DISABLE)
  4835. #define CATCH_REGISTER_REPORTER( name, reporterType ) \
  4836. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  4837. namespace{ Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); } \
  4838. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  4839. #define CATCH_REGISTER_LISTENER( listenerType ) \
  4840. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  4841. namespace{ Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; } \
  4842. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  4843. #else // CATCH_CONFIG_DISABLE
  4844. #define CATCH_REGISTER_REPORTER(name, reporterType)
  4845. #define CATCH_REGISTER_LISTENER(listenerType)
  4846. #endif // CATCH_CONFIG_DISABLE
  4847. // end catch_reporter_registrars.hpp
  4848. // Allow users to base their work off existing reporters
  4849. // start catch_reporter_compact.h
  4850. namespace Catch {
  4851. struct CompactReporter : StreamingReporterBase<CompactReporter> {
  4852. using StreamingReporterBase::StreamingReporterBase;
  4853. ~CompactReporter() override;
  4854. static std::string getDescription();
  4855. ReporterPreferences getPreferences() const override;
  4856. void noMatchingTestCases(std::string const& spec) override;
  4857. void assertionStarting(AssertionInfo const&) override;
  4858. bool assertionEnded(AssertionStats const& _assertionStats) override;
  4859. void sectionEnded(SectionStats const& _sectionStats) override;
  4860. void testRunEnded(TestRunStats const& _testRunStats) override;
  4861. };
  4862. } // end namespace Catch
  4863. // end catch_reporter_compact.h
  4864. // start catch_reporter_console.h
  4865. #if defined(_MSC_VER)
  4866. #pragma warning(push)
  4867. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  4868. // Note that 4062 (not all labels are handled
  4869. // and default is missing) is enabled
  4870. #endif
  4871. namespace Catch {
  4872. // Fwd decls
  4873. struct SummaryColumn;
  4874. class TablePrinter;
  4875. struct ConsoleReporter : StreamingReporterBase<ConsoleReporter> {
  4876. std::unique_ptr<TablePrinter> m_tablePrinter;
  4877. ConsoleReporter(ReporterConfig const& config);
  4878. ~ConsoleReporter() override;
  4879. static std::string getDescription();
  4880. void noMatchingTestCases(std::string const& spec) override;
  4881. void assertionStarting(AssertionInfo const&) override;
  4882. bool assertionEnded(AssertionStats const& _assertionStats) override;
  4883. void sectionStarting(SectionInfo const& _sectionInfo) override;
  4884. void sectionEnded(SectionStats const& _sectionStats) override;
  4885. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  4886. void benchmarkPreparing(std::string const& name) override;
  4887. void benchmarkStarting(BenchmarkInfo const& info) override;
  4888. void benchmarkEnded(BenchmarkStats<> const& stats) override;
  4889. void benchmarkFailed(std::string const& error) override;
  4890. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  4891. void testCaseEnded(TestCaseStats const& _testCaseStats) override;
  4892. void testGroupEnded(TestGroupStats const& _testGroupStats) override;
  4893. void testRunEnded(TestRunStats const& _testRunStats) override;
  4894. void testRunStarting(TestRunInfo const& _testRunInfo) override;
  4895. private:
  4896. void lazyPrint();
  4897. void lazyPrintWithoutClosingBenchmarkTable();
  4898. void lazyPrintRunInfo();
  4899. void lazyPrintGroupInfo();
  4900. void printTestCaseAndSectionHeader();
  4901. void printClosedHeader(std::string const& _name);
  4902. void printOpenHeader(std::string const& _name);
  4903. // if string has a : in first line will set indent to follow it on
  4904. // subsequent lines
  4905. void printHeaderString(std::string const& _string, std::size_t indent = 0);
  4906. void printTotals(Totals const& totals);
  4907. void printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row);
  4908. void printTotalsDivider(Totals const& totals);
  4909. void printSummaryDivider();
  4910. void printTestFilters();
  4911. private:
  4912. bool m_headerPrinted = false;
  4913. };
  4914. } // end namespace Catch
  4915. #if defined(_MSC_VER)
  4916. #pragma warning(pop)
  4917. #endif
  4918. // end catch_reporter_console.h
  4919. // start catch_reporter_junit.h
  4920. // start catch_xmlwriter.h
  4921. #include <vector>
  4922. namespace Catch {
  4923. class XmlEncode {
  4924. public:
  4925. enum ForWhat { ForTextNodes, ForAttributes };
  4926. XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes );
  4927. void encodeTo( std::ostream& os ) const;
  4928. friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode );
  4929. private:
  4930. std::string m_str;
  4931. ForWhat m_forWhat;
  4932. };
  4933. class XmlWriter {
  4934. public:
  4935. class ScopedElement {
  4936. public:
  4937. ScopedElement( XmlWriter* writer );
  4938. ScopedElement( ScopedElement&& other ) noexcept;
  4939. ScopedElement& operator=( ScopedElement&& other ) noexcept;
  4940. ~ScopedElement();
  4941. ScopedElement& writeText( std::string const& text, bool indent = true );
  4942. template<typename T>
  4943. ScopedElement& writeAttribute( std::string const& name, T const& attribute ) {
  4944. m_writer->writeAttribute( name, attribute );
  4945. return *this;
  4946. }
  4947. private:
  4948. mutable XmlWriter* m_writer = nullptr;
  4949. };
  4950. XmlWriter( std::ostream& os = Catch::cout() );
  4951. ~XmlWriter();
  4952. XmlWriter( XmlWriter const& ) = delete;
  4953. XmlWriter& operator=( XmlWriter const& ) = delete;
  4954. XmlWriter& startElement( std::string const& name );
  4955. ScopedElement scopedElement( std::string const& name );
  4956. XmlWriter& endElement();
  4957. XmlWriter& writeAttribute( std::string const& name, std::string const& attribute );
  4958. XmlWriter& writeAttribute( std::string const& name, bool attribute );
  4959. template<typename T>
  4960. XmlWriter& writeAttribute( std::string const& name, T const& attribute ) {
  4961. ReusableStringStream rss;
  4962. rss << attribute;
  4963. return writeAttribute( name, rss.str() );
  4964. }
  4965. XmlWriter& writeText( std::string const& text, bool indent = true );
  4966. XmlWriter& writeComment( std::string const& text );
  4967. void writeStylesheetRef( std::string const& url );
  4968. XmlWriter& writeBlankLine();
  4969. void ensureTagClosed();
  4970. private:
  4971. void writeDeclaration();
  4972. void newlineIfNecessary();
  4973. bool m_tagIsOpen = false;
  4974. bool m_needsNewline = false;
  4975. std::vector<std::string> m_tags;
  4976. std::string m_indent;
  4977. std::ostream& m_os;
  4978. };
  4979. }
  4980. // end catch_xmlwriter.h
  4981. namespace Catch {
  4982. class JunitReporter : public CumulativeReporterBase<JunitReporter> {
  4983. public:
  4984. JunitReporter(ReporterConfig const& _config);
  4985. ~JunitReporter() override;
  4986. static std::string getDescription();
  4987. void noMatchingTestCases(std::string const& /*spec*/) override;
  4988. void testRunStarting(TestRunInfo const& runInfo) override;
  4989. void testGroupStarting(GroupInfo const& groupInfo) override;
  4990. void testCaseStarting(TestCaseInfo const& testCaseInfo) override;
  4991. bool assertionEnded(AssertionStats const& assertionStats) override;
  4992. void testCaseEnded(TestCaseStats const& testCaseStats) override;
  4993. void testGroupEnded(TestGroupStats const& testGroupStats) override;
  4994. void testRunEndedCumulative() override;
  4995. void writeGroup(TestGroupNode const& groupNode, double suiteTime);
  4996. void writeTestCase(TestCaseNode const& testCaseNode);
  4997. void writeSection(std::string const& className,
  4998. std::string const& rootName,
  4999. SectionNode const& sectionNode);
  5000. void writeAssertions(SectionNode const& sectionNode);
  5001. void writeAssertion(AssertionStats const& stats);
  5002. XmlWriter xml;
  5003. Timer suiteTimer;
  5004. std::string stdOutForSuite;
  5005. std::string stdErrForSuite;
  5006. unsigned int unexpectedExceptions = 0;
  5007. bool m_okToFail = false;
  5008. };
  5009. } // end namespace Catch
  5010. // end catch_reporter_junit.h
  5011. // start catch_reporter_xml.h
  5012. namespace Catch {
  5013. class XmlReporter : public StreamingReporterBase<XmlReporter> {
  5014. public:
  5015. XmlReporter(ReporterConfig const& _config);
  5016. ~XmlReporter() override;
  5017. static std::string getDescription();
  5018. virtual std::string getStylesheetRef() const;
  5019. void writeSourceInfo(SourceLineInfo const& sourceInfo);
  5020. public: // StreamingReporterBase
  5021. void noMatchingTestCases(std::string const& s) override;
  5022. void testRunStarting(TestRunInfo const& testInfo) override;
  5023. void testGroupStarting(GroupInfo const& groupInfo) override;
  5024. void testCaseStarting(TestCaseInfo const& testInfo) override;
  5025. void sectionStarting(SectionInfo const& sectionInfo) override;
  5026. void assertionStarting(AssertionInfo const&) override;
  5027. bool assertionEnded(AssertionStats const& assertionStats) override;
  5028. void sectionEnded(SectionStats const& sectionStats) override;
  5029. void testCaseEnded(TestCaseStats const& testCaseStats) override;
  5030. void testGroupEnded(TestGroupStats const& testGroupStats) override;
  5031. void testRunEnded(TestRunStats const& testRunStats) override;
  5032. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  5033. void benchmarkPreparing(std::string const& name) override;
  5034. void benchmarkStarting(BenchmarkInfo const&) override;
  5035. void benchmarkEnded(BenchmarkStats<> const&) override;
  5036. void benchmarkFailed(std::string const&) override;
  5037. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  5038. private:
  5039. Timer m_testCaseTimer;
  5040. XmlWriter m_xml;
  5041. int m_sectionDepth = 0;
  5042. };
  5043. } // end namespace Catch
  5044. // end catch_reporter_xml.h
  5045. // end catch_external_interfaces.h
  5046. #endif
  5047. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  5048. // start catch_benchmark.hpp
  5049. // Benchmark
  5050. // start catch_chronometer.hpp
  5051. // User-facing chronometer
  5052. // start catch_clock.hpp
  5053. // Clocks
  5054. #include <chrono>
  5055. #include <ratio>
  5056. namespace Catch {
  5057. namespace Benchmark {
  5058. template <typename Clock>
  5059. using ClockDuration = typename Clock::duration;
  5060. template <typename Clock>
  5061. using FloatDuration = std::chrono::duration<double, typename Clock::period>;
  5062. template <typename Clock>
  5063. using TimePoint = typename Clock::time_point;
  5064. using default_clock = std::chrono::steady_clock;
  5065. template <typename Clock>
  5066. struct now {
  5067. TimePoint<Clock> operator()() const {
  5068. return Clock::now();
  5069. }
  5070. };
  5071. using fp_seconds = std::chrono::duration<double, std::ratio<1>>;
  5072. } // namespace Benchmark
  5073. } // namespace Catch
  5074. // end catch_clock.hpp
  5075. // start catch_optimizer.hpp
  5076. // Hinting the optimizer
  5077. #if defined(_MSC_VER)
  5078. # include <atomic> // atomic_thread_fence
  5079. #endif
  5080. namespace Catch {
  5081. namespace Benchmark {
  5082. #if defined(__GNUC__) || defined(__clang__)
  5083. template <typename T>
  5084. inline void keep_memory(T* p) {
  5085. asm volatile("" : : "g"(p) : "memory");
  5086. }
  5087. inline void keep_memory() {
  5088. asm volatile("" : : : "memory");
  5089. }
  5090. namespace Detail {
  5091. inline void optimizer_barrier() { keep_memory(); }
  5092. } // namespace Detail
  5093. #elif defined(_MSC_VER)
  5094. #pragma optimize("", off)
  5095. template <typename T>
  5096. inline void keep_memory(T* p) {
  5097. // thanks @milleniumbug
  5098. *reinterpret_cast<char volatile*>(p) = *reinterpret_cast<char const volatile*>(p);
  5099. }
  5100. // TODO equivalent keep_memory()
  5101. #pragma optimize("", on)
  5102. namespace Detail {
  5103. inline void optimizer_barrier() {
  5104. std::atomic_thread_fence(std::memory_order_seq_cst);
  5105. }
  5106. } // namespace Detail
  5107. #endif
  5108. template <typename T>
  5109. inline void deoptimize_value(T&& x) {
  5110. keep_memory(&x);
  5111. }
  5112. template <typename Fn, typename... Args>
  5113. inline auto invoke_deoptimized(Fn&& fn, Args&&... args) -> typename std::enable_if<!std::is_same<void, decltype(fn(args...))>::value>::type {
  5114. deoptimize_value(std::forward<Fn>(fn) (std::forward<Args...>(args...)));
  5115. }
  5116. template <typename Fn, typename... Args>
  5117. inline auto invoke_deoptimized(Fn&& fn, Args&&... args) -> typename std::enable_if<std::is_same<void, decltype(fn(args...))>::value>::type {
  5118. std::forward<Fn>(fn) (std::forward<Args...>(args...));
  5119. }
  5120. } // namespace Benchmark
  5121. } // namespace Catch
  5122. // end catch_optimizer.hpp
  5123. // start catch_complete_invoke.hpp
  5124. // Invoke with a special case for void
  5125. #include <type_traits>
  5126. #include <utility>
  5127. namespace Catch {
  5128. namespace Benchmark {
  5129. namespace Detail {
  5130. template <typename T>
  5131. struct CompleteType { using type = T; };
  5132. template <>
  5133. struct CompleteType<void> { struct type {}; };
  5134. template <typename T>
  5135. using CompleteType_t = typename CompleteType<T>::type;
  5136. template <typename Result>
  5137. struct CompleteInvoker {
  5138. template <typename Fun, typename... Args>
  5139. static Result invoke(Fun&& fun, Args&&... args) {
  5140. return std::forward<Fun>(fun)(std::forward<Args>(args)...);
  5141. }
  5142. };
  5143. template <>
  5144. struct CompleteInvoker<void> {
  5145. template <typename Fun, typename... Args>
  5146. static CompleteType_t<void> invoke(Fun&& fun, Args&&... args) {
  5147. std::forward<Fun>(fun)(std::forward<Args>(args)...);
  5148. return {};
  5149. }
  5150. };
  5151. template <typename Sig>
  5152. using ResultOf_t = typename std::result_of<Sig>::type;
  5153. // invoke and not return void :(
  5154. template <typename Fun, typename... Args>
  5155. CompleteType_t<ResultOf_t<Fun(Args...)>> complete_invoke(Fun&& fun, Args&&... args) {
  5156. return CompleteInvoker<ResultOf_t<Fun(Args...)>>::invoke(std::forward<Fun>(fun), std::forward<Args>(args)...);
  5157. }
  5158. const std::string benchmarkErrorMsg = "a benchmark failed to run successfully";
  5159. } // namespace Detail
  5160. template <typename Fun>
  5161. Detail::CompleteType_t<Detail::ResultOf_t<Fun()>> user_code(Fun&& fun) {
  5162. CATCH_TRY{
  5163. return Detail::complete_invoke(std::forward<Fun>(fun));
  5164. } CATCH_CATCH_ALL{
  5165. getResultCapture().benchmarkFailed(translateActiveException());
  5166. CATCH_RUNTIME_ERROR(Detail::benchmarkErrorMsg);
  5167. }
  5168. }
  5169. } // namespace Benchmark
  5170. } // namespace Catch
  5171. // end catch_complete_invoke.hpp
  5172. namespace Catch {
  5173. namespace Benchmark {
  5174. namespace Detail {
  5175. struct ChronometerConcept {
  5176. virtual void start() = 0;
  5177. virtual void finish() = 0;
  5178. virtual ~ChronometerConcept() = default;
  5179. };
  5180. template <typename Clock>
  5181. struct ChronometerModel final : public ChronometerConcept {
  5182. void start() override { started = Clock::now(); }
  5183. void finish() override { finished = Clock::now(); }
  5184. ClockDuration<Clock> elapsed() const { return finished - started; }
  5185. TimePoint<Clock> started;
  5186. TimePoint<Clock> finished;
  5187. };
  5188. } // namespace Detail
  5189. struct Chronometer {
  5190. public:
  5191. template <typename Fun>
  5192. void measure(Fun&& fun) { measure(std::forward<Fun>(fun), is_callable<Fun(int)>()); }
  5193. int runs() const { return k; }
  5194. Chronometer(Detail::ChronometerConcept& meter, int k)
  5195. : impl(&meter)
  5196. , k(k) {}
  5197. private:
  5198. template <typename Fun>
  5199. void measure(Fun&& fun, std::false_type) {
  5200. measure([&fun](int) { return fun(); }, std::true_type());
  5201. }
  5202. template <typename Fun>
  5203. void measure(Fun&& fun, std::true_type) {
  5204. Detail::optimizer_barrier();
  5205. impl->start();
  5206. for (int i = 0; i < k; ++i) invoke_deoptimized(fun, i);
  5207. impl->finish();
  5208. Detail::optimizer_barrier();
  5209. }
  5210. Detail::ChronometerConcept* impl;
  5211. int k;
  5212. };
  5213. } // namespace Benchmark
  5214. } // namespace Catch
  5215. // end catch_chronometer.hpp
  5216. // start catch_environment.hpp
  5217. // Environment information
  5218. namespace Catch {
  5219. namespace Benchmark {
  5220. template <typename Duration>
  5221. struct EnvironmentEstimate {
  5222. Duration mean;
  5223. OutlierClassification outliers;
  5224. template <typename Duration2>
  5225. operator EnvironmentEstimate<Duration2>() const {
  5226. return { mean, outliers };
  5227. }
  5228. };
  5229. template <typename Clock>
  5230. struct Environment {
  5231. using clock_type = Clock;
  5232. EnvironmentEstimate<FloatDuration<Clock>> clock_resolution;
  5233. EnvironmentEstimate<FloatDuration<Clock>> clock_cost;
  5234. };
  5235. } // namespace Benchmark
  5236. } // namespace Catch
  5237. // end catch_environment.hpp
  5238. // start catch_execution_plan.hpp
  5239. // Execution plan
  5240. // start catch_benchmark_function.hpp
  5241. // Dumb std::function implementation for consistent call overhead
  5242. #include <cassert>
  5243. #include <type_traits>
  5244. #include <utility>
  5245. #include <memory>
  5246. namespace Catch {
  5247. namespace Benchmark {
  5248. namespace Detail {
  5249. template <typename T>
  5250. using Decay = typename std::decay<T>::type;
  5251. template <typename T, typename U>
  5252. struct is_related
  5253. : std::is_same<Decay<T>, Decay<U>> {};
  5254. /// We need to reinvent std::function because every piece of code that might add overhead
  5255. /// in a measurement context needs to have consistent performance characteristics so that we
  5256. /// can account for it in the measurement.
  5257. /// Implementations of std::function with optimizations that aren't always applicable, like
  5258. /// small buffer optimizations, are not uncommon.
  5259. /// This is effectively an implementation of std::function without any such optimizations;
  5260. /// it may be slow, but it is consistently slow.
  5261. struct BenchmarkFunction {
  5262. private:
  5263. struct callable {
  5264. virtual void call(Chronometer meter) const = 0;
  5265. virtual callable* clone() const = 0;
  5266. virtual ~callable() = default;
  5267. };
  5268. template <typename Fun>
  5269. struct model : public callable {
  5270. model(Fun&& fun) : fun(std::move(fun)) {}
  5271. model(Fun const& fun) : fun(fun) {}
  5272. model<Fun>* clone() const override { return new model<Fun>(*this); }
  5273. void call(Chronometer meter) const override {
  5274. call(meter, is_callable<Fun(Chronometer)>());
  5275. }
  5276. void call(Chronometer meter, std::true_type) const {
  5277. fun(meter);
  5278. }
  5279. void call(Chronometer meter, std::false_type) const {
  5280. meter.measure(fun);
  5281. }
  5282. Fun fun;
  5283. };
  5284. struct do_nothing { void operator()() const {} };
  5285. template <typename T>
  5286. BenchmarkFunction(model<T>* c) : f(c) {}
  5287. public:
  5288. BenchmarkFunction()
  5289. : f(new model<do_nothing>{ {} }) {}
  5290. template <typename Fun,
  5291. typename std::enable_if<!is_related<Fun, BenchmarkFunction>::value, int>::type = 0>
  5292. BenchmarkFunction(Fun&& fun)
  5293. : f(new model<typename std::decay<Fun>::type>(std::forward<Fun>(fun))) {}
  5294. BenchmarkFunction(BenchmarkFunction&& that)
  5295. : f(std::move(that.f)) {}
  5296. BenchmarkFunction(BenchmarkFunction const& that)
  5297. : f(that.f->clone()) {}
  5298. BenchmarkFunction& operator=(BenchmarkFunction&& that) {
  5299. f = std::move(that.f);
  5300. return *this;
  5301. }
  5302. BenchmarkFunction& operator=(BenchmarkFunction const& that) {
  5303. f.reset(that.f->clone());
  5304. return *this;
  5305. }
  5306. void operator()(Chronometer meter) const { f->call(meter); }
  5307. private:
  5308. std::unique_ptr<callable> f;
  5309. };
  5310. } // namespace Detail
  5311. } // namespace Benchmark
  5312. } // namespace Catch
  5313. // end catch_benchmark_function.hpp
  5314. // start catch_repeat.hpp
  5315. // repeat algorithm
  5316. #include <type_traits>
  5317. #include <utility>
  5318. namespace Catch {
  5319. namespace Benchmark {
  5320. namespace Detail {
  5321. template <typename Fun>
  5322. struct repeater {
  5323. void operator()(int k) const {
  5324. for (int i = 0; i < k; ++i) {
  5325. fun();
  5326. }
  5327. }
  5328. Fun fun;
  5329. };
  5330. template <typename Fun>
  5331. repeater<typename std::decay<Fun>::type> repeat(Fun&& fun) {
  5332. return { std::forward<Fun>(fun) };
  5333. }
  5334. } // namespace Detail
  5335. } // namespace Benchmark
  5336. } // namespace Catch
  5337. // end catch_repeat.hpp
  5338. // start catch_run_for_at_least.hpp
  5339. // Run a function for a minimum amount of time
  5340. // start catch_measure.hpp
  5341. // Measure
  5342. // start catch_timing.hpp
  5343. // Timing
  5344. #include <tuple>
  5345. #include <type_traits>
  5346. namespace Catch {
  5347. namespace Benchmark {
  5348. template <typename Duration, typename Result>
  5349. struct Timing {
  5350. Duration elapsed;
  5351. Result result;
  5352. int iterations;
  5353. };
  5354. template <typename Clock, typename Sig>
  5355. using TimingOf = Timing<ClockDuration<Clock>, Detail::CompleteType_t<Detail::ResultOf_t<Sig>>>;
  5356. } // namespace Benchmark
  5357. } // namespace Catch
  5358. // end catch_timing.hpp
  5359. #include <utility>
  5360. namespace Catch {
  5361. namespace Benchmark {
  5362. namespace Detail {
  5363. template <typename Clock, typename Fun, typename... Args>
  5364. TimingOf<Clock, Fun(Args...)> measure(Fun&& fun, Args&&... args) {
  5365. auto start = Clock::now();
  5366. auto&& r = Detail::complete_invoke(fun, std::forward<Args>(args)...);
  5367. auto end = Clock::now();
  5368. auto delta = end - start;
  5369. return { delta, std::forward<decltype(r)>(r), 1 };
  5370. }
  5371. } // namespace Detail
  5372. } // namespace Benchmark
  5373. } // namespace Catch
  5374. // end catch_measure.hpp
  5375. #include <utility>
  5376. #include <type_traits>
  5377. namespace Catch {
  5378. namespace Benchmark {
  5379. namespace Detail {
  5380. template <typename Clock, typename Fun>
  5381. TimingOf<Clock, Fun(int)> measure_one(Fun&& fun, int iters, std::false_type) {
  5382. return Detail::measure<Clock>(fun, iters);
  5383. }
  5384. template <typename Clock, typename Fun>
  5385. TimingOf<Clock, Fun(Chronometer)> measure_one(Fun&& fun, int iters, std::true_type) {
  5386. Detail::ChronometerModel<Clock> meter;
  5387. auto&& result = Detail::complete_invoke(fun, Chronometer(meter, iters));
  5388. return { meter.elapsed(), std::move(result), iters };
  5389. }
  5390. template <typename Clock, typename Fun>
  5391. using run_for_at_least_argument_t = typename std::conditional<is_callable<Fun(Chronometer)>::value, Chronometer, int>::type;
  5392. struct optimized_away_error : std::exception {
  5393. const char* what() const noexcept override {
  5394. return "could not measure benchmark, maybe it was optimized away";
  5395. }
  5396. };
  5397. template <typename Clock, typename Fun>
  5398. TimingOf<Clock, Fun(run_for_at_least_argument_t<Clock, Fun>)> run_for_at_least(ClockDuration<Clock> how_long, int seed, Fun&& fun) {
  5399. auto iters = seed;
  5400. while (iters < (1 << 30)) {
  5401. auto&& Timing = measure_one<Clock>(fun, iters, is_callable<Fun(Chronometer)>());
  5402. if (Timing.elapsed >= how_long) {
  5403. return { Timing.elapsed, std::move(Timing.result), iters };
  5404. }
  5405. iters *= 2;
  5406. }
  5407. throw optimized_away_error{};
  5408. }
  5409. } // namespace Detail
  5410. } // namespace Benchmark
  5411. } // namespace Catch
  5412. // end catch_run_for_at_least.hpp
  5413. #include <algorithm>
  5414. namespace Catch {
  5415. namespace Benchmark {
  5416. template <typename Duration>
  5417. struct ExecutionPlan {
  5418. int iterations_per_sample;
  5419. Duration estimated_duration;
  5420. Detail::BenchmarkFunction benchmark;
  5421. Duration warmup_time;
  5422. int warmup_iterations;
  5423. template <typename Duration2>
  5424. operator ExecutionPlan<Duration2>() const {
  5425. return { iterations_per_sample, estimated_duration, benchmark, warmup_time, warmup_iterations };
  5426. }
  5427. template <typename Clock>
  5428. std::vector<FloatDuration<Clock>> run(const IConfig &cfg, Environment<FloatDuration<Clock>> env) const {
  5429. // warmup a bit
  5430. Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_iterations, Detail::repeat(now<Clock>{}));
  5431. std::vector<FloatDuration<Clock>> times;
  5432. times.reserve(cfg.benchmarkSamples());
  5433. std::generate_n(std::back_inserter(times), cfg.benchmarkSamples(), [this, env] {
  5434. Detail::ChronometerModel<Clock> model;
  5435. this->benchmark(Chronometer(model, iterations_per_sample));
  5436. auto sample_time = model.elapsed() - env.clock_cost.mean;
  5437. if (sample_time < FloatDuration<Clock>::zero()) sample_time = FloatDuration<Clock>::zero();
  5438. return sample_time / iterations_per_sample;
  5439. });
  5440. return times;
  5441. }
  5442. };
  5443. } // namespace Benchmark
  5444. } // namespace Catch
  5445. // end catch_execution_plan.hpp
  5446. // start catch_estimate_clock.hpp
  5447. // Environment measurement
  5448. // start catch_stats.hpp
  5449. // Statistical analysis tools
  5450. #include <algorithm>
  5451. #include <functional>
  5452. #include <vector>
  5453. #include <numeric>
  5454. #include <tuple>
  5455. #include <cmath>
  5456. #include <utility>
  5457. #include <cstddef>
  5458. namespace Catch {
  5459. namespace Benchmark {
  5460. namespace Detail {
  5461. using sample = std::vector<double>;
  5462. double weighted_average_quantile(int k, int q, std::vector<double>::iterator first, std::vector<double>::iterator last);
  5463. template <typename Iterator>
  5464. OutlierClassification classify_outliers(Iterator first, Iterator last) {
  5465. std::vector<double> copy(first, last);
  5466. auto q1 = weighted_average_quantile(1, 4, copy.begin(), copy.end());
  5467. auto q3 = weighted_average_quantile(3, 4, copy.begin(), copy.end());
  5468. auto iqr = q3 - q1;
  5469. auto los = q1 - (iqr * 3.);
  5470. auto lom = q1 - (iqr * 1.5);
  5471. auto him = q3 + (iqr * 1.5);
  5472. auto his = q3 + (iqr * 3.);
  5473. OutlierClassification o;
  5474. for (; first != last; ++first) {
  5475. auto&& t = *first;
  5476. if (t < los) ++o.low_severe;
  5477. else if (t < lom) ++o.low_mild;
  5478. else if (t > his) ++o.high_severe;
  5479. else if (t > him) ++o.high_mild;
  5480. ++o.samples_seen;
  5481. }
  5482. return o;
  5483. }
  5484. template <typename Iterator>
  5485. double mean(Iterator first, Iterator last) {
  5486. auto count = last - first;
  5487. double sum = std::accumulate(first, last, 0.);
  5488. return sum / count;
  5489. }
  5490. template <typename URng, typename Iterator, typename Estimator>
  5491. sample resample(URng& rng, int resamples, Iterator first, Iterator last, Estimator& estimator) {
  5492. auto n = last - first;
  5493. std::uniform_int_distribution<decltype(n)> dist(0, n - 1);
  5494. sample out;
  5495. out.reserve(resamples);
  5496. std::generate_n(std::back_inserter(out), resamples, [n, first, &estimator, &dist, &rng] {
  5497. std::vector<double> resampled;
  5498. resampled.reserve(n);
  5499. std::generate_n(std::back_inserter(resampled), n, [first, &dist, &rng] { return first[dist(rng)]; });
  5500. return estimator(resampled.begin(), resampled.end());
  5501. });
  5502. std::sort(out.begin(), out.end());
  5503. return out;
  5504. }
  5505. template <typename Estimator, typename Iterator>
  5506. sample jackknife(Estimator&& estimator, Iterator first, Iterator last) {
  5507. auto n = last - first;
  5508. auto second = std::next(first);
  5509. sample results;
  5510. results.reserve(n);
  5511. for (auto it = first; it != last; ++it) {
  5512. std::iter_swap(it, first);
  5513. results.push_back(estimator(second, last));
  5514. }
  5515. return results;
  5516. }
  5517. inline double normal_cdf(double x) {
  5518. return std::erfc(-x / std::sqrt(2.0)) / 2.0;
  5519. }
  5520. double erfc_inv(double x);
  5521. double normal_quantile(double p);
  5522. template <typename Iterator, typename Estimator>
  5523. Estimate<double> bootstrap(double confidence_level, Iterator first, Iterator last, sample const& resample, Estimator&& estimator) {
  5524. auto n_samples = last - first;
  5525. double point = estimator(first, last);
  5526. // Degenerate case with a single sample
  5527. if (n_samples == 1) return { point, point, point, confidence_level };
  5528. sample jack = jackknife(estimator, first, last);
  5529. double jack_mean = mean(jack.begin(), jack.end());
  5530. double sum_squares, sum_cubes;
  5531. 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> {
  5532. auto d = jack_mean - x;
  5533. auto d2 = d * d;
  5534. auto d3 = d2 * d;
  5535. return { sqcb.first + d2, sqcb.second + d3 };
  5536. });
  5537. double accel = sum_cubes / (6 * std::pow(sum_squares, 1.5));
  5538. int n = static_cast<int>(resample.size());
  5539. double prob_n = std::count_if(resample.begin(), resample.end(), [point](double x) { return x < point; }) / (double)n;
  5540. // degenerate case with uniform samples
  5541. if (prob_n == 0) return { point, point, point, confidence_level };
  5542. double bias = normal_quantile(prob_n);
  5543. double z1 = normal_quantile((1. - confidence_level) / 2.);
  5544. auto cumn = [n](double x) -> int {
  5545. return std::lround(normal_cdf(x) * n); };
  5546. auto a = [bias, accel](double b) { return bias + b / (1. - accel * b); };
  5547. double b1 = bias + z1;
  5548. double b2 = bias - z1;
  5549. double a1 = a(b1);
  5550. double a2 = a(b2);
  5551. auto lo = std::max(cumn(a1), 0);
  5552. auto hi = std::min(cumn(a2), n - 1);
  5553. return { point, resample[lo], resample[hi], confidence_level };
  5554. }
  5555. double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n);
  5556. struct bootstrap_analysis {
  5557. Estimate<double> mean;
  5558. Estimate<double> standard_deviation;
  5559. double outlier_variance;
  5560. };
  5561. bootstrap_analysis analyse_samples(double confidence_level, int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last);
  5562. } // namespace Detail
  5563. } // namespace Benchmark
  5564. } // namespace Catch
  5565. // end catch_stats.hpp
  5566. #include <algorithm>
  5567. #include <iterator>
  5568. #include <tuple>
  5569. #include <vector>
  5570. #include <cmath>
  5571. namespace Catch {
  5572. namespace Benchmark {
  5573. namespace Detail {
  5574. template <typename Clock>
  5575. std::vector<double> resolution(int k) {
  5576. std::vector<TimePoint<Clock>> times;
  5577. times.reserve(k + 1);
  5578. std::generate_n(std::back_inserter(times), k + 1, now<Clock>{});
  5579. std::vector<double> deltas;
  5580. deltas.reserve(k);
  5581. std::transform(std::next(times.begin()), times.end(), times.begin(),
  5582. std::back_inserter(deltas),
  5583. [](TimePoint<Clock> a, TimePoint<Clock> b) { return static_cast<double>((a - b).count()); });
  5584. return deltas;
  5585. }
  5586. const auto warmup_iterations = 10000;
  5587. const auto warmup_time = std::chrono::milliseconds(100);
  5588. const auto minimum_ticks = 1000;
  5589. const auto warmup_seed = 10000;
  5590. const auto clock_resolution_estimation_time = std::chrono::milliseconds(500);
  5591. const auto clock_cost_estimation_time_limit = std::chrono::seconds(1);
  5592. const auto clock_cost_estimation_tick_limit = 100000;
  5593. const auto clock_cost_estimation_time = std::chrono::milliseconds(10);
  5594. const auto clock_cost_estimation_iterations = 10000;
  5595. template <typename Clock>
  5596. int warmup() {
  5597. return run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_seed, &resolution<Clock>)
  5598. .iterations;
  5599. }
  5600. template <typename Clock>
  5601. EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_resolution(int iterations) {
  5602. auto r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_resolution_estimation_time), iterations, &resolution<Clock>)
  5603. .result;
  5604. return {
  5605. FloatDuration<Clock>(mean(r.begin(), r.end())),
  5606. classify_outliers(r.begin(), r.end()),
  5607. };
  5608. }
  5609. template <typename Clock>
  5610. EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_cost(FloatDuration<Clock> resolution) {
  5611. auto time_limit = std::min(resolution * clock_cost_estimation_tick_limit, FloatDuration<Clock>(clock_cost_estimation_time_limit));
  5612. auto time_clock = [](int k) {
  5613. return Detail::measure<Clock>([k] {
  5614. for (int i = 0; i < k; ++i) {
  5615. volatile auto ignored = Clock::now();
  5616. (void)ignored;
  5617. }
  5618. }).elapsed;
  5619. };
  5620. time_clock(1);
  5621. int iters = clock_cost_estimation_iterations;
  5622. auto&& r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_cost_estimation_time), iters, time_clock);
  5623. std::vector<double> times;
  5624. int nsamples = static_cast<int>(std::ceil(time_limit / r.elapsed));
  5625. times.reserve(nsamples);
  5626. std::generate_n(std::back_inserter(times), nsamples, [time_clock, &r] {
  5627. return static_cast<double>((time_clock(r.iterations) / r.iterations).count());
  5628. });
  5629. return {
  5630. FloatDuration<Clock>(mean(times.begin(), times.end())),
  5631. classify_outliers(times.begin(), times.end()),
  5632. };
  5633. }
  5634. template <typename Clock>
  5635. Environment<FloatDuration<Clock>> measure_environment() {
  5636. static Environment<FloatDuration<Clock>>* env = nullptr;
  5637. if (env) {
  5638. return *env;
  5639. }
  5640. auto iters = Detail::warmup<Clock>();
  5641. auto resolution = Detail::estimate_clock_resolution<Clock>(iters);
  5642. auto cost = Detail::estimate_clock_cost<Clock>(resolution.mean);
  5643. env = new Environment<FloatDuration<Clock>>{ resolution, cost };
  5644. return *env;
  5645. }
  5646. } // namespace Detail
  5647. } // namespace Benchmark
  5648. } // namespace Catch
  5649. // end catch_estimate_clock.hpp
  5650. // start catch_analyse.hpp
  5651. // Run and analyse one benchmark
  5652. // start catch_sample_analysis.hpp
  5653. // Benchmark results
  5654. #include <algorithm>
  5655. #include <vector>
  5656. #include <string>
  5657. #include <iterator>
  5658. namespace Catch {
  5659. namespace Benchmark {
  5660. template <typename Duration>
  5661. struct SampleAnalysis {
  5662. std::vector<Duration> samples;
  5663. Estimate<Duration> mean;
  5664. Estimate<Duration> standard_deviation;
  5665. OutlierClassification outliers;
  5666. double outlier_variance;
  5667. template <typename Duration2>
  5668. operator SampleAnalysis<Duration2>() const {
  5669. std::vector<Duration2> samples2;
  5670. samples2.reserve(samples.size());
  5671. std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration d) { return Duration2(d); });
  5672. return {
  5673. std::move(samples2),
  5674. mean,
  5675. standard_deviation,
  5676. outliers,
  5677. outlier_variance,
  5678. };
  5679. }
  5680. };
  5681. } // namespace Benchmark
  5682. } // namespace Catch
  5683. // end catch_sample_analysis.hpp
  5684. #include <algorithm>
  5685. #include <iterator>
  5686. #include <vector>
  5687. namespace Catch {
  5688. namespace Benchmark {
  5689. namespace Detail {
  5690. template <typename Duration, typename Iterator>
  5691. SampleAnalysis<Duration> analyse(const IConfig &cfg, Environment<Duration>, Iterator first, Iterator last) {
  5692. if (!cfg.benchmarkNoAnalysis()) {
  5693. std::vector<double> samples;
  5694. samples.reserve(last - first);
  5695. std::transform(first, last, std::back_inserter(samples), [](Duration d) { return d.count(); });
  5696. auto analysis = Catch::Benchmark::Detail::analyse_samples(cfg.benchmarkConfidenceInterval(), cfg.benchmarkResamples(), samples.begin(), samples.end());
  5697. auto outliers = Catch::Benchmark::Detail::classify_outliers(samples.begin(), samples.end());
  5698. auto wrap_estimate = [](Estimate<double> e) {
  5699. return Estimate<Duration> {
  5700. Duration(e.point),
  5701. Duration(e.lower_bound),
  5702. Duration(e.upper_bound),
  5703. e.confidence_interval,
  5704. };
  5705. };
  5706. std::vector<Duration> samples2;
  5707. samples2.reserve(samples.size());
  5708. std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](double d) { return Duration(d); });
  5709. return {
  5710. std::move(samples2),
  5711. wrap_estimate(analysis.mean),
  5712. wrap_estimate(analysis.standard_deviation),
  5713. outliers,
  5714. analysis.outlier_variance,
  5715. };
  5716. } else {
  5717. std::vector<Duration> samples;
  5718. samples.reserve(last - first);
  5719. Duration mean = Duration(0);
  5720. int i = 0;
  5721. for (auto it = first; it < last; ++it, ++i) {
  5722. samples.push_back(Duration(*it));
  5723. mean += Duration(*it);
  5724. }
  5725. mean /= i;
  5726. return {
  5727. std::move(samples),
  5728. Estimate<Duration>{mean, mean, mean, 0.0},
  5729. Estimate<Duration>{Duration(0), Duration(0), Duration(0), 0.0},
  5730. OutlierClassification{},
  5731. 0.0
  5732. };
  5733. }
  5734. }
  5735. } // namespace Detail
  5736. } // namespace Benchmark
  5737. } // namespace Catch
  5738. // end catch_analyse.hpp
  5739. #include <algorithm>
  5740. #include <functional>
  5741. #include <string>
  5742. #include <vector>
  5743. #include <cmath>
  5744. namespace Catch {
  5745. namespace Benchmark {
  5746. struct Benchmark {
  5747. Benchmark(std::string &&name)
  5748. : name(std::move(name)) {}
  5749. template <class FUN>
  5750. Benchmark(std::string &&name, FUN &&func)
  5751. : fun(std::move(func)), name(std::move(name)) {}
  5752. template <typename Clock>
  5753. ExecutionPlan<FloatDuration<Clock>> prepare(const IConfig &cfg, Environment<FloatDuration<Clock>> env) const {
  5754. auto min_time = env.clock_resolution.mean * Detail::minimum_ticks;
  5755. auto run_time = std::max(min_time, std::chrono::duration_cast<decltype(min_time)>(Detail::warmup_time));
  5756. auto&& test = Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(run_time), 1, fun);
  5757. int new_iters = static_cast<int>(std::ceil(min_time * test.iterations / test.elapsed));
  5758. return { new_iters, test.elapsed / test.iterations * new_iters * cfg.benchmarkSamples(), fun, std::chrono::duration_cast<FloatDuration<Clock>>(Detail::warmup_time), Detail::warmup_iterations };
  5759. }
  5760. template <typename Clock = default_clock>
  5761. void run() {
  5762. IConfigPtr cfg = getCurrentContext().getConfig();
  5763. auto env = Detail::measure_environment<Clock>();
  5764. getResultCapture().benchmarkPreparing(name);
  5765. CATCH_TRY{
  5766. auto plan = user_code([&] {
  5767. return prepare<Clock>(*cfg, env);
  5768. });
  5769. BenchmarkInfo info {
  5770. name,
  5771. plan.estimated_duration.count(),
  5772. plan.iterations_per_sample,
  5773. cfg->benchmarkSamples(),
  5774. cfg->benchmarkResamples(),
  5775. env.clock_resolution.mean.count(),
  5776. env.clock_cost.mean.count()
  5777. };
  5778. getResultCapture().benchmarkStarting(info);
  5779. auto samples = user_code([&] {
  5780. return plan.template run<Clock>(*cfg, env);
  5781. });
  5782. auto analysis = Detail::analyse(*cfg, env, samples.begin(), samples.end());
  5783. BenchmarkStats<std::chrono::duration<double, std::nano>> stats{ info, analysis.samples, analysis.mean, analysis.standard_deviation, analysis.outliers, analysis.outlier_variance };
  5784. getResultCapture().benchmarkEnded(stats);
  5785. } CATCH_CATCH_ALL{
  5786. if (translateActiveException() != Detail::benchmarkErrorMsg) // benchmark errors have been reported, otherwise rethrow.
  5787. std::rethrow_exception(std::current_exception());
  5788. }
  5789. }
  5790. // sets lambda to be used in fun *and* executes benchmark!
  5791. template <typename Fun,
  5792. typename std::enable_if<!Detail::is_related<Fun, Benchmark>::value, int>::type = 0>
  5793. Benchmark & operator=(Fun func) {
  5794. fun = Detail::BenchmarkFunction(func);
  5795. run();
  5796. return *this;
  5797. }
  5798. explicit operator bool() {
  5799. return true;
  5800. }
  5801. private:
  5802. Detail::BenchmarkFunction fun;
  5803. std::string name;
  5804. };
  5805. }
  5806. } // namespace Catch
  5807. #define INTERNAL_CATCH_GET_1_ARG(arg1, arg2, ...) arg1
  5808. #define INTERNAL_CATCH_GET_2_ARG(arg1, arg2, ...) arg2
  5809. #define INTERNAL_CATCH_BENCHMARK(BenchmarkName, name, benchmarkIndex)\
  5810. if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \
  5811. BenchmarkName = [&](int benchmarkIndex)
  5812. #define INTERNAL_CATCH_BENCHMARK_ADVANCED(BenchmarkName, name)\
  5813. if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \
  5814. BenchmarkName = [&]
  5815. // end catch_benchmark.hpp
  5816. #endif
  5817. #endif // ! CATCH_CONFIG_IMPL_ONLY
  5818. #ifdef CATCH_IMPL
  5819. // start catch_impl.hpp
  5820. #ifdef __clang__
  5821. #pragma clang diagnostic push
  5822. #pragma clang diagnostic ignored "-Wweak-vtables"
  5823. #endif
  5824. // Keep these here for external reporters
  5825. // start catch_test_case_tracker.h
  5826. #include <string>
  5827. #include <vector>
  5828. #include <memory>
  5829. namespace Catch {
  5830. namespace TestCaseTracking {
  5831. struct NameAndLocation {
  5832. std::string name;
  5833. SourceLineInfo location;
  5834. NameAndLocation( std::string const& _name, SourceLineInfo const& _location );
  5835. };
  5836. struct ITracker;
  5837. using ITrackerPtr = std::shared_ptr<ITracker>;
  5838. struct ITracker {
  5839. virtual ~ITracker();
  5840. // static queries
  5841. virtual NameAndLocation const& nameAndLocation() const = 0;
  5842. // dynamic queries
  5843. virtual bool isComplete() const = 0; // Successfully completed or failed
  5844. virtual bool isSuccessfullyCompleted() const = 0;
  5845. virtual bool isOpen() const = 0; // Started but not complete
  5846. virtual bool hasChildren() const = 0;
  5847. virtual ITracker& parent() = 0;
  5848. // actions
  5849. virtual void close() = 0; // Successfully complete
  5850. virtual void fail() = 0;
  5851. virtual void markAsNeedingAnotherRun() = 0;
  5852. virtual void addChild( ITrackerPtr const& child ) = 0;
  5853. virtual ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) = 0;
  5854. virtual void openChild() = 0;
  5855. // Debug/ checking
  5856. virtual bool isSectionTracker() const = 0;
  5857. virtual bool isGeneratorTracker() const = 0;
  5858. };
  5859. class TrackerContext {
  5860. enum RunState {
  5861. NotStarted,
  5862. Executing,
  5863. CompletedCycle
  5864. };
  5865. ITrackerPtr m_rootTracker;
  5866. ITracker* m_currentTracker = nullptr;
  5867. RunState m_runState = NotStarted;
  5868. public:
  5869. ITracker& startRun();
  5870. void endRun();
  5871. void startCycle();
  5872. void completeCycle();
  5873. bool completedCycle() const;
  5874. ITracker& currentTracker();
  5875. void setCurrentTracker( ITracker* tracker );
  5876. };
  5877. class TrackerBase : public ITracker {
  5878. protected:
  5879. enum CycleState {
  5880. NotStarted,
  5881. Executing,
  5882. ExecutingChildren,
  5883. NeedsAnotherRun,
  5884. CompletedSuccessfully,
  5885. Failed
  5886. };
  5887. using Children = std::vector<ITrackerPtr>;
  5888. NameAndLocation m_nameAndLocation;
  5889. TrackerContext& m_ctx;
  5890. ITracker* m_parent;
  5891. Children m_children;
  5892. CycleState m_runState = NotStarted;
  5893. public:
  5894. TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  5895. NameAndLocation const& nameAndLocation() const override;
  5896. bool isComplete() const override;
  5897. bool isSuccessfullyCompleted() const override;
  5898. bool isOpen() const override;
  5899. bool hasChildren() const override;
  5900. void addChild( ITrackerPtr const& child ) override;
  5901. ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) override;
  5902. ITracker& parent() override;
  5903. void openChild() override;
  5904. bool isSectionTracker() const override;
  5905. bool isGeneratorTracker() const override;
  5906. void open();
  5907. void close() override;
  5908. void fail() override;
  5909. void markAsNeedingAnotherRun() override;
  5910. private:
  5911. void moveToParent();
  5912. void moveToThis();
  5913. };
  5914. class SectionTracker : public TrackerBase {
  5915. std::vector<std::string> m_filters;
  5916. public:
  5917. SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  5918. bool isSectionTracker() const override;
  5919. bool isComplete() const override;
  5920. static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation );
  5921. void tryOpen();
  5922. void addInitialFilters( std::vector<std::string> const& filters );
  5923. void addNextFilters( std::vector<std::string> const& filters );
  5924. };
  5925. } // namespace TestCaseTracking
  5926. using TestCaseTracking::ITracker;
  5927. using TestCaseTracking::TrackerContext;
  5928. using TestCaseTracking::SectionTracker;
  5929. } // namespace Catch
  5930. // end catch_test_case_tracker.h
  5931. // start catch_leak_detector.h
  5932. namespace Catch {
  5933. struct LeakDetector {
  5934. LeakDetector();
  5935. ~LeakDetector();
  5936. };
  5937. }
  5938. // end catch_leak_detector.h
  5939. // Cpp files will be included in the single-header file here
  5940. // start catch_stats.cpp
  5941. // Statistical analysis tools
  5942. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  5943. #include <cassert>
  5944. #include <random>
  5945. #if defined(CATCH_CONFIG_USE_ASYNC)
  5946. #include <future>
  5947. #endif
  5948. namespace {
  5949. double erf_inv(double x) {
  5950. // Code accompanying the article "Approximating the erfinv function" in GPU Computing Gems, Volume 2
  5951. double w, p;
  5952. w = -log((1.0 - x) * (1.0 + x));
  5953. if (w < 6.250000) {
  5954. w = w - 3.125000;
  5955. p = -3.6444120640178196996e-21;
  5956. p = -1.685059138182016589e-19 + p * w;
  5957. p = 1.2858480715256400167e-18 + p * w;
  5958. p = 1.115787767802518096e-17 + p * w;
  5959. p = -1.333171662854620906e-16 + p * w;
  5960. p = 2.0972767875968561637e-17 + p * w;
  5961. p = 6.6376381343583238325e-15 + p * w;
  5962. p = -4.0545662729752068639e-14 + p * w;
  5963. p = -8.1519341976054721522e-14 + p * w;
  5964. p = 2.6335093153082322977e-12 + p * w;
  5965. p = -1.2975133253453532498e-11 + p * w;
  5966. p = -5.4154120542946279317e-11 + p * w;
  5967. p = 1.051212273321532285e-09 + p * w;
  5968. p = -4.1126339803469836976e-09 + p * w;
  5969. p = -2.9070369957882005086e-08 + p * w;
  5970. p = 4.2347877827932403518e-07 + p * w;
  5971. p = -1.3654692000834678645e-06 + p * w;
  5972. p = -1.3882523362786468719e-05 + p * w;
  5973. p = 0.0001867342080340571352 + p * w;
  5974. p = -0.00074070253416626697512 + p * w;
  5975. p = -0.0060336708714301490533 + p * w;
  5976. p = 0.24015818242558961693 + p * w;
  5977. p = 1.6536545626831027356 + p * w;
  5978. } else if (w < 16.000000) {
  5979. w = sqrt(w) - 3.250000;
  5980. p = 2.2137376921775787049e-09;
  5981. p = 9.0756561938885390979e-08 + p * w;
  5982. p = -2.7517406297064545428e-07 + p * w;
  5983. p = 1.8239629214389227755e-08 + p * w;
  5984. p = 1.5027403968909827627e-06 + p * w;
  5985. p = -4.013867526981545969e-06 + p * w;
  5986. p = 2.9234449089955446044e-06 + p * w;
  5987. p = 1.2475304481671778723e-05 + p * w;
  5988. p = -4.7318229009055733981e-05 + p * w;
  5989. p = 6.8284851459573175448e-05 + p * w;
  5990. p = 2.4031110387097893999e-05 + p * w;
  5991. p = -0.0003550375203628474796 + p * w;
  5992. p = 0.00095328937973738049703 + p * w;
  5993. p = -0.0016882755560235047313 + p * w;
  5994. p = 0.0024914420961078508066 + p * w;
  5995. p = -0.0037512085075692412107 + p * w;
  5996. p = 0.005370914553590063617 + p * w;
  5997. p = 1.0052589676941592334 + p * w;
  5998. p = 3.0838856104922207635 + p * w;
  5999. } else {
  6000. w = sqrt(w) - 5.000000;
  6001. p = -2.7109920616438573243e-11;
  6002. p = -2.5556418169965252055e-10 + p * w;
  6003. p = 1.5076572693500548083e-09 + p * w;
  6004. p = -3.7894654401267369937e-09 + p * w;
  6005. p = 7.6157012080783393804e-09 + p * w;
  6006. p = -1.4960026627149240478e-08 + p * w;
  6007. p = 2.9147953450901080826e-08 + p * w;
  6008. p = -6.7711997758452339498e-08 + p * w;
  6009. p = 2.2900482228026654717e-07 + p * w;
  6010. p = -9.9298272942317002539e-07 + p * w;
  6011. p = 4.5260625972231537039e-06 + p * w;
  6012. p = -1.9681778105531670567e-05 + p * w;
  6013. p = 7.5995277030017761139e-05 + p * w;
  6014. p = -0.00021503011930044477347 + p * w;
  6015. p = -0.00013871931833623122026 + p * w;
  6016. p = 1.0103004648645343977 + p * w;
  6017. p = 4.8499064014085844221 + p * w;
  6018. }
  6019. return p * x;
  6020. }
  6021. double standard_deviation(std::vector<double>::iterator first, std::vector<double>::iterator last) {
  6022. auto m = Catch::Benchmark::Detail::mean(first, last);
  6023. double variance = std::accumulate(first, last, 0., [m](double a, double b) {
  6024. double diff = b - m;
  6025. return a + diff * diff;
  6026. }) / (last - first);
  6027. return std::sqrt(variance);
  6028. }
  6029. }
  6030. namespace Catch {
  6031. namespace Benchmark {
  6032. namespace Detail {
  6033. double weighted_average_quantile(int k, int q, std::vector<double>::iterator first, std::vector<double>::iterator last) {
  6034. auto count = last - first;
  6035. double idx = (count - 1) * k / static_cast<double>(q);
  6036. int j = static_cast<int>(idx);
  6037. double g = idx - j;
  6038. std::nth_element(first, first + j, last);
  6039. auto xj = first[j];
  6040. if (g == 0) return xj;
  6041. auto xj1 = *std::min_element(first + (j + 1), last);
  6042. return xj + g * (xj1 - xj);
  6043. }
  6044. double erfc_inv(double x) {
  6045. return erf_inv(1.0 - x);
  6046. }
  6047. double normal_quantile(double p) {
  6048. static const double ROOT_TWO = std::sqrt(2.0);
  6049. double result = 0.0;
  6050. assert(p >= 0 && p <= 1);
  6051. if (p < 0 || p > 1) {
  6052. return result;
  6053. }
  6054. result = -erfc_inv(2.0 * p);
  6055. // result *= normal distribution standard deviation (1.0) * sqrt(2)
  6056. result *= /*sd * */ ROOT_TWO;
  6057. // result += normal disttribution mean (0)
  6058. return result;
  6059. }
  6060. double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n) {
  6061. double sb = stddev.point;
  6062. double mn = mean.point / n;
  6063. double mg_min = mn / 2.;
  6064. double sg = std::min(mg_min / 4., sb / std::sqrt(n));
  6065. double sg2 = sg * sg;
  6066. double sb2 = sb * sb;
  6067. auto c_max = [n, mn, sb2, sg2](double x) -> double {
  6068. double k = mn - x;
  6069. double d = k * k;
  6070. double nd = n * d;
  6071. double k0 = -n * nd;
  6072. double k1 = sb2 - n * sg2 + nd;
  6073. double det = k1 * k1 - 4 * sg2 * k0;
  6074. return (int)(-2. * k0 / (k1 + std::sqrt(det)));
  6075. };
  6076. auto var_out = [n, sb2, sg2](double c) {
  6077. double nc = n - c;
  6078. return (nc / n) * (sb2 - nc * sg2);
  6079. };
  6080. return std::min(var_out(1), var_out(std::min(c_max(0.), c_max(mg_min)))) / sb2;
  6081. }
  6082. bootstrap_analysis analyse_samples(double confidence_level, int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last) {
  6083. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  6084. static std::random_device entropy;
  6085. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  6086. auto n = static_cast<int>(last - first); // seriously, one can't use integral types without hell in C++
  6087. auto mean = &Detail::mean<std::vector<double>::iterator>;
  6088. auto stddev = &standard_deviation;
  6089. #if defined(CATCH_CONFIG_USE_ASYNC)
  6090. auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
  6091. auto seed = entropy();
  6092. return std::async(std::launch::async, [=] {
  6093. std::mt19937 rng(seed);
  6094. auto resampled = resample(rng, n_resamples, first, last, f);
  6095. return bootstrap(confidence_level, first, last, resampled, f);
  6096. });
  6097. };
  6098. auto mean_future = Estimate(mean);
  6099. auto stddev_future = Estimate(stddev);
  6100. auto mean_estimate = mean_future.get();
  6101. auto stddev_estimate = stddev_future.get();
  6102. #else
  6103. auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
  6104. auto seed = entropy();
  6105. std::mt19937 rng(seed);
  6106. auto resampled = resample(rng, n_resamples, first, last, f);
  6107. return bootstrap(confidence_level, first, last, resampled, f);
  6108. };
  6109. auto mean_estimate = Estimate(mean);
  6110. auto stddev_estimate = Estimate(stddev);
  6111. #endif // CATCH_USE_ASYNC
  6112. double outlier_variance = Detail::outlier_variance(mean_estimate, stddev_estimate, n);
  6113. return { mean_estimate, stddev_estimate, outlier_variance };
  6114. }
  6115. } // namespace Detail
  6116. } // namespace Benchmark
  6117. } // namespace Catch
  6118. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  6119. // end catch_stats.cpp
  6120. // start catch_approx.cpp
  6121. #include <cmath>
  6122. #include <limits>
  6123. namespace {
  6124. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  6125. // But without the subtraction to allow for INFINITY in comparison
  6126. bool marginComparison(double lhs, double rhs, double margin) {
  6127. return (lhs + margin >= rhs) && (rhs + margin >= lhs);
  6128. }
  6129. }
  6130. namespace Catch {
  6131. namespace Detail {
  6132. Approx::Approx ( double value )
  6133. : m_epsilon( std::numeric_limits<float>::epsilon()*100 ),
  6134. m_margin( 0.0 ),
  6135. m_scale( 0.0 ),
  6136. m_value( value )
  6137. {}
  6138. Approx Approx::custom() {
  6139. return Approx( 0 );
  6140. }
  6141. Approx Approx::operator-() const {
  6142. auto temp(*this);
  6143. temp.m_value = -temp.m_value;
  6144. return temp;
  6145. }
  6146. std::string Approx::toString() const {
  6147. ReusableStringStream rss;
  6148. rss << "Approx( " << ::Catch::Detail::stringify( m_value ) << " )";
  6149. return rss.str();
  6150. }
  6151. bool Approx::equalityComparisonImpl(const double other) const {
  6152. // First try with fixed margin, then compute margin based on epsilon, scale and Approx's value
  6153. // Thanks to Richard Harris for his help refining the scaled margin value
  6154. return marginComparison(m_value, other, m_margin) || marginComparison(m_value, other, m_epsilon * (m_scale + std::fabs(m_value)));
  6155. }
  6156. void Approx::setMargin(double newMargin) {
  6157. CATCH_ENFORCE(newMargin >= 0,
  6158. "Invalid Approx::margin: " << newMargin << '.'
  6159. << " Approx::Margin has to be non-negative.");
  6160. m_margin = newMargin;
  6161. }
  6162. void Approx::setEpsilon(double newEpsilon) {
  6163. CATCH_ENFORCE(newEpsilon >= 0 && newEpsilon <= 1.0,
  6164. "Invalid Approx::epsilon: " << newEpsilon << '.'
  6165. << " Approx::epsilon has to be in [0, 1]");
  6166. m_epsilon = newEpsilon;
  6167. }
  6168. } // end namespace Detail
  6169. namespace literals {
  6170. Detail::Approx operator "" _a(long double val) {
  6171. return Detail::Approx(val);
  6172. }
  6173. Detail::Approx operator "" _a(unsigned long long val) {
  6174. return Detail::Approx(val);
  6175. }
  6176. } // end namespace literals
  6177. std::string StringMaker<Catch::Detail::Approx>::convert(Catch::Detail::Approx const& value) {
  6178. return value.toString();
  6179. }
  6180. } // end namespace Catch
  6181. // end catch_approx.cpp
  6182. // start catch_assertionhandler.cpp
  6183. // start catch_debugger.h
  6184. namespace Catch {
  6185. bool isDebuggerActive();
  6186. }
  6187. #ifdef CATCH_PLATFORM_MAC
  6188. #define CATCH_TRAP() __asm__("int $3\n" : : ) /* NOLINT */
  6189. #elif defined(CATCH_PLATFORM_LINUX)
  6190. // If we can use inline assembler, do it because this allows us to break
  6191. // directly at the location of the failing check instead of breaking inside
  6192. // raise() called from it, i.e. one stack frame below.
  6193. #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64))
  6194. #define CATCH_TRAP() asm volatile ("int $3") /* NOLINT */
  6195. #else // Fall back to the generic way.
  6196. #include <signal.h>
  6197. #define CATCH_TRAP() raise(SIGTRAP)
  6198. #endif
  6199. #elif defined(_MSC_VER)
  6200. #define CATCH_TRAP() __debugbreak()
  6201. #elif defined(__MINGW32__)
  6202. extern "C" __declspec(dllimport) void __stdcall DebugBreak();
  6203. #define CATCH_TRAP() DebugBreak()
  6204. #endif
  6205. #ifdef CATCH_TRAP
  6206. #define CATCH_BREAK_INTO_DEBUGGER() []{ if( Catch::isDebuggerActive() ) { CATCH_TRAP(); } }()
  6207. #else
  6208. #define CATCH_BREAK_INTO_DEBUGGER() []{}()
  6209. #endif
  6210. // end catch_debugger.h
  6211. // start catch_run_context.h
  6212. // start catch_fatal_condition.h
  6213. // start catch_windows_h_proxy.h
  6214. #if defined(CATCH_PLATFORM_WINDOWS)
  6215. #if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX)
  6216. # define CATCH_DEFINED_NOMINMAX
  6217. # define NOMINMAX
  6218. #endif
  6219. #if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN)
  6220. # define CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  6221. # define WIN32_LEAN_AND_MEAN
  6222. #endif
  6223. #ifdef __AFXDLL
  6224. #include <AfxWin.h>
  6225. #else
  6226. #include <windows.h>
  6227. #endif
  6228. #ifdef CATCH_DEFINED_NOMINMAX
  6229. # undef NOMINMAX
  6230. #endif
  6231. #ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  6232. # undef WIN32_LEAN_AND_MEAN
  6233. #endif
  6234. #endif // defined(CATCH_PLATFORM_WINDOWS)
  6235. // end catch_windows_h_proxy.h
  6236. #if defined( CATCH_CONFIG_WINDOWS_SEH )
  6237. namespace Catch {
  6238. struct FatalConditionHandler {
  6239. static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo);
  6240. FatalConditionHandler();
  6241. static void reset();
  6242. ~FatalConditionHandler();
  6243. private:
  6244. static bool isSet;
  6245. static ULONG guaranteeSize;
  6246. static PVOID exceptionHandlerHandle;
  6247. };
  6248. } // namespace Catch
  6249. #elif defined ( CATCH_CONFIG_POSIX_SIGNALS )
  6250. #include <signal.h>
  6251. namespace Catch {
  6252. struct FatalConditionHandler {
  6253. static bool isSet;
  6254. static struct sigaction oldSigActions[];
  6255. static stack_t oldSigStack;
  6256. static char altStackMem[];
  6257. static void handleSignal( int sig );
  6258. FatalConditionHandler();
  6259. ~FatalConditionHandler();
  6260. static void reset();
  6261. };
  6262. } // namespace Catch
  6263. #else
  6264. namespace Catch {
  6265. struct FatalConditionHandler {
  6266. void reset();
  6267. };
  6268. }
  6269. #endif
  6270. // end catch_fatal_condition.h
  6271. #include <string>
  6272. namespace Catch {
  6273. struct IMutableContext;
  6274. ///////////////////////////////////////////////////////////////////////////
  6275. class RunContext : public IResultCapture, public IRunner {
  6276. public:
  6277. RunContext( RunContext const& ) = delete;
  6278. RunContext& operator =( RunContext const& ) = delete;
  6279. explicit RunContext( IConfigPtr const& _config, IStreamingReporterPtr&& reporter );
  6280. ~RunContext() override;
  6281. void testGroupStarting( std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount );
  6282. void testGroupEnded( std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount );
  6283. Totals runTest(TestCase const& testCase);
  6284. IConfigPtr config() const;
  6285. IStreamingReporter& reporter() const;
  6286. public: // IResultCapture
  6287. // Assertion handlers
  6288. void handleExpr
  6289. ( AssertionInfo const& info,
  6290. ITransientExpression const& expr,
  6291. AssertionReaction& reaction ) override;
  6292. void handleMessage
  6293. ( AssertionInfo const& info,
  6294. ResultWas::OfType resultType,
  6295. StringRef const& message,
  6296. AssertionReaction& reaction ) override;
  6297. void handleUnexpectedExceptionNotThrown
  6298. ( AssertionInfo const& info,
  6299. AssertionReaction& reaction ) override;
  6300. void handleUnexpectedInflightException
  6301. ( AssertionInfo const& info,
  6302. std::string const& message,
  6303. AssertionReaction& reaction ) override;
  6304. void handleIncomplete
  6305. ( AssertionInfo const& info ) override;
  6306. void handleNonExpr
  6307. ( AssertionInfo const &info,
  6308. ResultWas::OfType resultType,
  6309. AssertionReaction &reaction ) override;
  6310. bool sectionStarted( SectionInfo const& sectionInfo, Counts& assertions ) override;
  6311. void sectionEnded( SectionEndInfo const& endInfo ) override;
  6312. void sectionEndedEarly( SectionEndInfo const& endInfo ) override;
  6313. auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& override;
  6314. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  6315. void benchmarkPreparing( std::string const& name ) override;
  6316. void benchmarkStarting( BenchmarkInfo const& info ) override;
  6317. void benchmarkEnded( BenchmarkStats<> const& stats ) override;
  6318. void benchmarkFailed( std::string const& error ) override;
  6319. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  6320. void pushScopedMessage( MessageInfo const& message ) override;
  6321. void popScopedMessage( MessageInfo const& message ) override;
  6322. void emplaceUnscopedMessage( MessageBuilder const& builder ) override;
  6323. std::string getCurrentTestName() const override;
  6324. const AssertionResult* getLastResult() const override;
  6325. void exceptionEarlyReported() override;
  6326. void handleFatalErrorCondition( StringRef message ) override;
  6327. bool lastAssertionPassed() override;
  6328. void assertionPassed() override;
  6329. public:
  6330. // !TBD We need to do this another way!
  6331. bool aborting() const final;
  6332. private:
  6333. void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr );
  6334. void invokeActiveTestCase();
  6335. void resetAssertionInfo();
  6336. bool testForMissingAssertions( Counts& assertions );
  6337. void assertionEnded( AssertionResult const& result );
  6338. void reportExpr
  6339. ( AssertionInfo const &info,
  6340. ResultWas::OfType resultType,
  6341. ITransientExpression const *expr,
  6342. bool negated );
  6343. void populateReaction( AssertionReaction& reaction );
  6344. private:
  6345. void handleUnfinishedSections();
  6346. TestRunInfo m_runInfo;
  6347. IMutableContext& m_context;
  6348. TestCase const* m_activeTestCase = nullptr;
  6349. ITracker* m_testCaseTracker = nullptr;
  6350. Option<AssertionResult> m_lastResult;
  6351. IConfigPtr m_config;
  6352. Totals m_totals;
  6353. IStreamingReporterPtr m_reporter;
  6354. std::vector<MessageInfo> m_messages;
  6355. std::vector<ScopedMessage> m_messageScopes; /* Keeps owners of so-called unscoped messages. */
  6356. AssertionInfo m_lastAssertionInfo;
  6357. std::vector<SectionEndInfo> m_unfinishedSections;
  6358. std::vector<ITracker*> m_activeSections;
  6359. TrackerContext m_trackerContext;
  6360. bool m_lastAssertionPassed = false;
  6361. bool m_shouldReportUnexpected = true;
  6362. bool m_includeSuccessfulResults;
  6363. };
  6364. } // end namespace Catch
  6365. // end catch_run_context.h
  6366. namespace Catch {
  6367. namespace {
  6368. auto operator <<( std::ostream& os, ITransientExpression const& expr ) -> std::ostream& {
  6369. expr.streamReconstructedExpression( os );
  6370. return os;
  6371. }
  6372. }
  6373. LazyExpression::LazyExpression( bool isNegated )
  6374. : m_isNegated( isNegated )
  6375. {}
  6376. LazyExpression::LazyExpression( LazyExpression const& other ) : m_isNegated( other.m_isNegated ) {}
  6377. LazyExpression::operator bool() const {
  6378. return m_transientExpression != nullptr;
  6379. }
  6380. auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream& {
  6381. if( lazyExpr.m_isNegated )
  6382. os << "!";
  6383. if( lazyExpr ) {
  6384. if( lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression() )
  6385. os << "(" << *lazyExpr.m_transientExpression << ")";
  6386. else
  6387. os << *lazyExpr.m_transientExpression;
  6388. }
  6389. else {
  6390. os << "{** error - unchecked empty expression requested **}";
  6391. }
  6392. return os;
  6393. }
  6394. AssertionHandler::AssertionHandler
  6395. ( StringRef const& macroName,
  6396. SourceLineInfo const& lineInfo,
  6397. StringRef capturedExpression,
  6398. ResultDisposition::Flags resultDisposition )
  6399. : m_assertionInfo{ macroName, lineInfo, capturedExpression, resultDisposition },
  6400. m_resultCapture( getResultCapture() )
  6401. {}
  6402. void AssertionHandler::handleExpr( ITransientExpression const& expr ) {
  6403. m_resultCapture.handleExpr( m_assertionInfo, expr, m_reaction );
  6404. }
  6405. void AssertionHandler::handleMessage(ResultWas::OfType resultType, StringRef const& message) {
  6406. m_resultCapture.handleMessage( m_assertionInfo, resultType, message, m_reaction );
  6407. }
  6408. auto AssertionHandler::allowThrows() const -> bool {
  6409. return getCurrentContext().getConfig()->allowThrows();
  6410. }
  6411. void AssertionHandler::complete() {
  6412. setCompleted();
  6413. if( m_reaction.shouldDebugBreak ) {
  6414. // If you find your debugger stopping you here then go one level up on the
  6415. // call-stack for the code that caused it (typically a failed assertion)
  6416. // (To go back to the test and change execution, jump over the throw, next)
  6417. CATCH_BREAK_INTO_DEBUGGER();
  6418. }
  6419. if (m_reaction.shouldThrow) {
  6420. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  6421. throw Catch::TestFailureException();
  6422. #else
  6423. CATCH_ERROR( "Test failure requires aborting test!" );
  6424. #endif
  6425. }
  6426. }
  6427. void AssertionHandler::setCompleted() {
  6428. m_completed = true;
  6429. }
  6430. void AssertionHandler::handleUnexpectedInflightException() {
  6431. m_resultCapture.handleUnexpectedInflightException( m_assertionInfo, Catch::translateActiveException(), m_reaction );
  6432. }
  6433. void AssertionHandler::handleExceptionThrownAsExpected() {
  6434. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  6435. }
  6436. void AssertionHandler::handleExceptionNotThrownAsExpected() {
  6437. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  6438. }
  6439. void AssertionHandler::handleUnexpectedExceptionNotThrown() {
  6440. m_resultCapture.handleUnexpectedExceptionNotThrown( m_assertionInfo, m_reaction );
  6441. }
  6442. void AssertionHandler::handleThrowingCallSkipped() {
  6443. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  6444. }
  6445. // This is the overload that takes a string and infers the Equals matcher from it
  6446. // The more general overload, that takes any string matcher, is in catch_capture_matchers.cpp
  6447. void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString ) {
  6448. handleExceptionMatchExpr( handler, Matchers::Equals( str ), matcherString );
  6449. }
  6450. } // namespace Catch
  6451. // end catch_assertionhandler.cpp
  6452. // start catch_assertionresult.cpp
  6453. namespace Catch {
  6454. AssertionResultData::AssertionResultData(ResultWas::OfType _resultType, LazyExpression const & _lazyExpression):
  6455. lazyExpression(_lazyExpression),
  6456. resultType(_resultType) {}
  6457. std::string AssertionResultData::reconstructExpression() const {
  6458. if( reconstructedExpression.empty() ) {
  6459. if( lazyExpression ) {
  6460. ReusableStringStream rss;
  6461. rss << lazyExpression;
  6462. reconstructedExpression = rss.str();
  6463. }
  6464. }
  6465. return reconstructedExpression;
  6466. }
  6467. AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data )
  6468. : m_info( info ),
  6469. m_resultData( data )
  6470. {}
  6471. // Result was a success
  6472. bool AssertionResult::succeeded() const {
  6473. return Catch::isOk( m_resultData.resultType );
  6474. }
  6475. // Result was a success, or failure is suppressed
  6476. bool AssertionResult::isOk() const {
  6477. return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition );
  6478. }
  6479. ResultWas::OfType AssertionResult::getResultType() const {
  6480. return m_resultData.resultType;
  6481. }
  6482. bool AssertionResult::hasExpression() const {
  6483. return m_info.capturedExpression[0] != 0;
  6484. }
  6485. bool AssertionResult::hasMessage() const {
  6486. return !m_resultData.message.empty();
  6487. }
  6488. std::string AssertionResult::getExpression() const {
  6489. if( isFalseTest( m_info.resultDisposition ) )
  6490. return "!(" + m_info.capturedExpression + ")";
  6491. else
  6492. return m_info.capturedExpression;
  6493. }
  6494. std::string AssertionResult::getExpressionInMacro() const {
  6495. std::string expr;
  6496. if( m_info.macroName[0] == 0 )
  6497. expr = m_info.capturedExpression;
  6498. else {
  6499. expr.reserve( m_info.macroName.size() + m_info.capturedExpression.size() + 4 );
  6500. expr += m_info.macroName;
  6501. expr += "( ";
  6502. expr += m_info.capturedExpression;
  6503. expr += " )";
  6504. }
  6505. return expr;
  6506. }
  6507. bool AssertionResult::hasExpandedExpression() const {
  6508. return hasExpression() && getExpandedExpression() != getExpression();
  6509. }
  6510. std::string AssertionResult::getExpandedExpression() const {
  6511. std::string expr = m_resultData.reconstructExpression();
  6512. return expr.empty()
  6513. ? getExpression()
  6514. : expr;
  6515. }
  6516. std::string AssertionResult::getMessage() const {
  6517. return m_resultData.message;
  6518. }
  6519. SourceLineInfo AssertionResult::getSourceInfo() const {
  6520. return m_info.lineInfo;
  6521. }
  6522. StringRef AssertionResult::getTestMacroName() const {
  6523. return m_info.macroName;
  6524. }
  6525. } // end namespace Catch
  6526. // end catch_assertionresult.cpp
  6527. // start catch_capture_matchers.cpp
  6528. namespace Catch {
  6529. using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
  6530. // This is the general overload that takes a any string matcher
  6531. // There is another overload, in catch_assertionhandler.h/.cpp, that only takes a string and infers
  6532. // the Equals matcher (so the header does not mention matchers)
  6533. void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString ) {
  6534. std::string exceptionMessage = Catch::translateActiveException();
  6535. MatchExpr<std::string, StringMatcher const&> expr( exceptionMessage, matcher, matcherString );
  6536. handler.handleExpr( expr );
  6537. }
  6538. } // namespace Catch
  6539. // end catch_capture_matchers.cpp
  6540. // start catch_commandline.cpp
  6541. // start catch_commandline.h
  6542. // start catch_clara.h
  6543. // Use Catch's value for console width (store Clara's off to the side, if present)
  6544. #ifdef CLARA_CONFIG_CONSOLE_WIDTH
  6545. #define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  6546. #undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  6547. #endif
  6548. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH-1
  6549. #ifdef __clang__
  6550. #pragma clang diagnostic push
  6551. #pragma clang diagnostic ignored "-Wweak-vtables"
  6552. #pragma clang diagnostic ignored "-Wexit-time-destructors"
  6553. #pragma clang diagnostic ignored "-Wshadow"
  6554. #endif
  6555. // start clara.hpp
  6556. // Copyright 2017 Two Blue Cubes Ltd. All rights reserved.
  6557. //
  6558. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  6559. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6560. //
  6561. // See https://github.com/philsquared/Clara for more details
  6562. // Clara v1.1.5
  6563. #ifndef CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  6564. #define CATCH_CLARA_CONFIG_CONSOLE_WIDTH 80
  6565. #endif
  6566. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  6567. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  6568. #endif
  6569. #ifndef CLARA_CONFIG_OPTIONAL_TYPE
  6570. #ifdef __has_include
  6571. #if __has_include(<optional>) && __cplusplus >= 201703L
  6572. #include <optional>
  6573. #define CLARA_CONFIG_OPTIONAL_TYPE std::optional
  6574. #endif
  6575. #endif
  6576. #endif
  6577. // ----------- #included from clara_textflow.hpp -----------
  6578. // TextFlowCpp
  6579. //
  6580. // A single-header library for wrapping and laying out basic text, by Phil Nash
  6581. //
  6582. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  6583. // file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6584. //
  6585. // This project is hosted at https://github.com/philsquared/textflowcpp
  6586. #include <cassert>
  6587. #include <ostream>
  6588. #include <sstream>
  6589. #include <vector>
  6590. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  6591. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80
  6592. #endif
  6593. namespace Catch {
  6594. namespace clara {
  6595. namespace TextFlow {
  6596. inline auto isWhitespace(char c) -> bool {
  6597. static std::string chars = " \t\n\r";
  6598. return chars.find(c) != std::string::npos;
  6599. }
  6600. inline auto isBreakableBefore(char c) -> bool {
  6601. static std::string chars = "[({<|";
  6602. return chars.find(c) != std::string::npos;
  6603. }
  6604. inline auto isBreakableAfter(char c) -> bool {
  6605. static std::string chars = "])}>.,:;*+-=&/\\";
  6606. return chars.find(c) != std::string::npos;
  6607. }
  6608. class Columns;
  6609. class Column {
  6610. std::vector<std::string> m_strings;
  6611. size_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH;
  6612. size_t m_indent = 0;
  6613. size_t m_initialIndent = std::string::npos;
  6614. public:
  6615. class iterator {
  6616. friend Column;
  6617. Column const& m_column;
  6618. size_t m_stringIndex = 0;
  6619. size_t m_pos = 0;
  6620. size_t m_len = 0;
  6621. size_t m_end = 0;
  6622. bool m_suffix = false;
  6623. iterator(Column const& column, size_t stringIndex)
  6624. : m_column(column),
  6625. m_stringIndex(stringIndex) {}
  6626. auto line() const -> std::string const& { return m_column.m_strings[m_stringIndex]; }
  6627. auto isBoundary(size_t at) const -> bool {
  6628. assert(at > 0);
  6629. assert(at <= line().size());
  6630. return at == line().size() ||
  6631. (isWhitespace(line()[at]) && !isWhitespace(line()[at - 1])) ||
  6632. isBreakableBefore(line()[at]) ||
  6633. isBreakableAfter(line()[at - 1]);
  6634. }
  6635. void calcLength() {
  6636. assert(m_stringIndex < m_column.m_strings.size());
  6637. m_suffix = false;
  6638. auto width = m_column.m_width - indent();
  6639. m_end = m_pos;
  6640. if (line()[m_pos] == '\n') {
  6641. ++m_end;
  6642. }
  6643. while (m_end < line().size() && line()[m_end] != '\n')
  6644. ++m_end;
  6645. if (m_end < m_pos + width) {
  6646. m_len = m_end - m_pos;
  6647. } else {
  6648. size_t len = width;
  6649. while (len > 0 && !isBoundary(m_pos + len))
  6650. --len;
  6651. while (len > 0 && isWhitespace(line()[m_pos + len - 1]))
  6652. --len;
  6653. if (len > 0) {
  6654. m_len = len;
  6655. } else {
  6656. m_suffix = true;
  6657. m_len = width - 1;
  6658. }
  6659. }
  6660. }
  6661. auto indent() const -> size_t {
  6662. auto initial = m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos;
  6663. return initial == std::string::npos ? m_column.m_indent : initial;
  6664. }
  6665. auto addIndentAndSuffix(std::string const &plain) const -> std::string {
  6666. return std::string(indent(), ' ') + (m_suffix ? plain + "-" : plain);
  6667. }
  6668. public:
  6669. using difference_type = std::ptrdiff_t;
  6670. using value_type = std::string;
  6671. using pointer = value_type * ;
  6672. using reference = value_type & ;
  6673. using iterator_category = std::forward_iterator_tag;
  6674. explicit iterator(Column const& column) : m_column(column) {
  6675. assert(m_column.m_width > m_column.m_indent);
  6676. assert(m_column.m_initialIndent == std::string::npos || m_column.m_width > m_column.m_initialIndent);
  6677. calcLength();
  6678. if (m_len == 0)
  6679. m_stringIndex++; // Empty string
  6680. }
  6681. auto operator *() const -> std::string {
  6682. assert(m_stringIndex < m_column.m_strings.size());
  6683. assert(m_pos <= m_end);
  6684. return addIndentAndSuffix(line().substr(m_pos, m_len));
  6685. }
  6686. auto operator ++() -> iterator& {
  6687. m_pos += m_len;
  6688. if (m_pos < line().size() && line()[m_pos] == '\n')
  6689. m_pos += 1;
  6690. else
  6691. while (m_pos < line().size() && isWhitespace(line()[m_pos]))
  6692. ++m_pos;
  6693. if (m_pos == line().size()) {
  6694. m_pos = 0;
  6695. ++m_stringIndex;
  6696. }
  6697. if (m_stringIndex < m_column.m_strings.size())
  6698. calcLength();
  6699. return *this;
  6700. }
  6701. auto operator ++(int) -> iterator {
  6702. iterator prev(*this);
  6703. operator++();
  6704. return prev;
  6705. }
  6706. auto operator ==(iterator const& other) const -> bool {
  6707. return
  6708. m_pos == other.m_pos &&
  6709. m_stringIndex == other.m_stringIndex &&
  6710. &m_column == &other.m_column;
  6711. }
  6712. auto operator !=(iterator const& other) const -> bool {
  6713. return !operator==(other);
  6714. }
  6715. };
  6716. using const_iterator = iterator;
  6717. explicit Column(std::string const& text) { m_strings.push_back(text); }
  6718. auto width(size_t newWidth) -> Column& {
  6719. assert(newWidth > 0);
  6720. m_width = newWidth;
  6721. return *this;
  6722. }
  6723. auto indent(size_t newIndent) -> Column& {
  6724. m_indent = newIndent;
  6725. return *this;
  6726. }
  6727. auto initialIndent(size_t newIndent) -> Column& {
  6728. m_initialIndent = newIndent;
  6729. return *this;
  6730. }
  6731. auto width() const -> size_t { return m_width; }
  6732. auto begin() const -> iterator { return iterator(*this); }
  6733. auto end() const -> iterator { return { *this, m_strings.size() }; }
  6734. inline friend std::ostream& operator << (std::ostream& os, Column const& col) {
  6735. bool first = true;
  6736. for (auto line : col) {
  6737. if (first)
  6738. first = false;
  6739. else
  6740. os << "\n";
  6741. os << line;
  6742. }
  6743. return os;
  6744. }
  6745. auto operator + (Column const& other)->Columns;
  6746. auto toString() const -> std::string {
  6747. std::ostringstream oss;
  6748. oss << *this;
  6749. return oss.str();
  6750. }
  6751. };
  6752. class Spacer : public Column {
  6753. public:
  6754. explicit Spacer(size_t spaceWidth) : Column("") {
  6755. width(spaceWidth);
  6756. }
  6757. };
  6758. class Columns {
  6759. std::vector<Column> m_columns;
  6760. public:
  6761. class iterator {
  6762. friend Columns;
  6763. struct EndTag {};
  6764. std::vector<Column> const& m_columns;
  6765. std::vector<Column::iterator> m_iterators;
  6766. size_t m_activeIterators;
  6767. iterator(Columns const& columns, EndTag)
  6768. : m_columns(columns.m_columns),
  6769. m_activeIterators(0) {
  6770. m_iterators.reserve(m_columns.size());
  6771. for (auto const& col : m_columns)
  6772. m_iterators.push_back(col.end());
  6773. }
  6774. public:
  6775. using difference_type = std::ptrdiff_t;
  6776. using value_type = std::string;
  6777. using pointer = value_type * ;
  6778. using reference = value_type & ;
  6779. using iterator_category = std::forward_iterator_tag;
  6780. explicit iterator(Columns const& columns)
  6781. : m_columns(columns.m_columns),
  6782. m_activeIterators(m_columns.size()) {
  6783. m_iterators.reserve(m_columns.size());
  6784. for (auto const& col : m_columns)
  6785. m_iterators.push_back(col.begin());
  6786. }
  6787. auto operator ==(iterator const& other) const -> bool {
  6788. return m_iterators == other.m_iterators;
  6789. }
  6790. auto operator !=(iterator const& other) const -> bool {
  6791. return m_iterators != other.m_iterators;
  6792. }
  6793. auto operator *() const -> std::string {
  6794. std::string row, padding;
  6795. for (size_t i = 0; i < m_columns.size(); ++i) {
  6796. auto width = m_columns[i].width();
  6797. if (m_iterators[i] != m_columns[i].end()) {
  6798. std::string col = *m_iterators[i];
  6799. row += padding + col;
  6800. if (col.size() < width)
  6801. padding = std::string(width - col.size(), ' ');
  6802. else
  6803. padding = "";
  6804. } else {
  6805. padding += std::string(width, ' ');
  6806. }
  6807. }
  6808. return row;
  6809. }
  6810. auto operator ++() -> iterator& {
  6811. for (size_t i = 0; i < m_columns.size(); ++i) {
  6812. if (m_iterators[i] != m_columns[i].end())
  6813. ++m_iterators[i];
  6814. }
  6815. return *this;
  6816. }
  6817. auto operator ++(int) -> iterator {
  6818. iterator prev(*this);
  6819. operator++();
  6820. return prev;
  6821. }
  6822. };
  6823. using const_iterator = iterator;
  6824. auto begin() const -> iterator { return iterator(*this); }
  6825. auto end() const -> iterator { return { *this, iterator::EndTag() }; }
  6826. auto operator += (Column const& col) -> Columns& {
  6827. m_columns.push_back(col);
  6828. return *this;
  6829. }
  6830. auto operator + (Column const& col) -> Columns {
  6831. Columns combined = *this;
  6832. combined += col;
  6833. return combined;
  6834. }
  6835. inline friend std::ostream& operator << (std::ostream& os, Columns const& cols) {
  6836. bool first = true;
  6837. for (auto line : cols) {
  6838. if (first)
  6839. first = false;
  6840. else
  6841. os << "\n";
  6842. os << line;
  6843. }
  6844. return os;
  6845. }
  6846. auto toString() const -> std::string {
  6847. std::ostringstream oss;
  6848. oss << *this;
  6849. return oss.str();
  6850. }
  6851. };
  6852. inline auto Column::operator + (Column const& other) -> Columns {
  6853. Columns cols;
  6854. cols += *this;
  6855. cols += other;
  6856. return cols;
  6857. }
  6858. }
  6859. }
  6860. }
  6861. // ----------- end of #include from clara_textflow.hpp -----------
  6862. // ........... back in clara.hpp
  6863. #include <cctype>
  6864. #include <string>
  6865. #include <memory>
  6866. #include <set>
  6867. #include <algorithm>
  6868. #if !defined(CATCH_PLATFORM_WINDOWS) && ( defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) )
  6869. #define CATCH_PLATFORM_WINDOWS
  6870. #endif
  6871. namespace Catch { namespace clara {
  6872. namespace detail {
  6873. // Traits for extracting arg and return type of lambdas (for single argument lambdas)
  6874. template<typename L>
  6875. struct UnaryLambdaTraits : UnaryLambdaTraits<decltype( &L::operator() )> {};
  6876. template<typename ClassT, typename ReturnT, typename... Args>
  6877. struct UnaryLambdaTraits<ReturnT( ClassT::* )( Args... ) const> {
  6878. static const bool isValid = false;
  6879. };
  6880. template<typename ClassT, typename ReturnT, typename ArgT>
  6881. struct UnaryLambdaTraits<ReturnT( ClassT::* )( ArgT ) const> {
  6882. static const bool isValid = true;
  6883. using ArgType = typename std::remove_const<typename std::remove_reference<ArgT>::type>::type;
  6884. using ReturnType = ReturnT;
  6885. };
  6886. class TokenStream;
  6887. // Transport for raw args (copied from main args, or supplied via init list for testing)
  6888. class Args {
  6889. friend TokenStream;
  6890. std::string m_exeName;
  6891. std::vector<std::string> m_args;
  6892. public:
  6893. Args( int argc, char const* const* argv )
  6894. : m_exeName(argv[0]),
  6895. m_args(argv + 1, argv + argc) {}
  6896. Args( std::initializer_list<std::string> args )
  6897. : m_exeName( *args.begin() ),
  6898. m_args( args.begin()+1, args.end() )
  6899. {}
  6900. auto exeName() const -> std::string {
  6901. return m_exeName;
  6902. }
  6903. };
  6904. // Wraps a token coming from a token stream. These may not directly correspond to strings as a single string
  6905. // may encode an option + its argument if the : or = form is used
  6906. enum class TokenType {
  6907. Option, Argument
  6908. };
  6909. struct Token {
  6910. TokenType type;
  6911. std::string token;
  6912. };
  6913. inline auto isOptPrefix( char c ) -> bool {
  6914. return c == '-'
  6915. #ifdef CATCH_PLATFORM_WINDOWS
  6916. || c == '/'
  6917. #endif
  6918. ;
  6919. }
  6920. // Abstracts iterators into args as a stream of tokens, with option arguments uniformly handled
  6921. class TokenStream {
  6922. using Iterator = std::vector<std::string>::const_iterator;
  6923. Iterator it;
  6924. Iterator itEnd;
  6925. std::vector<Token> m_tokenBuffer;
  6926. void loadBuffer() {
  6927. m_tokenBuffer.resize( 0 );
  6928. // Skip any empty strings
  6929. while( it != itEnd && it->empty() )
  6930. ++it;
  6931. if( it != itEnd ) {
  6932. auto const &next = *it;
  6933. if( isOptPrefix( next[0] ) ) {
  6934. auto delimiterPos = next.find_first_of( " :=" );
  6935. if( delimiterPos != std::string::npos ) {
  6936. m_tokenBuffer.push_back( { TokenType::Option, next.substr( 0, delimiterPos ) } );
  6937. m_tokenBuffer.push_back( { TokenType::Argument, next.substr( delimiterPos + 1 ) } );
  6938. } else {
  6939. if( next[1] != '-' && next.size() > 2 ) {
  6940. std::string opt = "- ";
  6941. for( size_t i = 1; i < next.size(); ++i ) {
  6942. opt[1] = next[i];
  6943. m_tokenBuffer.push_back( { TokenType::Option, opt } );
  6944. }
  6945. } else {
  6946. m_tokenBuffer.push_back( { TokenType::Option, next } );
  6947. }
  6948. }
  6949. } else {
  6950. m_tokenBuffer.push_back( { TokenType::Argument, next } );
  6951. }
  6952. }
  6953. }
  6954. public:
  6955. explicit TokenStream( Args const &args ) : TokenStream( args.m_args.begin(), args.m_args.end() ) {}
  6956. TokenStream( Iterator it, Iterator itEnd ) : it( it ), itEnd( itEnd ) {
  6957. loadBuffer();
  6958. }
  6959. explicit operator bool() const {
  6960. return !m_tokenBuffer.empty() || it != itEnd;
  6961. }
  6962. auto count() const -> size_t { return m_tokenBuffer.size() + (itEnd - it); }
  6963. auto operator*() const -> Token {
  6964. assert( !m_tokenBuffer.empty() );
  6965. return m_tokenBuffer.front();
  6966. }
  6967. auto operator->() const -> Token const * {
  6968. assert( !m_tokenBuffer.empty() );
  6969. return &m_tokenBuffer.front();
  6970. }
  6971. auto operator++() -> TokenStream & {
  6972. if( m_tokenBuffer.size() >= 2 ) {
  6973. m_tokenBuffer.erase( m_tokenBuffer.begin() );
  6974. } else {
  6975. if( it != itEnd )
  6976. ++it;
  6977. loadBuffer();
  6978. }
  6979. return *this;
  6980. }
  6981. };
  6982. class ResultBase {
  6983. public:
  6984. enum Type {
  6985. Ok, LogicError, RuntimeError
  6986. };
  6987. protected:
  6988. ResultBase( Type type ) : m_type( type ) {}
  6989. virtual ~ResultBase() = default;
  6990. virtual void enforceOk() const = 0;
  6991. Type m_type;
  6992. };
  6993. template<typename T>
  6994. class ResultValueBase : public ResultBase {
  6995. public:
  6996. auto value() const -> T const & {
  6997. enforceOk();
  6998. return m_value;
  6999. }
  7000. protected:
  7001. ResultValueBase( Type type ) : ResultBase( type ) {}
  7002. ResultValueBase( ResultValueBase const &other ) : ResultBase( other ) {
  7003. if( m_type == ResultBase::Ok )
  7004. new( &m_value ) T( other.m_value );
  7005. }
  7006. ResultValueBase( Type, T const &value ) : ResultBase( Ok ) {
  7007. new( &m_value ) T( value );
  7008. }
  7009. auto operator=( ResultValueBase const &other ) -> ResultValueBase & {
  7010. if( m_type == ResultBase::Ok )
  7011. m_value.~T();
  7012. ResultBase::operator=(other);
  7013. if( m_type == ResultBase::Ok )
  7014. new( &m_value ) T( other.m_value );
  7015. return *this;
  7016. }
  7017. ~ResultValueBase() override {
  7018. if( m_type == Ok )
  7019. m_value.~T();
  7020. }
  7021. union {
  7022. T m_value;
  7023. };
  7024. };
  7025. template<>
  7026. class ResultValueBase<void> : public ResultBase {
  7027. protected:
  7028. using ResultBase::ResultBase;
  7029. };
  7030. template<typename T = void>
  7031. class BasicResult : public ResultValueBase<T> {
  7032. public:
  7033. template<typename U>
  7034. explicit BasicResult( BasicResult<U> const &other )
  7035. : ResultValueBase<T>( other.type() ),
  7036. m_errorMessage( other.errorMessage() )
  7037. {
  7038. assert( type() != ResultBase::Ok );
  7039. }
  7040. template<typename U>
  7041. static auto ok( U const &value ) -> BasicResult { return { ResultBase::Ok, value }; }
  7042. static auto ok() -> BasicResult { return { ResultBase::Ok }; }
  7043. static auto logicError( std::string const &message ) -> BasicResult { return { ResultBase::LogicError, message }; }
  7044. static auto runtimeError( std::string const &message ) -> BasicResult { return { ResultBase::RuntimeError, message }; }
  7045. explicit operator bool() const { return m_type == ResultBase::Ok; }
  7046. auto type() const -> ResultBase::Type { return m_type; }
  7047. auto errorMessage() const -> std::string { return m_errorMessage; }
  7048. protected:
  7049. void enforceOk() const override {
  7050. // Errors shouldn't reach this point, but if they do
  7051. // the actual error message will be in m_errorMessage
  7052. assert( m_type != ResultBase::LogicError );
  7053. assert( m_type != ResultBase::RuntimeError );
  7054. if( m_type != ResultBase::Ok )
  7055. std::abort();
  7056. }
  7057. std::string m_errorMessage; // Only populated if resultType is an error
  7058. BasicResult( ResultBase::Type type, std::string const &message )
  7059. : ResultValueBase<T>(type),
  7060. m_errorMessage(message)
  7061. {
  7062. assert( m_type != ResultBase::Ok );
  7063. }
  7064. using ResultValueBase<T>::ResultValueBase;
  7065. using ResultBase::m_type;
  7066. };
  7067. enum class ParseResultType {
  7068. Matched, NoMatch, ShortCircuitAll, ShortCircuitSame
  7069. };
  7070. class ParseState {
  7071. public:
  7072. ParseState( ParseResultType type, TokenStream const &remainingTokens )
  7073. : m_type(type),
  7074. m_remainingTokens( remainingTokens )
  7075. {}
  7076. auto type() const -> ParseResultType { return m_type; }
  7077. auto remainingTokens() const -> TokenStream { return m_remainingTokens; }
  7078. private:
  7079. ParseResultType m_type;
  7080. TokenStream m_remainingTokens;
  7081. };
  7082. using Result = BasicResult<void>;
  7083. using ParserResult = BasicResult<ParseResultType>;
  7084. using InternalParseResult = BasicResult<ParseState>;
  7085. struct HelpColumns {
  7086. std::string left;
  7087. std::string right;
  7088. };
  7089. template<typename T>
  7090. inline auto convertInto( std::string const &source, T& target ) -> ParserResult {
  7091. std::stringstream ss;
  7092. ss << source;
  7093. ss >> target;
  7094. if( ss.fail() )
  7095. return ParserResult::runtimeError( "Unable to convert '" + source + "' to destination type" );
  7096. else
  7097. return ParserResult::ok( ParseResultType::Matched );
  7098. }
  7099. inline auto convertInto( std::string const &source, std::string& target ) -> ParserResult {
  7100. target = source;
  7101. return ParserResult::ok( ParseResultType::Matched );
  7102. }
  7103. inline auto convertInto( std::string const &source, bool &target ) -> ParserResult {
  7104. std::string srcLC = source;
  7105. std::transform( srcLC.begin(), srcLC.end(), srcLC.begin(), []( char c ) { return static_cast<char>( std::tolower(c) ); } );
  7106. if (srcLC == "y" || srcLC == "1" || srcLC == "true" || srcLC == "yes" || srcLC == "on")
  7107. target = true;
  7108. else if (srcLC == "n" || srcLC == "0" || srcLC == "false" || srcLC == "no" || srcLC == "off")
  7109. target = false;
  7110. else
  7111. return ParserResult::runtimeError( "Expected a boolean value but did not recognise: '" + source + "'" );
  7112. return ParserResult::ok( ParseResultType::Matched );
  7113. }
  7114. #ifdef CLARA_CONFIG_OPTIONAL_TYPE
  7115. template<typename T>
  7116. inline auto convertInto( std::string const &source, CLARA_CONFIG_OPTIONAL_TYPE<T>& target ) -> ParserResult {
  7117. T temp;
  7118. auto result = convertInto( source, temp );
  7119. if( result )
  7120. target = std::move(temp);
  7121. return result;
  7122. }
  7123. #endif // CLARA_CONFIG_OPTIONAL_TYPE
  7124. struct NonCopyable {
  7125. NonCopyable() = default;
  7126. NonCopyable( NonCopyable const & ) = delete;
  7127. NonCopyable( NonCopyable && ) = delete;
  7128. NonCopyable &operator=( NonCopyable const & ) = delete;
  7129. NonCopyable &operator=( NonCopyable && ) = delete;
  7130. };
  7131. struct BoundRef : NonCopyable {
  7132. virtual ~BoundRef() = default;
  7133. virtual auto isContainer() const -> bool { return false; }
  7134. virtual auto isFlag() const -> bool { return false; }
  7135. };
  7136. struct BoundValueRefBase : BoundRef {
  7137. virtual auto setValue( std::string const &arg ) -> ParserResult = 0;
  7138. };
  7139. struct BoundFlagRefBase : BoundRef {
  7140. virtual auto setFlag( bool flag ) -> ParserResult = 0;
  7141. virtual auto isFlag() const -> bool { return true; }
  7142. };
  7143. template<typename T>
  7144. struct BoundValueRef : BoundValueRefBase {
  7145. T &m_ref;
  7146. explicit BoundValueRef( T &ref ) : m_ref( ref ) {}
  7147. auto setValue( std::string const &arg ) -> ParserResult override {
  7148. return convertInto( arg, m_ref );
  7149. }
  7150. };
  7151. template<typename T>
  7152. struct BoundValueRef<std::vector<T>> : BoundValueRefBase {
  7153. std::vector<T> &m_ref;
  7154. explicit BoundValueRef( std::vector<T> &ref ) : m_ref( ref ) {}
  7155. auto isContainer() const -> bool override { return true; }
  7156. auto setValue( std::string const &arg ) -> ParserResult override {
  7157. T temp;
  7158. auto result = convertInto( arg, temp );
  7159. if( result )
  7160. m_ref.push_back( temp );
  7161. return result;
  7162. }
  7163. };
  7164. struct BoundFlagRef : BoundFlagRefBase {
  7165. bool &m_ref;
  7166. explicit BoundFlagRef( bool &ref ) : m_ref( ref ) {}
  7167. auto setFlag( bool flag ) -> ParserResult override {
  7168. m_ref = flag;
  7169. return ParserResult::ok( ParseResultType::Matched );
  7170. }
  7171. };
  7172. template<typename ReturnType>
  7173. struct LambdaInvoker {
  7174. static_assert( std::is_same<ReturnType, ParserResult>::value, "Lambda must return void or clara::ParserResult" );
  7175. template<typename L, typename ArgType>
  7176. static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
  7177. return lambda( arg );
  7178. }
  7179. };
  7180. template<>
  7181. struct LambdaInvoker<void> {
  7182. template<typename L, typename ArgType>
  7183. static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
  7184. lambda( arg );
  7185. return ParserResult::ok( ParseResultType::Matched );
  7186. }
  7187. };
  7188. template<typename ArgType, typename L>
  7189. inline auto invokeLambda( L const &lambda, std::string const &arg ) -> ParserResult {
  7190. ArgType temp{};
  7191. auto result = convertInto( arg, temp );
  7192. return !result
  7193. ? result
  7194. : LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( lambda, temp );
  7195. }
  7196. template<typename L>
  7197. struct BoundLambda : BoundValueRefBase {
  7198. L m_lambda;
  7199. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  7200. explicit BoundLambda( L const &lambda ) : m_lambda( lambda ) {}
  7201. auto setValue( std::string const &arg ) -> ParserResult override {
  7202. return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>( m_lambda, arg );
  7203. }
  7204. };
  7205. template<typename L>
  7206. struct BoundFlagLambda : BoundFlagRefBase {
  7207. L m_lambda;
  7208. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  7209. static_assert( std::is_same<typename UnaryLambdaTraits<L>::ArgType, bool>::value, "flags must be boolean" );
  7210. explicit BoundFlagLambda( L const &lambda ) : m_lambda( lambda ) {}
  7211. auto setFlag( bool flag ) -> ParserResult override {
  7212. return LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( m_lambda, flag );
  7213. }
  7214. };
  7215. enum class Optionality { Optional, Required };
  7216. struct Parser;
  7217. class ParserBase {
  7218. public:
  7219. virtual ~ParserBase() = default;
  7220. virtual auto validate() const -> Result { return Result::ok(); }
  7221. virtual auto parse( std::string const& exeName, TokenStream const &tokens) const -> InternalParseResult = 0;
  7222. virtual auto cardinality() const -> size_t { return 1; }
  7223. auto parse( Args const &args ) const -> InternalParseResult {
  7224. return parse( args.exeName(), TokenStream( args ) );
  7225. }
  7226. };
  7227. template<typename DerivedT>
  7228. class ComposableParserImpl : public ParserBase {
  7229. public:
  7230. template<typename T>
  7231. auto operator|( T const &other ) const -> Parser;
  7232. template<typename T>
  7233. auto operator+( T const &other ) const -> Parser;
  7234. };
  7235. // Common code and state for Args and Opts
  7236. template<typename DerivedT>
  7237. class ParserRefImpl : public ComposableParserImpl<DerivedT> {
  7238. protected:
  7239. Optionality m_optionality = Optionality::Optional;
  7240. std::shared_ptr<BoundRef> m_ref;
  7241. std::string m_hint;
  7242. std::string m_description;
  7243. explicit ParserRefImpl( std::shared_ptr<BoundRef> const &ref ) : m_ref( ref ) {}
  7244. public:
  7245. template<typename T>
  7246. ParserRefImpl( T &ref, std::string const &hint )
  7247. : m_ref( std::make_shared<BoundValueRef<T>>( ref ) ),
  7248. m_hint( hint )
  7249. {}
  7250. template<typename LambdaT>
  7251. ParserRefImpl( LambdaT const &ref, std::string const &hint )
  7252. : m_ref( std::make_shared<BoundLambda<LambdaT>>( ref ) ),
  7253. m_hint(hint)
  7254. {}
  7255. auto operator()( std::string const &description ) -> DerivedT & {
  7256. m_description = description;
  7257. return static_cast<DerivedT &>( *this );
  7258. }
  7259. auto optional() -> DerivedT & {
  7260. m_optionality = Optionality::Optional;
  7261. return static_cast<DerivedT &>( *this );
  7262. };
  7263. auto required() -> DerivedT & {
  7264. m_optionality = Optionality::Required;
  7265. return static_cast<DerivedT &>( *this );
  7266. };
  7267. auto isOptional() const -> bool {
  7268. return m_optionality == Optionality::Optional;
  7269. }
  7270. auto cardinality() const -> size_t override {
  7271. if( m_ref->isContainer() )
  7272. return 0;
  7273. else
  7274. return 1;
  7275. }
  7276. auto hint() const -> std::string { return m_hint; }
  7277. };
  7278. class ExeName : public ComposableParserImpl<ExeName> {
  7279. std::shared_ptr<std::string> m_name;
  7280. std::shared_ptr<BoundValueRefBase> m_ref;
  7281. template<typename LambdaT>
  7282. static auto makeRef(LambdaT const &lambda) -> std::shared_ptr<BoundValueRefBase> {
  7283. return std::make_shared<BoundLambda<LambdaT>>( lambda) ;
  7284. }
  7285. public:
  7286. ExeName() : m_name( std::make_shared<std::string>( "<executable>" ) ) {}
  7287. explicit ExeName( std::string &ref ) : ExeName() {
  7288. m_ref = std::make_shared<BoundValueRef<std::string>>( ref );
  7289. }
  7290. template<typename LambdaT>
  7291. explicit ExeName( LambdaT const& lambda ) : ExeName() {
  7292. m_ref = std::make_shared<BoundLambda<LambdaT>>( lambda );
  7293. }
  7294. // The exe name is not parsed out of the normal tokens, but is handled specially
  7295. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  7296. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
  7297. }
  7298. auto name() const -> std::string { return *m_name; }
  7299. auto set( std::string const& newName ) -> ParserResult {
  7300. auto lastSlash = newName.find_last_of( "\\/" );
  7301. auto filename = ( lastSlash == std::string::npos )
  7302. ? newName
  7303. : newName.substr( lastSlash+1 );
  7304. *m_name = filename;
  7305. if( m_ref )
  7306. return m_ref->setValue( filename );
  7307. else
  7308. return ParserResult::ok( ParseResultType::Matched );
  7309. }
  7310. };
  7311. class Arg : public ParserRefImpl<Arg> {
  7312. public:
  7313. using ParserRefImpl::ParserRefImpl;
  7314. auto parse( std::string const &, TokenStream const &tokens ) const -> InternalParseResult override {
  7315. auto validationResult = validate();
  7316. if( !validationResult )
  7317. return InternalParseResult( validationResult );
  7318. auto remainingTokens = tokens;
  7319. auto const &token = *remainingTokens;
  7320. if( token.type != TokenType::Argument )
  7321. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
  7322. assert( !m_ref->isFlag() );
  7323. auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
  7324. auto result = valueRef->setValue( remainingTokens->token );
  7325. if( !result )
  7326. return InternalParseResult( result );
  7327. else
  7328. return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
  7329. }
  7330. };
  7331. inline auto normaliseOpt( std::string const &optName ) -> std::string {
  7332. #ifdef CATCH_PLATFORM_WINDOWS
  7333. if( optName[0] == '/' )
  7334. return "-" + optName.substr( 1 );
  7335. else
  7336. #endif
  7337. return optName;
  7338. }
  7339. class Opt : public ParserRefImpl<Opt> {
  7340. protected:
  7341. std::vector<std::string> m_optNames;
  7342. public:
  7343. template<typename LambdaT>
  7344. explicit Opt( LambdaT const &ref ) : ParserRefImpl( std::make_shared<BoundFlagLambda<LambdaT>>( ref ) ) {}
  7345. explicit Opt( bool &ref ) : ParserRefImpl( std::make_shared<BoundFlagRef>( ref ) ) {}
  7346. template<typename LambdaT>
  7347. Opt( LambdaT const &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  7348. template<typename T>
  7349. Opt( T &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  7350. auto operator[]( std::string const &optName ) -> Opt & {
  7351. m_optNames.push_back( optName );
  7352. return *this;
  7353. }
  7354. auto getHelpColumns() const -> std::vector<HelpColumns> {
  7355. std::ostringstream oss;
  7356. bool first = true;
  7357. for( auto const &opt : m_optNames ) {
  7358. if (first)
  7359. first = false;
  7360. else
  7361. oss << ", ";
  7362. oss << opt;
  7363. }
  7364. if( !m_hint.empty() )
  7365. oss << " <" << m_hint << ">";
  7366. return { { oss.str(), m_description } };
  7367. }
  7368. auto isMatch( std::string const &optToken ) const -> bool {
  7369. auto normalisedToken = normaliseOpt( optToken );
  7370. for( auto const &name : m_optNames ) {
  7371. if( normaliseOpt( name ) == normalisedToken )
  7372. return true;
  7373. }
  7374. return false;
  7375. }
  7376. using ParserBase::parse;
  7377. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  7378. auto validationResult = validate();
  7379. if( !validationResult )
  7380. return InternalParseResult( validationResult );
  7381. auto remainingTokens = tokens;
  7382. if( remainingTokens && remainingTokens->type == TokenType::Option ) {
  7383. auto const &token = *remainingTokens;
  7384. if( isMatch(token.token ) ) {
  7385. if( m_ref->isFlag() ) {
  7386. auto flagRef = static_cast<detail::BoundFlagRefBase*>( m_ref.get() );
  7387. auto result = flagRef->setFlag( true );
  7388. if( !result )
  7389. return InternalParseResult( result );
  7390. if( result.value() == ParseResultType::ShortCircuitAll )
  7391. return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
  7392. } else {
  7393. auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
  7394. ++remainingTokens;
  7395. if( !remainingTokens )
  7396. return InternalParseResult::runtimeError( "Expected argument following " + token.token );
  7397. auto const &argToken = *remainingTokens;
  7398. if( argToken.type != TokenType::Argument )
  7399. return InternalParseResult::runtimeError( "Expected argument following " + token.token );
  7400. auto result = valueRef->setValue( argToken.token );
  7401. if( !result )
  7402. return InternalParseResult( result );
  7403. if( result.value() == ParseResultType::ShortCircuitAll )
  7404. return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
  7405. }
  7406. return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
  7407. }
  7408. }
  7409. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
  7410. }
  7411. auto validate() const -> Result override {
  7412. if( m_optNames.empty() )
  7413. return Result::logicError( "No options supplied to Opt" );
  7414. for( auto const &name : m_optNames ) {
  7415. if( name.empty() )
  7416. return Result::logicError( "Option name cannot be empty" );
  7417. #ifdef CATCH_PLATFORM_WINDOWS
  7418. if( name[0] != '-' && name[0] != '/' )
  7419. return Result::logicError( "Option name must begin with '-' or '/'" );
  7420. #else
  7421. if( name[0] != '-' )
  7422. return Result::logicError( "Option name must begin with '-'" );
  7423. #endif
  7424. }
  7425. return ParserRefImpl::validate();
  7426. }
  7427. };
  7428. struct Help : Opt {
  7429. Help( bool &showHelpFlag )
  7430. : Opt([&]( bool flag ) {
  7431. showHelpFlag = flag;
  7432. return ParserResult::ok( ParseResultType::ShortCircuitAll );
  7433. })
  7434. {
  7435. static_cast<Opt &>( *this )
  7436. ("display usage information")
  7437. ["-?"]["-h"]["--help"]
  7438. .optional();
  7439. }
  7440. };
  7441. struct Parser : ParserBase {
  7442. mutable ExeName m_exeName;
  7443. std::vector<Opt> m_options;
  7444. std::vector<Arg> m_args;
  7445. auto operator|=( ExeName const &exeName ) -> Parser & {
  7446. m_exeName = exeName;
  7447. return *this;
  7448. }
  7449. auto operator|=( Arg const &arg ) -> Parser & {
  7450. m_args.push_back(arg);
  7451. return *this;
  7452. }
  7453. auto operator|=( Opt const &opt ) -> Parser & {
  7454. m_options.push_back(opt);
  7455. return *this;
  7456. }
  7457. auto operator|=( Parser const &other ) -> Parser & {
  7458. m_options.insert(m_options.end(), other.m_options.begin(), other.m_options.end());
  7459. m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end());
  7460. return *this;
  7461. }
  7462. template<typename T>
  7463. auto operator|( T const &other ) const -> Parser {
  7464. return Parser( *this ) |= other;
  7465. }
  7466. // Forward deprecated interface with '+' instead of '|'
  7467. template<typename T>
  7468. auto operator+=( T const &other ) -> Parser & { return operator|=( other ); }
  7469. template<typename T>
  7470. auto operator+( T const &other ) const -> Parser { return operator|( other ); }
  7471. auto getHelpColumns() const -> std::vector<HelpColumns> {
  7472. std::vector<HelpColumns> cols;
  7473. for (auto const &o : m_options) {
  7474. auto childCols = o.getHelpColumns();
  7475. cols.insert( cols.end(), childCols.begin(), childCols.end() );
  7476. }
  7477. return cols;
  7478. }
  7479. void writeToStream( std::ostream &os ) const {
  7480. if (!m_exeName.name().empty()) {
  7481. os << "usage:\n" << " " << m_exeName.name() << " ";
  7482. bool required = true, first = true;
  7483. for( auto const &arg : m_args ) {
  7484. if (first)
  7485. first = false;
  7486. else
  7487. os << " ";
  7488. if( arg.isOptional() && required ) {
  7489. os << "[";
  7490. required = false;
  7491. }
  7492. os << "<" << arg.hint() << ">";
  7493. if( arg.cardinality() == 0 )
  7494. os << " ... ";
  7495. }
  7496. if( !required )
  7497. os << "]";
  7498. if( !m_options.empty() )
  7499. os << " options";
  7500. os << "\n\nwhere options are:" << std::endl;
  7501. }
  7502. auto rows = getHelpColumns();
  7503. size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH;
  7504. size_t optWidth = 0;
  7505. for( auto const &cols : rows )
  7506. optWidth = (std::max)(optWidth, cols.left.size() + 2);
  7507. optWidth = (std::min)(optWidth, consoleWidth/2);
  7508. for( auto const &cols : rows ) {
  7509. auto row =
  7510. TextFlow::Column( cols.left ).width( optWidth ).indent( 2 ) +
  7511. TextFlow::Spacer(4) +
  7512. TextFlow::Column( cols.right ).width( consoleWidth - 7 - optWidth );
  7513. os << row << std::endl;
  7514. }
  7515. }
  7516. friend auto operator<<( std::ostream &os, Parser const &parser ) -> std::ostream& {
  7517. parser.writeToStream( os );
  7518. return os;
  7519. }
  7520. auto validate() const -> Result override {
  7521. for( auto const &opt : m_options ) {
  7522. auto result = opt.validate();
  7523. if( !result )
  7524. return result;
  7525. }
  7526. for( auto const &arg : m_args ) {
  7527. auto result = arg.validate();
  7528. if( !result )
  7529. return result;
  7530. }
  7531. return Result::ok();
  7532. }
  7533. using ParserBase::parse;
  7534. auto parse( std::string const& exeName, TokenStream const &tokens ) const -> InternalParseResult override {
  7535. struct ParserInfo {
  7536. ParserBase const* parser = nullptr;
  7537. size_t count = 0;
  7538. };
  7539. const size_t totalParsers = m_options.size() + m_args.size();
  7540. assert( totalParsers < 512 );
  7541. // ParserInfo parseInfos[totalParsers]; // <-- this is what we really want to do
  7542. ParserInfo parseInfos[512];
  7543. {
  7544. size_t i = 0;
  7545. for (auto const &opt : m_options) parseInfos[i++].parser = &opt;
  7546. for (auto const &arg : m_args) parseInfos[i++].parser = &arg;
  7547. }
  7548. m_exeName.set( exeName );
  7549. auto result = InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
  7550. while( result.value().remainingTokens() ) {
  7551. bool tokenParsed = false;
  7552. for( size_t i = 0; i < totalParsers; ++i ) {
  7553. auto& parseInfo = parseInfos[i];
  7554. if( parseInfo.parser->cardinality() == 0 || parseInfo.count < parseInfo.parser->cardinality() ) {
  7555. result = parseInfo.parser->parse(exeName, result.value().remainingTokens());
  7556. if (!result)
  7557. return result;
  7558. if (result.value().type() != ParseResultType::NoMatch) {
  7559. tokenParsed = true;
  7560. ++parseInfo.count;
  7561. break;
  7562. }
  7563. }
  7564. }
  7565. if( result.value().type() == ParseResultType::ShortCircuitAll )
  7566. return result;
  7567. if( !tokenParsed )
  7568. return InternalParseResult::runtimeError( "Unrecognised token: " + result.value().remainingTokens()->token );
  7569. }
  7570. // !TBD Check missing required options
  7571. return result;
  7572. }
  7573. };
  7574. template<typename DerivedT>
  7575. template<typename T>
  7576. auto ComposableParserImpl<DerivedT>::operator|( T const &other ) const -> Parser {
  7577. return Parser() | static_cast<DerivedT const &>( *this ) | other;
  7578. }
  7579. } // namespace detail
  7580. // A Combined parser
  7581. using detail::Parser;
  7582. // A parser for options
  7583. using detail::Opt;
  7584. // A parser for arguments
  7585. using detail::Arg;
  7586. // Wrapper for argc, argv from main()
  7587. using detail::Args;
  7588. // Specifies the name of the executable
  7589. using detail::ExeName;
  7590. // Convenience wrapper for option parser that specifies the help option
  7591. using detail::Help;
  7592. // enum of result types from a parse
  7593. using detail::ParseResultType;
  7594. // Result type for parser operation
  7595. using detail::ParserResult;
  7596. }} // namespace Catch::clara
  7597. // end clara.hpp
  7598. #ifdef __clang__
  7599. #pragma clang diagnostic pop
  7600. #endif
  7601. // Restore Clara's value for console width, if present
  7602. #ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  7603. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  7604. #undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  7605. #endif
  7606. // end catch_clara.h
  7607. namespace Catch {
  7608. clara::Parser makeCommandLineParser( ConfigData& config );
  7609. } // end namespace Catch
  7610. // end catch_commandline.h
  7611. #include <fstream>
  7612. #include <ctime>
  7613. namespace Catch {
  7614. clara::Parser makeCommandLineParser( ConfigData& config ) {
  7615. using namespace clara;
  7616. auto const setWarning = [&]( std::string const& warning ) {
  7617. auto warningSet = [&]() {
  7618. if( warning == "NoAssertions" )
  7619. return WarnAbout::NoAssertions;
  7620. if ( warning == "NoTests" )
  7621. return WarnAbout::NoTests;
  7622. return WarnAbout::Nothing;
  7623. }();
  7624. if (warningSet == WarnAbout::Nothing)
  7625. return ParserResult::runtimeError( "Unrecognised warning: '" + warning + "'" );
  7626. config.warnings = static_cast<WarnAbout::What>( config.warnings | warningSet );
  7627. return ParserResult::ok( ParseResultType::Matched );
  7628. };
  7629. auto const loadTestNamesFromFile = [&]( std::string const& filename ) {
  7630. std::ifstream f( filename.c_str() );
  7631. if( !f.is_open() )
  7632. return ParserResult::runtimeError( "Unable to load input file: '" + filename + "'" );
  7633. std::string line;
  7634. while( std::getline( f, line ) ) {
  7635. line = trim(line);
  7636. if( !line.empty() && !startsWith( line, '#' ) ) {
  7637. if( !startsWith( line, '"' ) )
  7638. line = '"' + line + '"';
  7639. config.testsOrTags.push_back( line + ',' );
  7640. }
  7641. }
  7642. return ParserResult::ok( ParseResultType::Matched );
  7643. };
  7644. auto const setTestOrder = [&]( std::string const& order ) {
  7645. if( startsWith( "declared", order ) )
  7646. config.runOrder = RunTests::InDeclarationOrder;
  7647. else if( startsWith( "lexical", order ) )
  7648. config.runOrder = RunTests::InLexicographicalOrder;
  7649. else if( startsWith( "random", order ) )
  7650. config.runOrder = RunTests::InRandomOrder;
  7651. else
  7652. return clara::ParserResult::runtimeError( "Unrecognised ordering: '" + order + "'" );
  7653. return ParserResult::ok( ParseResultType::Matched );
  7654. };
  7655. auto const setRngSeed = [&]( std::string const& seed ) {
  7656. if( seed != "time" )
  7657. return clara::detail::convertInto( seed, config.rngSeed );
  7658. config.rngSeed = static_cast<unsigned int>( std::time(nullptr) );
  7659. return ParserResult::ok( ParseResultType::Matched );
  7660. };
  7661. auto const setColourUsage = [&]( std::string const& useColour ) {
  7662. auto mode = toLower( useColour );
  7663. if( mode == "yes" )
  7664. config.useColour = UseColour::Yes;
  7665. else if( mode == "no" )
  7666. config.useColour = UseColour::No;
  7667. else if( mode == "auto" )
  7668. config.useColour = UseColour::Auto;
  7669. else
  7670. return ParserResult::runtimeError( "colour mode must be one of: auto, yes or no. '" + useColour + "' not recognised" );
  7671. return ParserResult::ok( ParseResultType::Matched );
  7672. };
  7673. auto const setWaitForKeypress = [&]( std::string const& keypress ) {
  7674. auto keypressLc = toLower( keypress );
  7675. if( keypressLc == "start" )
  7676. config.waitForKeypress = WaitForKeypress::BeforeStart;
  7677. else if( keypressLc == "exit" )
  7678. config.waitForKeypress = WaitForKeypress::BeforeExit;
  7679. else if( keypressLc == "both" )
  7680. config.waitForKeypress = WaitForKeypress::BeforeStartAndExit;
  7681. else
  7682. return ParserResult::runtimeError( "keypress argument must be one of: start, exit or both. '" + keypress + "' not recognised" );
  7683. return ParserResult::ok( ParseResultType::Matched );
  7684. };
  7685. auto const setVerbosity = [&]( std::string const& verbosity ) {
  7686. auto lcVerbosity = toLower( verbosity );
  7687. if( lcVerbosity == "quiet" )
  7688. config.verbosity = Verbosity::Quiet;
  7689. else if( lcVerbosity == "normal" )
  7690. config.verbosity = Verbosity::Normal;
  7691. else if( lcVerbosity == "high" )
  7692. config.verbosity = Verbosity::High;
  7693. else
  7694. return ParserResult::runtimeError( "Unrecognised verbosity, '" + verbosity + "'" );
  7695. return ParserResult::ok( ParseResultType::Matched );
  7696. };
  7697. auto const setReporter = [&]( std::string const& reporter ) {
  7698. IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
  7699. auto lcReporter = toLower( reporter );
  7700. auto result = factories.find( lcReporter );
  7701. if( factories.end() != result )
  7702. config.reporterName = lcReporter;
  7703. else
  7704. return ParserResult::runtimeError( "Unrecognized reporter, '" + reporter + "'. Check available with --list-reporters" );
  7705. return ParserResult::ok( ParseResultType::Matched );
  7706. };
  7707. auto cli
  7708. = ExeName( config.processName )
  7709. | Help( config.showHelp )
  7710. | Opt( config.listTests )
  7711. ["-l"]["--list-tests"]
  7712. ( "list all/matching test cases" )
  7713. | Opt( config.listTags )
  7714. ["-t"]["--list-tags"]
  7715. ( "list all/matching tags" )
  7716. | Opt( config.showSuccessfulTests )
  7717. ["-s"]["--success"]
  7718. ( "include successful tests in output" )
  7719. | Opt( config.shouldDebugBreak )
  7720. ["-b"]["--break"]
  7721. ( "break into debugger on failure" )
  7722. | Opt( config.noThrow )
  7723. ["-e"]["--nothrow"]
  7724. ( "skip exception tests" )
  7725. | Opt( config.showInvisibles )
  7726. ["-i"]["--invisibles"]
  7727. ( "show invisibles (tabs, newlines)" )
  7728. | Opt( config.outputFilename, "filename" )
  7729. ["-o"]["--out"]
  7730. ( "output filename" )
  7731. | Opt( setReporter, "name" )
  7732. ["-r"]["--reporter"]
  7733. ( "reporter to use (defaults to console)" )
  7734. | Opt( config.name, "name" )
  7735. ["-n"]["--name"]
  7736. ( "suite name" )
  7737. | Opt( [&]( bool ){ config.abortAfter = 1; } )
  7738. ["-a"]["--abort"]
  7739. ( "abort at first failure" )
  7740. | Opt( [&]( int x ){ config.abortAfter = x; }, "no. failures" )
  7741. ["-x"]["--abortx"]
  7742. ( "abort after x failures" )
  7743. | Opt( setWarning, "warning name" )
  7744. ["-w"]["--warn"]
  7745. ( "enable warnings" )
  7746. | Opt( [&]( bool flag ) { config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never; }, "yes|no" )
  7747. ["-d"]["--durations"]
  7748. ( "show test durations" )
  7749. | Opt( loadTestNamesFromFile, "filename" )
  7750. ["-f"]["--input-file"]
  7751. ( "load test names to run from a file" )
  7752. | Opt( config.filenamesAsTags )
  7753. ["-#"]["--filenames-as-tags"]
  7754. ( "adds a tag for the filename" )
  7755. | Opt( config.sectionsToRun, "section name" )
  7756. ["-c"]["--section"]
  7757. ( "specify section to run" )
  7758. | Opt( setVerbosity, "quiet|normal|high" )
  7759. ["-v"]["--verbosity"]
  7760. ( "set output verbosity" )
  7761. | Opt( config.listTestNamesOnly )
  7762. ["--list-test-names-only"]
  7763. ( "list all/matching test cases names only" )
  7764. | Opt( config.listReporters )
  7765. ["--list-reporters"]
  7766. ( "list all reporters" )
  7767. | Opt( setTestOrder, "decl|lex|rand" )
  7768. ["--order"]
  7769. ( "test case order (defaults to decl)" )
  7770. | Opt( setRngSeed, "'time'|number" )
  7771. ["--rng-seed"]
  7772. ( "set a specific seed for random numbers" )
  7773. | Opt( setColourUsage, "yes|no" )
  7774. ["--use-colour"]
  7775. ( "should output be colourised" )
  7776. | Opt( config.libIdentify )
  7777. ["--libidentify"]
  7778. ( "report name and version according to libidentify standard" )
  7779. | Opt( setWaitForKeypress, "start|exit|both" )
  7780. ["--wait-for-keypress"]
  7781. ( "waits for a keypress before exiting" )
  7782. | Opt( config.benchmarkSamples, "samples" )
  7783. ["--benchmark-samples"]
  7784. ( "number of samples to collect (default: 100)" )
  7785. | Opt( config.benchmarkResamples, "resamples" )
  7786. ["--benchmark-resamples"]
  7787. ( "number of resamples for the bootstrap (default: 100000)" )
  7788. | Opt( config.benchmarkConfidenceInterval, "confidence interval" )
  7789. ["--benchmark-confidence-interval"]
  7790. ( "confidence interval for the bootstrap (between 0 and 1, default: 0.95)" )
  7791. | Opt( config.benchmarkNoAnalysis )
  7792. ["--benchmark-no-analysis"]
  7793. ( "perform only measurements; do not perform any analysis" )
  7794. | Arg( config.testsOrTags, "test name|pattern|tags" )
  7795. ( "which test or tests to use" );
  7796. return cli;
  7797. }
  7798. } // end namespace Catch
  7799. // end catch_commandline.cpp
  7800. // start catch_common.cpp
  7801. #include <cstring>
  7802. #include <ostream>
  7803. namespace Catch {
  7804. bool SourceLineInfo::empty() const noexcept {
  7805. return file[0] == '\0';
  7806. }
  7807. bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const noexcept {
  7808. return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0);
  7809. }
  7810. bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const noexcept {
  7811. // We can assume that the same file will usually have the same pointer.
  7812. // Thus, if the pointers are the same, there is no point in calling the strcmp
  7813. return line < other.line || ( line == other.line && file != other.file && (std::strcmp(file, other.file) < 0));
  7814. }
  7815. std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) {
  7816. #ifndef __GNUG__
  7817. os << info.file << '(' << info.line << ')';
  7818. #else
  7819. os << info.file << ':' << info.line;
  7820. #endif
  7821. return os;
  7822. }
  7823. std::string StreamEndStop::operator+() const {
  7824. return std::string();
  7825. }
  7826. NonCopyable::NonCopyable() = default;
  7827. NonCopyable::~NonCopyable() = default;
  7828. }
  7829. // end catch_common.cpp
  7830. // start catch_config.cpp
  7831. namespace Catch {
  7832. Config::Config( ConfigData const& data )
  7833. : m_data( data ),
  7834. m_stream( openStream() )
  7835. {
  7836. TestSpecParser parser(ITagAliasRegistry::get());
  7837. if (!data.testsOrTags.empty()) {
  7838. m_hasTestFilters = true;
  7839. for( auto const& testOrTags : data.testsOrTags )
  7840. parser.parse( testOrTags );
  7841. }
  7842. m_testSpec = parser.testSpec();
  7843. }
  7844. std::string const& Config::getFilename() const {
  7845. return m_data.outputFilename ;
  7846. }
  7847. bool Config::listTests() const { return m_data.listTests; }
  7848. bool Config::listTestNamesOnly() const { return m_data.listTestNamesOnly; }
  7849. bool Config::listTags() const { return m_data.listTags; }
  7850. bool Config::listReporters() const { return m_data.listReporters; }
  7851. std::string Config::getProcessName() const { return m_data.processName; }
  7852. std::string const& Config::getReporterName() const { return m_data.reporterName; }
  7853. std::vector<std::string> const& Config::getTestsOrTags() const { return m_data.testsOrTags; }
  7854. std::vector<std::string> const& Config::getSectionsToRun() const { return m_data.sectionsToRun; }
  7855. TestSpec const& Config::testSpec() const { return m_testSpec; }
  7856. bool Config::hasTestFilters() const { return m_hasTestFilters; }
  7857. bool Config::showHelp() const { return m_data.showHelp; }
  7858. // IConfig interface
  7859. bool Config::allowThrows() const { return !m_data.noThrow; }
  7860. std::ostream& Config::stream() const { return m_stream->stream(); }
  7861. std::string Config::name() const { return m_data.name.empty() ? m_data.processName : m_data.name; }
  7862. bool Config::includeSuccessfulResults() const { return m_data.showSuccessfulTests; }
  7863. bool Config::warnAboutMissingAssertions() const { return !!(m_data.warnings & WarnAbout::NoAssertions); }
  7864. bool Config::warnAboutNoTests() const { return !!(m_data.warnings & WarnAbout::NoTests); }
  7865. ShowDurations::OrNot Config::showDurations() const { return m_data.showDurations; }
  7866. RunTests::InWhatOrder Config::runOrder() const { return m_data.runOrder; }
  7867. unsigned int Config::rngSeed() const { return m_data.rngSeed; }
  7868. UseColour::YesOrNo Config::useColour() const { return m_data.useColour; }
  7869. bool Config::shouldDebugBreak() const { return m_data.shouldDebugBreak; }
  7870. int Config::abortAfter() const { return m_data.abortAfter; }
  7871. bool Config::showInvisibles() const { return m_data.showInvisibles; }
  7872. Verbosity Config::verbosity() const { return m_data.verbosity; }
  7873. bool Config::benchmarkNoAnalysis() const { return m_data.benchmarkNoAnalysis; }
  7874. int Config::benchmarkSamples() const { return m_data.benchmarkSamples; }
  7875. double Config::benchmarkConfidenceInterval() const { return m_data.benchmarkConfidenceInterval; }
  7876. unsigned int Config::benchmarkResamples() const { return m_data.benchmarkResamples; }
  7877. IStream const* Config::openStream() {
  7878. return Catch::makeStream(m_data.outputFilename);
  7879. }
  7880. } // end namespace Catch
  7881. // end catch_config.cpp
  7882. // start catch_console_colour.cpp
  7883. #if defined(__clang__)
  7884. # pragma clang diagnostic push
  7885. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  7886. #endif
  7887. // start catch_errno_guard.h
  7888. namespace Catch {
  7889. class ErrnoGuard {
  7890. public:
  7891. ErrnoGuard();
  7892. ~ErrnoGuard();
  7893. private:
  7894. int m_oldErrno;
  7895. };
  7896. }
  7897. // end catch_errno_guard.h
  7898. #include <sstream>
  7899. namespace Catch {
  7900. namespace {
  7901. struct IColourImpl {
  7902. virtual ~IColourImpl() = default;
  7903. virtual void use( Colour::Code _colourCode ) = 0;
  7904. };
  7905. struct NoColourImpl : IColourImpl {
  7906. void use( Colour::Code ) {}
  7907. static IColourImpl* instance() {
  7908. static NoColourImpl s_instance;
  7909. return &s_instance;
  7910. }
  7911. };
  7912. } // anon namespace
  7913. } // namespace Catch
  7914. #if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI )
  7915. # ifdef CATCH_PLATFORM_WINDOWS
  7916. # define CATCH_CONFIG_COLOUR_WINDOWS
  7917. # else
  7918. # define CATCH_CONFIG_COLOUR_ANSI
  7919. # endif
  7920. #endif
  7921. #if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) /////////////////////////////////////////
  7922. namespace Catch {
  7923. namespace {
  7924. class Win32ColourImpl : public IColourImpl {
  7925. public:
  7926. Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) )
  7927. {
  7928. CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
  7929. GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo );
  7930. originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY );
  7931. originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY );
  7932. }
  7933. void use( Colour::Code _colourCode ) override {
  7934. switch( _colourCode ) {
  7935. case Colour::None: return setTextAttribute( originalForegroundAttributes );
  7936. case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  7937. case Colour::Red: return setTextAttribute( FOREGROUND_RED );
  7938. case Colour::Green: return setTextAttribute( FOREGROUND_GREEN );
  7939. case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE );
  7940. case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN );
  7941. case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN );
  7942. case Colour::Grey: return setTextAttribute( 0 );
  7943. case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY );
  7944. case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED );
  7945. case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN );
  7946. case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  7947. case Colour::BrightYellow: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN );
  7948. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  7949. default:
  7950. CATCH_ERROR( "Unknown colour requested" );
  7951. }
  7952. }
  7953. private:
  7954. void setTextAttribute( WORD _textAttribute ) {
  7955. SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes );
  7956. }
  7957. HANDLE stdoutHandle;
  7958. WORD originalForegroundAttributes;
  7959. WORD originalBackgroundAttributes;
  7960. };
  7961. IColourImpl* platformColourInstance() {
  7962. static Win32ColourImpl s_instance;
  7963. IConfigPtr config = getCurrentContext().getConfig();
  7964. UseColour::YesOrNo colourMode = config
  7965. ? config->useColour()
  7966. : UseColour::Auto;
  7967. if( colourMode == UseColour::Auto )
  7968. colourMode = UseColour::Yes;
  7969. return colourMode == UseColour::Yes
  7970. ? &s_instance
  7971. : NoColourImpl::instance();
  7972. }
  7973. } // end anon namespace
  7974. } // end namespace Catch
  7975. #elif defined( CATCH_CONFIG_COLOUR_ANSI ) //////////////////////////////////////
  7976. #include <unistd.h>
  7977. namespace Catch {
  7978. namespace {
  7979. // use POSIX/ ANSI console terminal codes
  7980. // Thanks to Adam Strzelecki for original contribution
  7981. // (http://github.com/nanoant)
  7982. // https://github.com/philsquared/Catch/pull/131
  7983. class PosixColourImpl : public IColourImpl {
  7984. public:
  7985. void use( Colour::Code _colourCode ) override {
  7986. switch( _colourCode ) {
  7987. case Colour::None:
  7988. case Colour::White: return setColour( "[0m" );
  7989. case Colour::Red: return setColour( "[0;31m" );
  7990. case Colour::Green: return setColour( "[0;32m" );
  7991. case Colour::Blue: return setColour( "[0;34m" );
  7992. case Colour::Cyan: return setColour( "[0;36m" );
  7993. case Colour::Yellow: return setColour( "[0;33m" );
  7994. case Colour::Grey: return setColour( "[1;30m" );
  7995. case Colour::LightGrey: return setColour( "[0;37m" );
  7996. case Colour::BrightRed: return setColour( "[1;31m" );
  7997. case Colour::BrightGreen: return setColour( "[1;32m" );
  7998. case Colour::BrightWhite: return setColour( "[1;37m" );
  7999. case Colour::BrightYellow: return setColour( "[1;33m" );
  8000. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  8001. default: CATCH_INTERNAL_ERROR( "Unknown colour requested" );
  8002. }
  8003. }
  8004. static IColourImpl* instance() {
  8005. static PosixColourImpl s_instance;
  8006. return &s_instance;
  8007. }
  8008. private:
  8009. void setColour( const char* _escapeCode ) {
  8010. getCurrentContext().getConfig()->stream()
  8011. << '\033' << _escapeCode;
  8012. }
  8013. };
  8014. bool useColourOnPlatform() {
  8015. return
  8016. #ifdef CATCH_PLATFORM_MAC
  8017. !isDebuggerActive() &&
  8018. #endif
  8019. #if !(defined(__DJGPP__) && defined(__STRICT_ANSI__))
  8020. isatty(STDOUT_FILENO)
  8021. #else
  8022. false
  8023. #endif
  8024. ;
  8025. }
  8026. IColourImpl* platformColourInstance() {
  8027. ErrnoGuard guard;
  8028. IConfigPtr config = getCurrentContext().getConfig();
  8029. UseColour::YesOrNo colourMode = config
  8030. ? config->useColour()
  8031. : UseColour::Auto;
  8032. if( colourMode == UseColour::Auto )
  8033. colourMode = useColourOnPlatform()
  8034. ? UseColour::Yes
  8035. : UseColour::No;
  8036. return colourMode == UseColour::Yes
  8037. ? PosixColourImpl::instance()
  8038. : NoColourImpl::instance();
  8039. }
  8040. } // end anon namespace
  8041. } // end namespace Catch
  8042. #else // not Windows or ANSI ///////////////////////////////////////////////
  8043. namespace Catch {
  8044. static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); }
  8045. } // end namespace Catch
  8046. #endif // Windows/ ANSI/ None
  8047. namespace Catch {
  8048. Colour::Colour( Code _colourCode ) { use( _colourCode ); }
  8049. Colour::Colour( Colour&& rhs ) noexcept {
  8050. m_moved = rhs.m_moved;
  8051. rhs.m_moved = true;
  8052. }
  8053. Colour& Colour::operator=( Colour&& rhs ) noexcept {
  8054. m_moved = rhs.m_moved;
  8055. rhs.m_moved = true;
  8056. return *this;
  8057. }
  8058. Colour::~Colour(){ if( !m_moved ) use( None ); }
  8059. void Colour::use( Code _colourCode ) {
  8060. static IColourImpl* impl = platformColourInstance();
  8061. // Strictly speaking, this cannot possibly happen.
  8062. // However, under some conditions it does happen (see #1626),
  8063. // and this change is small enough that we can let practicality
  8064. // triumph over purity in this case.
  8065. if (impl != NULL) {
  8066. impl->use( _colourCode );
  8067. }
  8068. }
  8069. std::ostream& operator << ( std::ostream& os, Colour const& ) {
  8070. return os;
  8071. }
  8072. } // end namespace Catch
  8073. #if defined(__clang__)
  8074. # pragma clang diagnostic pop
  8075. #endif
  8076. // end catch_console_colour.cpp
  8077. // start catch_context.cpp
  8078. namespace Catch {
  8079. class Context : public IMutableContext, NonCopyable {
  8080. public: // IContext
  8081. IResultCapture* getResultCapture() override {
  8082. return m_resultCapture;
  8083. }
  8084. IRunner* getRunner() override {
  8085. return m_runner;
  8086. }
  8087. IConfigPtr const& getConfig() const override {
  8088. return m_config;
  8089. }
  8090. ~Context() override;
  8091. public: // IMutableContext
  8092. void setResultCapture( IResultCapture* resultCapture ) override {
  8093. m_resultCapture = resultCapture;
  8094. }
  8095. void setRunner( IRunner* runner ) override {
  8096. m_runner = runner;
  8097. }
  8098. void setConfig( IConfigPtr const& config ) override {
  8099. m_config = config;
  8100. }
  8101. friend IMutableContext& getCurrentMutableContext();
  8102. private:
  8103. IConfigPtr m_config;
  8104. IRunner* m_runner = nullptr;
  8105. IResultCapture* m_resultCapture = nullptr;
  8106. };
  8107. IMutableContext *IMutableContext::currentContext = nullptr;
  8108. void IMutableContext::createContext()
  8109. {
  8110. currentContext = new Context();
  8111. }
  8112. void cleanUpContext() {
  8113. delete IMutableContext::currentContext;
  8114. IMutableContext::currentContext = nullptr;
  8115. }
  8116. IContext::~IContext() = default;
  8117. IMutableContext::~IMutableContext() = default;
  8118. Context::~Context() = default;
  8119. }
  8120. // end catch_context.cpp
  8121. // start catch_debug_console.cpp
  8122. // start catch_debug_console.h
  8123. #include <string>
  8124. namespace Catch {
  8125. void writeToDebugConsole( std::string const& text );
  8126. }
  8127. // end catch_debug_console.h
  8128. #if defined(__ANDROID__)
  8129. #include <android/log.h>
  8130. namespace Catch {
  8131. void writeToDebugConsole( std::string const& text ) {
  8132. __android_log_print( ANDROID_LOG_DEBUG, "Catch", text.c_str() );
  8133. }
  8134. }
  8135. #elif defined(CATCH_PLATFORM_WINDOWS)
  8136. namespace Catch {
  8137. void writeToDebugConsole( std::string const& text ) {
  8138. ::OutputDebugStringA( text.c_str() );
  8139. }
  8140. }
  8141. #else
  8142. namespace Catch {
  8143. void writeToDebugConsole( std::string const& text ) {
  8144. // !TBD: Need a version for Mac/ XCode and other IDEs
  8145. Catch::cout() << text;
  8146. }
  8147. }
  8148. #endif // Platform
  8149. // end catch_debug_console.cpp
  8150. // start catch_debugger.cpp
  8151. #ifdef CATCH_PLATFORM_MAC
  8152. # include <assert.h>
  8153. # include <stdbool.h>
  8154. # include <sys/types.h>
  8155. # include <unistd.h>
  8156. # include <cstddef>
  8157. # include <ostream>
  8158. #ifdef __apple_build_version__
  8159. // These headers will only compile with AppleClang (XCode)
  8160. // For other compilers (Clang, GCC, ... ) we need to exclude them
  8161. # include <sys/sysctl.h>
  8162. #endif
  8163. namespace Catch {
  8164. #ifdef __apple_build_version__
  8165. // The following function is taken directly from the following technical note:
  8166. // https://developer.apple.com/library/archive/qa/qa1361/_index.html
  8167. // Returns true if the current process is being debugged (either
  8168. // running under the debugger or has a debugger attached post facto).
  8169. bool isDebuggerActive(){
  8170. int mib[4];
  8171. struct kinfo_proc info;
  8172. std::size_t size;
  8173. // Initialize the flags so that, if sysctl fails for some bizarre
  8174. // reason, we get a predictable result.
  8175. info.kp_proc.p_flag = 0;
  8176. // Initialize mib, which tells sysctl the info we want, in this case
  8177. // we're looking for information about a specific process ID.
  8178. mib[0] = CTL_KERN;
  8179. mib[1] = KERN_PROC;
  8180. mib[2] = KERN_PROC_PID;
  8181. mib[3] = getpid();
  8182. // Call sysctl.
  8183. size = sizeof(info);
  8184. if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0) != 0 ) {
  8185. Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl;
  8186. return false;
  8187. }
  8188. // We're being debugged if the P_TRACED flag is set.
  8189. return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
  8190. }
  8191. #else
  8192. bool isDebuggerActive() {
  8193. // We need to find another way to determine this for non-appleclang compilers on macOS
  8194. return false;
  8195. }
  8196. #endif
  8197. } // namespace Catch
  8198. #elif defined(CATCH_PLATFORM_LINUX)
  8199. #include <fstream>
  8200. #include <string>
  8201. namespace Catch{
  8202. // The standard POSIX way of detecting a debugger is to attempt to
  8203. // ptrace() the process, but this needs to be done from a child and not
  8204. // this process itself to still allow attaching to this process later
  8205. // if wanted, so is rather heavy. Under Linux we have the PID of the
  8206. // "debugger" (which doesn't need to be gdb, of course, it could also
  8207. // be strace, for example) in /proc/$PID/status, so just get it from
  8208. // there instead.
  8209. bool isDebuggerActive(){
  8210. // Libstdc++ has a bug, where std::ifstream sets errno to 0
  8211. // This way our users can properly assert over errno values
  8212. ErrnoGuard guard;
  8213. std::ifstream in("/proc/self/status");
  8214. for( std::string line; std::getline(in, line); ) {
  8215. static const int PREFIX_LEN = 11;
  8216. if( line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0 ) {
  8217. // We're traced if the PID is not 0 and no other PID starts
  8218. // with 0 digit, so it's enough to check for just a single
  8219. // character.
  8220. return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0';
  8221. }
  8222. }
  8223. return false;
  8224. }
  8225. } // namespace Catch
  8226. #elif defined(_MSC_VER)
  8227. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  8228. namespace Catch {
  8229. bool isDebuggerActive() {
  8230. return IsDebuggerPresent() != 0;
  8231. }
  8232. }
  8233. #elif defined(__MINGW32__)
  8234. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  8235. namespace Catch {
  8236. bool isDebuggerActive() {
  8237. return IsDebuggerPresent() != 0;
  8238. }
  8239. }
  8240. #else
  8241. namespace Catch {
  8242. bool isDebuggerActive() { return false; }
  8243. }
  8244. #endif // Platform
  8245. // end catch_debugger.cpp
  8246. // start catch_decomposer.cpp
  8247. namespace Catch {
  8248. ITransientExpression::~ITransientExpression() = default;
  8249. void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs ) {
  8250. if( lhs.size() + rhs.size() < 40 &&
  8251. lhs.find('\n') == std::string::npos &&
  8252. rhs.find('\n') == std::string::npos )
  8253. os << lhs << " " << op << " " << rhs;
  8254. else
  8255. os << lhs << "\n" << op << "\n" << rhs;
  8256. }
  8257. }
  8258. // end catch_decomposer.cpp
  8259. // start catch_enforce.cpp
  8260. #include <stdexcept>
  8261. namespace Catch {
  8262. #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS_CUSTOM_HANDLER)
  8263. [[noreturn]]
  8264. void throw_exception(std::exception const& e) {
  8265. Catch::cerr() << "Catch will terminate because it needed to throw an exception.\n"
  8266. << "The message was: " << e.what() << '\n';
  8267. std::terminate();
  8268. }
  8269. #endif
  8270. [[noreturn]]
  8271. void throw_logic_error(std::string const& msg) {
  8272. throw_exception(std::logic_error(msg));
  8273. }
  8274. [[noreturn]]
  8275. void throw_domain_error(std::string const& msg) {
  8276. throw_exception(std::domain_error(msg));
  8277. }
  8278. [[noreturn]]
  8279. void throw_runtime_error(std::string const& msg) {
  8280. throw_exception(std::runtime_error(msg));
  8281. }
  8282. } // namespace Catch;
  8283. // end catch_enforce.cpp
  8284. // start catch_enum_values_registry.cpp
  8285. // start catch_enum_values_registry.h
  8286. #include <vector>
  8287. #include <memory>
  8288. namespace Catch {
  8289. namespace Detail {
  8290. std::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int> const& values );
  8291. class EnumValuesRegistry : public IMutableEnumValuesRegistry {
  8292. std::vector<std::unique_ptr<EnumInfo>> m_enumInfos;
  8293. EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::vector<int> const& values) override;
  8294. };
  8295. std::vector<std::string> parseEnums( StringRef enums );
  8296. } // Detail
  8297. } // Catch
  8298. // end catch_enum_values_registry.h
  8299. #include <map>
  8300. #include <cassert>
  8301. namespace Catch {
  8302. IMutableEnumValuesRegistry::~IMutableEnumValuesRegistry() {}
  8303. namespace Detail {
  8304. std::vector<std::string> parseEnums( StringRef enums ) {
  8305. auto enumValues = splitStringRef( enums, ',' );
  8306. std::vector<std::string> parsed;
  8307. parsed.reserve( enumValues.size() );
  8308. for( auto const& enumValue : enumValues ) {
  8309. auto identifiers = splitStringRef( enumValue, ':' );
  8310. parsed.push_back( Catch::trim( identifiers.back() ) );
  8311. }
  8312. return parsed;
  8313. }
  8314. EnumInfo::~EnumInfo() {}
  8315. StringRef EnumInfo::lookup( int value ) const {
  8316. for( auto const& valueToName : m_values ) {
  8317. if( valueToName.first == value )
  8318. return valueToName.second;
  8319. }
  8320. return "{** unexpected enum value **}";
  8321. }
  8322. std::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ) {
  8323. std::unique_ptr<EnumInfo> enumInfo( new EnumInfo );
  8324. enumInfo->m_name = enumName;
  8325. enumInfo->m_values.reserve( values.size() );
  8326. const auto valueNames = Catch::Detail::parseEnums( allValueNames );
  8327. assert( valueNames.size() == values.size() );
  8328. std::size_t i = 0;
  8329. for( auto value : values )
  8330. enumInfo->m_values.push_back({ value, valueNames[i++] });
  8331. return enumInfo;
  8332. }
  8333. EnumInfo const& EnumValuesRegistry::registerEnum( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ) {
  8334. auto enumInfo = makeEnumInfo( enumName, allValueNames, values );
  8335. EnumInfo* raw = enumInfo.get();
  8336. m_enumInfos.push_back( std::move( enumInfo ) );
  8337. return *raw;
  8338. }
  8339. } // Detail
  8340. } // Catch
  8341. // end catch_enum_values_registry.cpp
  8342. // start catch_errno_guard.cpp
  8343. #include <cerrno>
  8344. namespace Catch {
  8345. ErrnoGuard::ErrnoGuard():m_oldErrno(errno){}
  8346. ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; }
  8347. }
  8348. // end catch_errno_guard.cpp
  8349. // start catch_exception_translator_registry.cpp
  8350. // start catch_exception_translator_registry.h
  8351. #include <vector>
  8352. #include <string>
  8353. #include <memory>
  8354. namespace Catch {
  8355. class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry {
  8356. public:
  8357. ~ExceptionTranslatorRegistry();
  8358. virtual void registerTranslator( const IExceptionTranslator* translator );
  8359. std::string translateActiveException() const override;
  8360. std::string tryTranslators() const;
  8361. private:
  8362. std::vector<std::unique_ptr<IExceptionTranslator const>> m_translators;
  8363. };
  8364. }
  8365. // end catch_exception_translator_registry.h
  8366. #ifdef __OBJC__
  8367. #import "Foundation/Foundation.h"
  8368. #endif
  8369. namespace Catch {
  8370. ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {
  8371. }
  8372. void ExceptionTranslatorRegistry::registerTranslator( const IExceptionTranslator* translator ) {
  8373. m_translators.push_back( std::unique_ptr<const IExceptionTranslator>( translator ) );
  8374. }
  8375. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  8376. std::string ExceptionTranslatorRegistry::translateActiveException() const {
  8377. try {
  8378. #ifdef __OBJC__
  8379. // In Objective-C try objective-c exceptions first
  8380. @try {
  8381. return tryTranslators();
  8382. }
  8383. @catch (NSException *exception) {
  8384. return Catch::Detail::stringify( [exception description] );
  8385. }
  8386. #else
  8387. // Compiling a mixed mode project with MSVC means that CLR
  8388. // exceptions will be caught in (...) as well. However, these
  8389. // do not fill-in std::current_exception and thus lead to crash
  8390. // when attempting rethrow.
  8391. // /EHa switch also causes structured exceptions to be caught
  8392. // here, but they fill-in current_exception properly, so
  8393. // at worst the output should be a little weird, instead of
  8394. // causing a crash.
  8395. if (std::current_exception() == nullptr) {
  8396. return "Non C++ exception. Possibly a CLR exception.";
  8397. }
  8398. return tryTranslators();
  8399. #endif
  8400. }
  8401. catch( TestFailureException& ) {
  8402. std::rethrow_exception(std::current_exception());
  8403. }
  8404. catch( std::exception& ex ) {
  8405. return ex.what();
  8406. }
  8407. catch( std::string& msg ) {
  8408. return msg;
  8409. }
  8410. catch( const char* msg ) {
  8411. return msg;
  8412. }
  8413. catch(...) {
  8414. return "Unknown exception";
  8415. }
  8416. }
  8417. std::string ExceptionTranslatorRegistry::tryTranslators() const {
  8418. if (m_translators.empty()) {
  8419. std::rethrow_exception(std::current_exception());
  8420. } else {
  8421. return m_translators[0]->translate(m_translators.begin() + 1, m_translators.end());
  8422. }
  8423. }
  8424. #else // ^^ Exceptions are enabled // Exceptions are disabled vv
  8425. std::string ExceptionTranslatorRegistry::translateActiveException() const {
  8426. CATCH_INTERNAL_ERROR("Attempted to translate active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
  8427. }
  8428. std::string ExceptionTranslatorRegistry::tryTranslators() const {
  8429. CATCH_INTERNAL_ERROR("Attempted to use exception translators under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
  8430. }
  8431. #endif
  8432. }
  8433. // end catch_exception_translator_registry.cpp
  8434. // start catch_fatal_condition.cpp
  8435. #if defined(__GNUC__)
  8436. # pragma GCC diagnostic push
  8437. # pragma GCC diagnostic ignored "-Wmissing-field-initializers"
  8438. #endif
  8439. #if defined( CATCH_CONFIG_WINDOWS_SEH ) || defined( CATCH_CONFIG_POSIX_SIGNALS )
  8440. namespace {
  8441. // Report the error condition
  8442. void reportFatal( char const * const message ) {
  8443. Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition( message );
  8444. }
  8445. }
  8446. #endif // signals/SEH handling
  8447. #if defined( CATCH_CONFIG_WINDOWS_SEH )
  8448. namespace Catch {
  8449. struct SignalDefs { DWORD id; const char* name; };
  8450. // There is no 1-1 mapping between signals and windows exceptions.
  8451. // Windows can easily distinguish between SO and SigSegV,
  8452. // but SigInt, SigTerm, etc are handled differently.
  8453. static SignalDefs signalDefs[] = {
  8454. { static_cast<DWORD>(EXCEPTION_ILLEGAL_INSTRUCTION), "SIGILL - Illegal instruction signal" },
  8455. { static_cast<DWORD>(EXCEPTION_STACK_OVERFLOW), "SIGSEGV - Stack overflow" },
  8456. { static_cast<DWORD>(EXCEPTION_ACCESS_VIOLATION), "SIGSEGV - Segmentation violation signal" },
  8457. { static_cast<DWORD>(EXCEPTION_INT_DIVIDE_BY_ZERO), "Divide by zero error" },
  8458. };
  8459. LONG CALLBACK FatalConditionHandler::handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {
  8460. for (auto const& def : signalDefs) {
  8461. if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) {
  8462. reportFatal(def.name);
  8463. }
  8464. }
  8465. // If its not an exception we care about, pass it along.
  8466. // This stops us from eating debugger breaks etc.
  8467. return EXCEPTION_CONTINUE_SEARCH;
  8468. }
  8469. FatalConditionHandler::FatalConditionHandler() {
  8470. isSet = true;
  8471. // 32k seems enough for Catch to handle stack overflow,
  8472. // but the value was found experimentally, so there is no strong guarantee
  8473. guaranteeSize = 32 * 1024;
  8474. exceptionHandlerHandle = nullptr;
  8475. // Register as first handler in current chain
  8476. exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);
  8477. // Pass in guarantee size to be filled
  8478. SetThreadStackGuarantee(&guaranteeSize);
  8479. }
  8480. void FatalConditionHandler::reset() {
  8481. if (isSet) {
  8482. RemoveVectoredExceptionHandler(exceptionHandlerHandle);
  8483. SetThreadStackGuarantee(&guaranteeSize);
  8484. exceptionHandlerHandle = nullptr;
  8485. isSet = false;
  8486. }
  8487. }
  8488. FatalConditionHandler::~FatalConditionHandler() {
  8489. reset();
  8490. }
  8491. bool FatalConditionHandler::isSet = false;
  8492. ULONG FatalConditionHandler::guaranteeSize = 0;
  8493. PVOID FatalConditionHandler::exceptionHandlerHandle = nullptr;
  8494. } // namespace Catch
  8495. #elif defined( CATCH_CONFIG_POSIX_SIGNALS )
  8496. namespace Catch {
  8497. struct SignalDefs {
  8498. int id;
  8499. const char* name;
  8500. };
  8501. // 32kb for the alternate stack seems to be sufficient. However, this value
  8502. // is experimentally determined, so that's not guaranteed.
  8503. static constexpr std::size_t sigStackSize = 32768 >= MINSIGSTKSZ ? 32768 : MINSIGSTKSZ;
  8504. static SignalDefs signalDefs[] = {
  8505. { SIGINT, "SIGINT - Terminal interrupt signal" },
  8506. { SIGILL, "SIGILL - Illegal instruction signal" },
  8507. { SIGFPE, "SIGFPE - Floating point error signal" },
  8508. { SIGSEGV, "SIGSEGV - Segmentation violation signal" },
  8509. { SIGTERM, "SIGTERM - Termination request signal" },
  8510. { SIGABRT, "SIGABRT - Abort (abnormal termination) signal" }
  8511. };
  8512. void FatalConditionHandler::handleSignal( int sig ) {
  8513. char const * name = "<unknown signal>";
  8514. for (auto const& def : signalDefs) {
  8515. if (sig == def.id) {
  8516. name = def.name;
  8517. break;
  8518. }
  8519. }
  8520. reset();
  8521. reportFatal(name);
  8522. raise( sig );
  8523. }
  8524. FatalConditionHandler::FatalConditionHandler() {
  8525. isSet = true;
  8526. stack_t sigStack;
  8527. sigStack.ss_sp = altStackMem;
  8528. sigStack.ss_size = sigStackSize;
  8529. sigStack.ss_flags = 0;
  8530. sigaltstack(&sigStack, &oldSigStack);
  8531. struct sigaction sa = { };
  8532. sa.sa_handler = handleSignal;
  8533. sa.sa_flags = SA_ONSTACK;
  8534. for (std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i) {
  8535. sigaction(signalDefs[i].id, &sa, &oldSigActions[i]);
  8536. }
  8537. }
  8538. FatalConditionHandler::~FatalConditionHandler() {
  8539. reset();
  8540. }
  8541. void FatalConditionHandler::reset() {
  8542. if( isSet ) {
  8543. // Set signals back to previous values -- hopefully nobody overwrote them in the meantime
  8544. for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) {
  8545. sigaction(signalDefs[i].id, &oldSigActions[i], nullptr);
  8546. }
  8547. // Return the old stack
  8548. sigaltstack(&oldSigStack, nullptr);
  8549. isSet = false;
  8550. }
  8551. }
  8552. bool FatalConditionHandler::isSet = false;
  8553. struct sigaction FatalConditionHandler::oldSigActions[sizeof(signalDefs)/sizeof(SignalDefs)] = {};
  8554. stack_t FatalConditionHandler::oldSigStack = {};
  8555. char FatalConditionHandler::altStackMem[sigStackSize] = {};
  8556. } // namespace Catch
  8557. #else
  8558. namespace Catch {
  8559. void FatalConditionHandler::reset() {}
  8560. }
  8561. #endif // signals/SEH handling
  8562. #if defined(__GNUC__)
  8563. # pragma GCC diagnostic pop
  8564. #endif
  8565. // end catch_fatal_condition.cpp
  8566. // start catch_generators.cpp
  8567. // start catch_random_number_generator.h
  8568. #include <algorithm>
  8569. #include <random>
  8570. namespace Catch {
  8571. struct IConfig;
  8572. std::mt19937& rng();
  8573. void seedRng( IConfig const& config );
  8574. unsigned int rngSeed();
  8575. }
  8576. // end catch_random_number_generator.h
  8577. #include <limits>
  8578. #include <set>
  8579. namespace Catch {
  8580. IGeneratorTracker::~IGeneratorTracker() {}
  8581. const char* GeneratorException::what() const noexcept {
  8582. return m_msg;
  8583. }
  8584. namespace Generators {
  8585. GeneratorUntypedBase::~GeneratorUntypedBase() {}
  8586. auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
  8587. return getResultCapture().acquireGeneratorTracker( lineInfo );
  8588. }
  8589. } // namespace Generators
  8590. } // namespace Catch
  8591. // end catch_generators.cpp
  8592. // start catch_interfaces_capture.cpp
  8593. namespace Catch {
  8594. IResultCapture::~IResultCapture() = default;
  8595. }
  8596. // end catch_interfaces_capture.cpp
  8597. // start catch_interfaces_config.cpp
  8598. namespace Catch {
  8599. IConfig::~IConfig() = default;
  8600. }
  8601. // end catch_interfaces_config.cpp
  8602. // start catch_interfaces_exception.cpp
  8603. namespace Catch {
  8604. IExceptionTranslator::~IExceptionTranslator() = default;
  8605. IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() = default;
  8606. }
  8607. // end catch_interfaces_exception.cpp
  8608. // start catch_interfaces_registry_hub.cpp
  8609. namespace Catch {
  8610. IRegistryHub::~IRegistryHub() = default;
  8611. IMutableRegistryHub::~IMutableRegistryHub() = default;
  8612. }
  8613. // end catch_interfaces_registry_hub.cpp
  8614. // start catch_interfaces_reporter.cpp
  8615. // start catch_reporter_listening.h
  8616. namespace Catch {
  8617. class ListeningReporter : public IStreamingReporter {
  8618. using Reporters = std::vector<IStreamingReporterPtr>;
  8619. Reporters m_listeners;
  8620. IStreamingReporterPtr m_reporter = nullptr;
  8621. ReporterPreferences m_preferences;
  8622. public:
  8623. ListeningReporter();
  8624. void addListener( IStreamingReporterPtr&& listener );
  8625. void addReporter( IStreamingReporterPtr&& reporter );
  8626. public: // IStreamingReporter
  8627. ReporterPreferences getPreferences() const override;
  8628. void noMatchingTestCases( std::string const& spec ) override;
  8629. static std::set<Verbosity> getSupportedVerbosities();
  8630. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  8631. void benchmarkPreparing(std::string const& name) override;
  8632. void benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) override;
  8633. void benchmarkEnded( BenchmarkStats<> const& benchmarkStats ) override;
  8634. void benchmarkFailed(std::string const&) override;
  8635. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  8636. void testRunStarting( TestRunInfo const& testRunInfo ) override;
  8637. void testGroupStarting( GroupInfo const& groupInfo ) override;
  8638. void testCaseStarting( TestCaseInfo const& testInfo ) override;
  8639. void sectionStarting( SectionInfo const& sectionInfo ) override;
  8640. void assertionStarting( AssertionInfo const& assertionInfo ) override;
  8641. // The return value indicates if the messages buffer should be cleared:
  8642. bool assertionEnded( AssertionStats const& assertionStats ) override;
  8643. void sectionEnded( SectionStats const& sectionStats ) override;
  8644. void testCaseEnded( TestCaseStats const& testCaseStats ) override;
  8645. void testGroupEnded( TestGroupStats const& testGroupStats ) override;
  8646. void testRunEnded( TestRunStats const& testRunStats ) override;
  8647. void skipTest( TestCaseInfo const& testInfo ) override;
  8648. bool isMulti() const override;
  8649. };
  8650. } // end namespace Catch
  8651. // end catch_reporter_listening.h
  8652. namespace Catch {
  8653. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig )
  8654. : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {}
  8655. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream )
  8656. : m_stream( &_stream ), m_fullConfig( _fullConfig ) {}
  8657. std::ostream& ReporterConfig::stream() const { return *m_stream; }
  8658. IConfigPtr ReporterConfig::fullConfig() const { return m_fullConfig; }
  8659. TestRunInfo::TestRunInfo( std::string const& _name ) : name( _name ) {}
  8660. GroupInfo::GroupInfo( std::string const& _name,
  8661. std::size_t _groupIndex,
  8662. std::size_t _groupsCount )
  8663. : name( _name ),
  8664. groupIndex( _groupIndex ),
  8665. groupsCounts( _groupsCount )
  8666. {}
  8667. AssertionStats::AssertionStats( AssertionResult const& _assertionResult,
  8668. std::vector<MessageInfo> const& _infoMessages,
  8669. Totals const& _totals )
  8670. : assertionResult( _assertionResult ),
  8671. infoMessages( _infoMessages ),
  8672. totals( _totals )
  8673. {
  8674. assertionResult.m_resultData.lazyExpression.m_transientExpression = _assertionResult.m_resultData.lazyExpression.m_transientExpression;
  8675. if( assertionResult.hasMessage() ) {
  8676. // Copy message into messages list.
  8677. // !TBD This should have been done earlier, somewhere
  8678. MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() );
  8679. builder << assertionResult.getMessage();
  8680. builder.m_info.message = builder.m_stream.str();
  8681. infoMessages.push_back( builder.m_info );
  8682. }
  8683. }
  8684. AssertionStats::~AssertionStats() = default;
  8685. SectionStats::SectionStats( SectionInfo const& _sectionInfo,
  8686. Counts const& _assertions,
  8687. double _durationInSeconds,
  8688. bool _missingAssertions )
  8689. : sectionInfo( _sectionInfo ),
  8690. assertions( _assertions ),
  8691. durationInSeconds( _durationInSeconds ),
  8692. missingAssertions( _missingAssertions )
  8693. {}
  8694. SectionStats::~SectionStats() = default;
  8695. TestCaseStats::TestCaseStats( TestCaseInfo const& _testInfo,
  8696. Totals const& _totals,
  8697. std::string const& _stdOut,
  8698. std::string const& _stdErr,
  8699. bool _aborting )
  8700. : testInfo( _testInfo ),
  8701. totals( _totals ),
  8702. stdOut( _stdOut ),
  8703. stdErr( _stdErr ),
  8704. aborting( _aborting )
  8705. {}
  8706. TestCaseStats::~TestCaseStats() = default;
  8707. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo,
  8708. Totals const& _totals,
  8709. bool _aborting )
  8710. : groupInfo( _groupInfo ),
  8711. totals( _totals ),
  8712. aborting( _aborting )
  8713. {}
  8714. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo )
  8715. : groupInfo( _groupInfo ),
  8716. aborting( false )
  8717. {}
  8718. TestGroupStats::~TestGroupStats() = default;
  8719. TestRunStats::TestRunStats( TestRunInfo const& _runInfo,
  8720. Totals const& _totals,
  8721. bool _aborting )
  8722. : runInfo( _runInfo ),
  8723. totals( _totals ),
  8724. aborting( _aborting )
  8725. {}
  8726. TestRunStats::~TestRunStats() = default;
  8727. void IStreamingReporter::fatalErrorEncountered( StringRef ) {}
  8728. bool IStreamingReporter::isMulti() const { return false; }
  8729. IReporterFactory::~IReporterFactory() = default;
  8730. IReporterRegistry::~IReporterRegistry() = default;
  8731. } // end namespace Catch
  8732. // end catch_interfaces_reporter.cpp
  8733. // start catch_interfaces_runner.cpp
  8734. namespace Catch {
  8735. IRunner::~IRunner() = default;
  8736. }
  8737. // end catch_interfaces_runner.cpp
  8738. // start catch_interfaces_testcase.cpp
  8739. namespace Catch {
  8740. ITestInvoker::~ITestInvoker() = default;
  8741. ITestCaseRegistry::~ITestCaseRegistry() = default;
  8742. }
  8743. // end catch_interfaces_testcase.cpp
  8744. // start catch_leak_detector.cpp
  8745. #ifdef CATCH_CONFIG_WINDOWS_CRTDBG
  8746. #include <crtdbg.h>
  8747. namespace Catch {
  8748. LeakDetector::LeakDetector() {
  8749. int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
  8750. flag |= _CRTDBG_LEAK_CHECK_DF;
  8751. flag |= _CRTDBG_ALLOC_MEM_DF;
  8752. _CrtSetDbgFlag(flag);
  8753. _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
  8754. _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
  8755. // Change this to leaking allocation's number to break there
  8756. _CrtSetBreakAlloc(-1);
  8757. }
  8758. }
  8759. #else
  8760. Catch::LeakDetector::LeakDetector() {}
  8761. #endif
  8762. Catch::LeakDetector::~LeakDetector() {
  8763. Catch::cleanUp();
  8764. }
  8765. // end catch_leak_detector.cpp
  8766. // start catch_list.cpp
  8767. // start catch_list.h
  8768. #include <set>
  8769. namespace Catch {
  8770. std::size_t listTests( Config const& config );
  8771. std::size_t listTestsNamesOnly( Config const& config );
  8772. struct TagInfo {
  8773. void add( std::string const& spelling );
  8774. std::string all() const;
  8775. std::set<std::string> spellings;
  8776. std::size_t count = 0;
  8777. };
  8778. std::size_t listTags( Config const& config );
  8779. std::size_t listReporters();
  8780. Option<std::size_t> list( std::shared_ptr<Config> const& config );
  8781. } // end namespace Catch
  8782. // end catch_list.h
  8783. // start catch_text.h
  8784. namespace Catch {
  8785. using namespace clara::TextFlow;
  8786. }
  8787. // end catch_text.h
  8788. #include <limits>
  8789. #include <algorithm>
  8790. #include <iomanip>
  8791. namespace Catch {
  8792. std::size_t listTests( Config const& config ) {
  8793. TestSpec testSpec = config.testSpec();
  8794. if( config.hasTestFilters() )
  8795. Catch::cout() << "Matching test cases:\n";
  8796. else {
  8797. Catch::cout() << "All available test cases:\n";
  8798. }
  8799. auto matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  8800. for( auto const& testCaseInfo : matchedTestCases ) {
  8801. Colour::Code colour = testCaseInfo.isHidden()
  8802. ? Colour::SecondaryText
  8803. : Colour::None;
  8804. Colour colourGuard( colour );
  8805. Catch::cout() << Column( testCaseInfo.name ).initialIndent( 2 ).indent( 4 ) << "\n";
  8806. if( config.verbosity() >= Verbosity::High ) {
  8807. Catch::cout() << Column( Catch::Detail::stringify( testCaseInfo.lineInfo ) ).indent(4) << std::endl;
  8808. std::string description = testCaseInfo.description;
  8809. if( description.empty() )
  8810. description = "(NO DESCRIPTION)";
  8811. Catch::cout() << Column( description ).indent(4) << std::endl;
  8812. }
  8813. if( !testCaseInfo.tags.empty() )
  8814. Catch::cout() << Column( testCaseInfo.tagsAsString() ).indent( 6 ) << "\n";
  8815. }
  8816. if( !config.hasTestFilters() )
  8817. Catch::cout() << pluralise( matchedTestCases.size(), "test case" ) << '\n' << std::endl;
  8818. else
  8819. Catch::cout() << pluralise( matchedTestCases.size(), "matching test case" ) << '\n' << std::endl;
  8820. return matchedTestCases.size();
  8821. }
  8822. std::size_t listTestsNamesOnly( Config const& config ) {
  8823. TestSpec testSpec = config.testSpec();
  8824. std::size_t matchedTests = 0;
  8825. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  8826. for( auto const& testCaseInfo : matchedTestCases ) {
  8827. matchedTests++;
  8828. if( startsWith( testCaseInfo.name, '#' ) )
  8829. Catch::cout() << '"' << testCaseInfo.name << '"';
  8830. else
  8831. Catch::cout() << testCaseInfo.name;
  8832. if ( config.verbosity() >= Verbosity::High )
  8833. Catch::cout() << "\t@" << testCaseInfo.lineInfo;
  8834. Catch::cout() << std::endl;
  8835. }
  8836. return matchedTests;
  8837. }
  8838. void TagInfo::add( std::string const& spelling ) {
  8839. ++count;
  8840. spellings.insert( spelling );
  8841. }
  8842. std::string TagInfo::all() const {
  8843. size_t size = 0;
  8844. for (auto const& spelling : spellings) {
  8845. // Add 2 for the brackes
  8846. size += spelling.size() + 2;
  8847. }
  8848. std::string out; out.reserve(size);
  8849. for (auto const& spelling : spellings) {
  8850. out += '[';
  8851. out += spelling;
  8852. out += ']';
  8853. }
  8854. return out;
  8855. }
  8856. std::size_t listTags( Config const& config ) {
  8857. TestSpec testSpec = config.testSpec();
  8858. if( config.hasTestFilters() )
  8859. Catch::cout() << "Tags for matching test cases:\n";
  8860. else {
  8861. Catch::cout() << "All available tags:\n";
  8862. }
  8863. std::map<std::string, TagInfo> tagCounts;
  8864. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  8865. for( auto const& testCase : matchedTestCases ) {
  8866. for( auto const& tagName : testCase.getTestCaseInfo().tags ) {
  8867. std::string lcaseTagName = toLower( tagName );
  8868. auto countIt = tagCounts.find( lcaseTagName );
  8869. if( countIt == tagCounts.end() )
  8870. countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first;
  8871. countIt->second.add( tagName );
  8872. }
  8873. }
  8874. for( auto const& tagCount : tagCounts ) {
  8875. ReusableStringStream rss;
  8876. rss << " " << std::setw(2) << tagCount.second.count << " ";
  8877. auto str = rss.str();
  8878. auto wrapper = Column( tagCount.second.all() )
  8879. .initialIndent( 0 )
  8880. .indent( str.size() )
  8881. .width( CATCH_CONFIG_CONSOLE_WIDTH-10 );
  8882. Catch::cout() << str << wrapper << '\n';
  8883. }
  8884. Catch::cout() << pluralise( tagCounts.size(), "tag" ) << '\n' << std::endl;
  8885. return tagCounts.size();
  8886. }
  8887. std::size_t listReporters() {
  8888. Catch::cout() << "Available reporters:\n";
  8889. IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
  8890. std::size_t maxNameLen = 0;
  8891. for( auto const& factoryKvp : factories )
  8892. maxNameLen = (std::max)( maxNameLen, factoryKvp.first.size() );
  8893. for( auto const& factoryKvp : factories ) {
  8894. Catch::cout()
  8895. << Column( factoryKvp.first + ":" )
  8896. .indent(2)
  8897. .width( 5+maxNameLen )
  8898. + Column( factoryKvp.second->getDescription() )
  8899. .initialIndent(0)
  8900. .indent(2)
  8901. .width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 )
  8902. << "\n";
  8903. }
  8904. Catch::cout() << std::endl;
  8905. return factories.size();
  8906. }
  8907. Option<std::size_t> list( std::shared_ptr<Config> const& config ) {
  8908. Option<std::size_t> listedCount;
  8909. getCurrentMutableContext().setConfig( config );
  8910. if( config->listTests() )
  8911. listedCount = listedCount.valueOr(0) + listTests( *config );
  8912. if( config->listTestNamesOnly() )
  8913. listedCount = listedCount.valueOr(0) + listTestsNamesOnly( *config );
  8914. if( config->listTags() )
  8915. listedCount = listedCount.valueOr(0) + listTags( *config );
  8916. if( config->listReporters() )
  8917. listedCount = listedCount.valueOr(0) + listReporters();
  8918. return listedCount;
  8919. }
  8920. } // end namespace Catch
  8921. // end catch_list.cpp
  8922. // start catch_matchers.cpp
  8923. namespace Catch {
  8924. namespace Matchers {
  8925. namespace Impl {
  8926. std::string MatcherUntypedBase::toString() const {
  8927. if( m_cachedToString.empty() )
  8928. m_cachedToString = describe();
  8929. return m_cachedToString;
  8930. }
  8931. MatcherUntypedBase::~MatcherUntypedBase() = default;
  8932. } // namespace Impl
  8933. } // namespace Matchers
  8934. using namespace Matchers;
  8935. using Matchers::Impl::MatcherBase;
  8936. } // namespace Catch
  8937. // end catch_matchers.cpp
  8938. // start catch_matchers_floating.cpp
  8939. // start catch_polyfills.hpp
  8940. namespace Catch {
  8941. bool isnan(float f);
  8942. bool isnan(double d);
  8943. }
  8944. // end catch_polyfills.hpp
  8945. // start catch_to_string.hpp
  8946. #include <string>
  8947. namespace Catch {
  8948. template <typename T>
  8949. std::string to_string(T const& t) {
  8950. #if defined(CATCH_CONFIG_CPP11_TO_STRING)
  8951. return std::to_string(t);
  8952. #else
  8953. ReusableStringStream rss;
  8954. rss << t;
  8955. return rss.str();
  8956. #endif
  8957. }
  8958. } // end namespace Catch
  8959. // end catch_to_string.hpp
  8960. #include <cstdlib>
  8961. #include <cstdint>
  8962. #include <cstring>
  8963. #include <sstream>
  8964. #include <iomanip>
  8965. #include <limits>
  8966. namespace Catch {
  8967. namespace Matchers {
  8968. namespace Floating {
  8969. enum class FloatingPointKind : uint8_t {
  8970. Float,
  8971. Double
  8972. };
  8973. }
  8974. }
  8975. }
  8976. namespace {
  8977. template <typename T>
  8978. struct Converter;
  8979. template <>
  8980. struct Converter<float> {
  8981. static_assert(sizeof(float) == sizeof(int32_t), "Important ULP matcher assumption violated");
  8982. Converter(float f) {
  8983. std::memcpy(&i, &f, sizeof(f));
  8984. }
  8985. int32_t i;
  8986. };
  8987. template <>
  8988. struct Converter<double> {
  8989. static_assert(sizeof(double) == sizeof(int64_t), "Important ULP matcher assumption violated");
  8990. Converter(double d) {
  8991. std::memcpy(&i, &d, sizeof(d));
  8992. }
  8993. int64_t i;
  8994. };
  8995. template <typename T>
  8996. auto convert(T t) -> Converter<T> {
  8997. return Converter<T>(t);
  8998. }
  8999. template <typename FP>
  9000. bool almostEqualUlps(FP lhs, FP rhs, int maxUlpDiff) {
  9001. // Comparison with NaN should always be false.
  9002. // This way we can rule it out before getting into the ugly details
  9003. if (Catch::isnan(lhs) || Catch::isnan(rhs)) {
  9004. return false;
  9005. }
  9006. auto lc = convert(lhs);
  9007. auto rc = convert(rhs);
  9008. if ((lc.i < 0) != (rc.i < 0)) {
  9009. // Potentially we can have +0 and -0
  9010. return lhs == rhs;
  9011. }
  9012. auto ulpDiff = std::abs(lc.i - rc.i);
  9013. return ulpDiff <= maxUlpDiff;
  9014. }
  9015. template <typename FP>
  9016. FP step(FP start, FP direction, int steps) {
  9017. for (int i = 0; i < steps; ++i) {
  9018. start = std::nextafter(start, direction);
  9019. }
  9020. return start;
  9021. }
  9022. } // end anonymous namespace
  9023. namespace Catch {
  9024. namespace Matchers {
  9025. namespace Floating {
  9026. WithinAbsMatcher::WithinAbsMatcher(double target, double margin)
  9027. :m_target{ target }, m_margin{ margin } {
  9028. CATCH_ENFORCE(margin >= 0, "Invalid margin: " << margin << '.'
  9029. << " Margin has to be non-negative.");
  9030. }
  9031. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  9032. // But without the subtraction to allow for INFINITY in comparison
  9033. bool WithinAbsMatcher::match(double const& matchee) const {
  9034. return (matchee + m_margin >= m_target) && (m_target + m_margin >= matchee);
  9035. }
  9036. std::string WithinAbsMatcher::describe() const {
  9037. return "is within " + ::Catch::Detail::stringify(m_margin) + " of " + ::Catch::Detail::stringify(m_target);
  9038. }
  9039. WithinUlpsMatcher::WithinUlpsMatcher(double target, int ulps, FloatingPointKind baseType)
  9040. :m_target{ target }, m_ulps{ ulps }, m_type{ baseType } {
  9041. CATCH_ENFORCE(ulps >= 0, "Invalid ULP setting: " << ulps << '.'
  9042. << " ULPs have to be non-negative.");
  9043. }
  9044. #if defined(__clang__)
  9045. #pragma clang diagnostic push
  9046. // Clang <3.5 reports on the default branch in the switch below
  9047. #pragma clang diagnostic ignored "-Wunreachable-code"
  9048. #endif
  9049. bool WithinUlpsMatcher::match(double const& matchee) const {
  9050. switch (m_type) {
  9051. case FloatingPointKind::Float:
  9052. return almostEqualUlps<float>(static_cast<float>(matchee), static_cast<float>(m_target), m_ulps);
  9053. case FloatingPointKind::Double:
  9054. return almostEqualUlps<double>(matchee, m_target, m_ulps);
  9055. default:
  9056. CATCH_INTERNAL_ERROR( "Unknown FloatingPointKind value" );
  9057. }
  9058. }
  9059. #if defined(__clang__)
  9060. #pragma clang diagnostic pop
  9061. #endif
  9062. std::string WithinUlpsMatcher::describe() const {
  9063. std::stringstream ret;
  9064. ret << "is within " << m_ulps << " ULPs of " << ::Catch::Detail::stringify(m_target);
  9065. if (m_type == FloatingPointKind::Float) {
  9066. ret << 'f';
  9067. }
  9068. ret << " ([";
  9069. ret << std::fixed << std::setprecision(std::numeric_limits<double>::max_digits10);
  9070. if (m_type == FloatingPointKind::Double) {
  9071. ret << step(m_target, static_cast<double>(-INFINITY), m_ulps)
  9072. << ", "
  9073. << step(m_target, static_cast<double>(INFINITY), m_ulps);
  9074. } else {
  9075. ret << step<float>(static_cast<float>(m_target), -INFINITY, m_ulps)
  9076. << ", "
  9077. << step<float>(static_cast<float>(m_target), INFINITY, m_ulps);
  9078. }
  9079. ret << "])";
  9080. return ret.str();
  9081. //return "is within " + Catch::to_string(m_ulps) + " ULPs of " + ::Catch::Detail::stringify(m_target) + ((m_type == FloatingPointKind::Float)? "f" : "");
  9082. }
  9083. }// namespace Floating
  9084. Floating::WithinUlpsMatcher WithinULP(double target, int maxUlpDiff) {
  9085. return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Double);
  9086. }
  9087. Floating::WithinUlpsMatcher WithinULP(float target, int maxUlpDiff) {
  9088. return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Float);
  9089. }
  9090. Floating::WithinAbsMatcher WithinAbs(double target, double margin) {
  9091. return Floating::WithinAbsMatcher(target, margin);
  9092. }
  9093. } // namespace Matchers
  9094. } // namespace Catch
  9095. // end catch_matchers_floating.cpp
  9096. // start catch_matchers_generic.cpp
  9097. std::string Catch::Matchers::Generic::Detail::finalizeDescription(const std::string& desc) {
  9098. if (desc.empty()) {
  9099. return "matches undescribed predicate";
  9100. } else {
  9101. return "matches predicate: \"" + desc + '"';
  9102. }
  9103. }
  9104. // end catch_matchers_generic.cpp
  9105. // start catch_matchers_string.cpp
  9106. #include <regex>
  9107. namespace Catch {
  9108. namespace Matchers {
  9109. namespace StdString {
  9110. CasedString::CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity )
  9111. : m_caseSensitivity( caseSensitivity ),
  9112. m_str( adjustString( str ) )
  9113. {}
  9114. std::string CasedString::adjustString( std::string const& str ) const {
  9115. return m_caseSensitivity == CaseSensitive::No
  9116. ? toLower( str )
  9117. : str;
  9118. }
  9119. std::string CasedString::caseSensitivitySuffix() const {
  9120. return m_caseSensitivity == CaseSensitive::No
  9121. ? " (case insensitive)"
  9122. : std::string();
  9123. }
  9124. StringMatcherBase::StringMatcherBase( std::string const& operation, CasedString const& comparator )
  9125. : m_comparator( comparator ),
  9126. m_operation( operation ) {
  9127. }
  9128. std::string StringMatcherBase::describe() const {
  9129. std::string description;
  9130. description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
  9131. m_comparator.caseSensitivitySuffix().size());
  9132. description += m_operation;
  9133. description += ": \"";
  9134. description += m_comparator.m_str;
  9135. description += "\"";
  9136. description += m_comparator.caseSensitivitySuffix();
  9137. return description;
  9138. }
  9139. EqualsMatcher::EqualsMatcher( CasedString const& comparator ) : StringMatcherBase( "equals", comparator ) {}
  9140. bool EqualsMatcher::match( std::string const& source ) const {
  9141. return m_comparator.adjustString( source ) == m_comparator.m_str;
  9142. }
  9143. ContainsMatcher::ContainsMatcher( CasedString const& comparator ) : StringMatcherBase( "contains", comparator ) {}
  9144. bool ContainsMatcher::match( std::string const& source ) const {
  9145. return contains( m_comparator.adjustString( source ), m_comparator.m_str );
  9146. }
  9147. StartsWithMatcher::StartsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "starts with", comparator ) {}
  9148. bool StartsWithMatcher::match( std::string const& source ) const {
  9149. return startsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  9150. }
  9151. EndsWithMatcher::EndsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "ends with", comparator ) {}
  9152. bool EndsWithMatcher::match( std::string const& source ) const {
  9153. return endsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  9154. }
  9155. RegexMatcher::RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity): m_regex(std::move(regex)), m_caseSensitivity(caseSensitivity) {}
  9156. bool RegexMatcher::match(std::string const& matchee) const {
  9157. auto flags = std::regex::ECMAScript; // ECMAScript is the default syntax option anyway
  9158. if (m_caseSensitivity == CaseSensitive::Choice::No) {
  9159. flags |= std::regex::icase;
  9160. }
  9161. auto reg = std::regex(m_regex, flags);
  9162. return std::regex_match(matchee, reg);
  9163. }
  9164. std::string RegexMatcher::describe() const {
  9165. return "matches " + ::Catch::Detail::stringify(m_regex) + ((m_caseSensitivity == CaseSensitive::Choice::Yes)? " case sensitively" : " case insensitively");
  9166. }
  9167. } // namespace StdString
  9168. StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  9169. return StdString::EqualsMatcher( StdString::CasedString( str, caseSensitivity) );
  9170. }
  9171. StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  9172. return StdString::ContainsMatcher( StdString::CasedString( str, caseSensitivity) );
  9173. }
  9174. StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  9175. return StdString::EndsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  9176. }
  9177. StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  9178. return StdString::StartsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  9179. }
  9180. StdString::RegexMatcher Matches(std::string const& regex, CaseSensitive::Choice caseSensitivity) {
  9181. return StdString::RegexMatcher(regex, caseSensitivity);
  9182. }
  9183. } // namespace Matchers
  9184. } // namespace Catch
  9185. // end catch_matchers_string.cpp
  9186. // start catch_message.cpp
  9187. // start catch_uncaught_exceptions.h
  9188. namespace Catch {
  9189. bool uncaught_exceptions();
  9190. } // end namespace Catch
  9191. // end catch_uncaught_exceptions.h
  9192. #include <cassert>
  9193. #include <stack>
  9194. namespace Catch {
  9195. MessageInfo::MessageInfo( StringRef const& _macroName,
  9196. SourceLineInfo const& _lineInfo,
  9197. ResultWas::OfType _type )
  9198. : macroName( _macroName ),
  9199. lineInfo( _lineInfo ),
  9200. type( _type ),
  9201. sequence( ++globalCount )
  9202. {}
  9203. bool MessageInfo::operator==( MessageInfo const& other ) const {
  9204. return sequence == other.sequence;
  9205. }
  9206. bool MessageInfo::operator<( MessageInfo const& other ) const {
  9207. return sequence < other.sequence;
  9208. }
  9209. // This may need protecting if threading support is added
  9210. unsigned int MessageInfo::globalCount = 0;
  9211. ////////////////////////////////////////////////////////////////////////////
  9212. Catch::MessageBuilder::MessageBuilder( StringRef const& macroName,
  9213. SourceLineInfo const& lineInfo,
  9214. ResultWas::OfType type )
  9215. :m_info(macroName, lineInfo, type) {}
  9216. ////////////////////////////////////////////////////////////////////////////
  9217. ScopedMessage::ScopedMessage( MessageBuilder const& builder )
  9218. : m_info( builder.m_info ), m_moved()
  9219. {
  9220. m_info.message = builder.m_stream.str();
  9221. getResultCapture().pushScopedMessage( m_info );
  9222. }
  9223. ScopedMessage::ScopedMessage( ScopedMessage&& old )
  9224. : m_info( old.m_info ), m_moved()
  9225. {
  9226. old.m_moved = true;
  9227. }
  9228. ScopedMessage::~ScopedMessage() {
  9229. if ( !uncaught_exceptions() && !m_moved ){
  9230. getResultCapture().popScopedMessage(m_info);
  9231. }
  9232. }
  9233. Capturer::Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names ) {
  9234. auto trimmed = [&] (size_t start, size_t end) {
  9235. while (names[start] == ',' || isspace(names[start])) {
  9236. ++start;
  9237. }
  9238. while (names[end] == ',' || isspace(names[end])) {
  9239. --end;
  9240. }
  9241. return names.substr(start, end - start + 1);
  9242. };
  9243. auto skipq = [&] (size_t start, char quote) {
  9244. for (auto i = start + 1; i < names.size() ; ++i) {
  9245. if (names[i] == quote)
  9246. return i;
  9247. if (names[i] == '\\')
  9248. ++i;
  9249. }
  9250. CATCH_INTERNAL_ERROR("CAPTURE parsing encountered unmatched quote");
  9251. };
  9252. size_t start = 0;
  9253. std::stack<char> openings;
  9254. for (size_t pos = 0; pos < names.size(); ++pos) {
  9255. char c = names[pos];
  9256. switch (c) {
  9257. case '[':
  9258. case '{':
  9259. case '(':
  9260. // It is basically impossible to disambiguate between
  9261. // comparison and start of template args in this context
  9262. // case '<':
  9263. openings.push(c);
  9264. break;
  9265. case ']':
  9266. case '}':
  9267. case ')':
  9268. // case '>':
  9269. openings.pop();
  9270. break;
  9271. case '"':
  9272. case '\'':
  9273. pos = skipq(pos, c);
  9274. break;
  9275. case ',':
  9276. if (start != pos && openings.size() == 0) {
  9277. m_messages.emplace_back(macroName, lineInfo, resultType);
  9278. m_messages.back().message = trimmed(start, pos);
  9279. m_messages.back().message += " := ";
  9280. start = pos;
  9281. }
  9282. }
  9283. }
  9284. assert(openings.size() == 0 && "Mismatched openings");
  9285. m_messages.emplace_back(macroName, lineInfo, resultType);
  9286. m_messages.back().message = trimmed(start, names.size() - 1);
  9287. m_messages.back().message += " := ";
  9288. }
  9289. Capturer::~Capturer() {
  9290. if ( !uncaught_exceptions() ){
  9291. assert( m_captured == m_messages.size() );
  9292. for( size_t i = 0; i < m_captured; ++i )
  9293. m_resultCapture.popScopedMessage( m_messages[i] );
  9294. }
  9295. }
  9296. void Capturer::captureValue( size_t index, std::string const& value ) {
  9297. assert( index < m_messages.size() );
  9298. m_messages[index].message += value;
  9299. m_resultCapture.pushScopedMessage( m_messages[index] );
  9300. m_captured++;
  9301. }
  9302. } // end namespace Catch
  9303. // end catch_message.cpp
  9304. // start catch_output_redirect.cpp
  9305. // start catch_output_redirect.h
  9306. #ifndef TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  9307. #define TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  9308. #include <cstdio>
  9309. #include <iosfwd>
  9310. #include <string>
  9311. namespace Catch {
  9312. class RedirectedStream {
  9313. std::ostream& m_originalStream;
  9314. std::ostream& m_redirectionStream;
  9315. std::streambuf* m_prevBuf;
  9316. public:
  9317. RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream );
  9318. ~RedirectedStream();
  9319. };
  9320. class RedirectedStdOut {
  9321. ReusableStringStream m_rss;
  9322. RedirectedStream m_cout;
  9323. public:
  9324. RedirectedStdOut();
  9325. auto str() const -> std::string;
  9326. };
  9327. // StdErr has two constituent streams in C++, std::cerr and std::clog
  9328. // This means that we need to redirect 2 streams into 1 to keep proper
  9329. // order of writes
  9330. class RedirectedStdErr {
  9331. ReusableStringStream m_rss;
  9332. RedirectedStream m_cerr;
  9333. RedirectedStream m_clog;
  9334. public:
  9335. RedirectedStdErr();
  9336. auto str() const -> std::string;
  9337. };
  9338. class RedirectedStreams {
  9339. public:
  9340. RedirectedStreams(RedirectedStreams const&) = delete;
  9341. RedirectedStreams& operator=(RedirectedStreams const&) = delete;
  9342. RedirectedStreams(RedirectedStreams&&) = delete;
  9343. RedirectedStreams& operator=(RedirectedStreams&&) = delete;
  9344. RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr);
  9345. ~RedirectedStreams();
  9346. private:
  9347. std::string& m_redirectedCout;
  9348. std::string& m_redirectedCerr;
  9349. RedirectedStdOut m_redirectedStdOut;
  9350. RedirectedStdErr m_redirectedStdErr;
  9351. };
  9352. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  9353. // Windows's implementation of std::tmpfile is terrible (it tries
  9354. // to create a file inside system folder, thus requiring elevated
  9355. // privileges for the binary), so we have to use tmpnam(_s) and
  9356. // create the file ourselves there.
  9357. class TempFile {
  9358. public:
  9359. TempFile(TempFile const&) = delete;
  9360. TempFile& operator=(TempFile const&) = delete;
  9361. TempFile(TempFile&&) = delete;
  9362. TempFile& operator=(TempFile&&) = delete;
  9363. TempFile();
  9364. ~TempFile();
  9365. std::FILE* getFile();
  9366. std::string getContents();
  9367. private:
  9368. std::FILE* m_file = nullptr;
  9369. #if defined(_MSC_VER)
  9370. char m_buffer[L_tmpnam] = { 0 };
  9371. #endif
  9372. };
  9373. class OutputRedirect {
  9374. public:
  9375. OutputRedirect(OutputRedirect const&) = delete;
  9376. OutputRedirect& operator=(OutputRedirect const&) = delete;
  9377. OutputRedirect(OutputRedirect&&) = delete;
  9378. OutputRedirect& operator=(OutputRedirect&&) = delete;
  9379. OutputRedirect(std::string& stdout_dest, std::string& stderr_dest);
  9380. ~OutputRedirect();
  9381. private:
  9382. int m_originalStdout = -1;
  9383. int m_originalStderr = -1;
  9384. TempFile m_stdoutFile;
  9385. TempFile m_stderrFile;
  9386. std::string& m_stdoutDest;
  9387. std::string& m_stderrDest;
  9388. };
  9389. #endif
  9390. } // end namespace Catch
  9391. #endif // TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  9392. // end catch_output_redirect.h
  9393. #include <cstdio>
  9394. #include <cstring>
  9395. #include <fstream>
  9396. #include <sstream>
  9397. #include <stdexcept>
  9398. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  9399. #if defined(_MSC_VER)
  9400. #include <io.h> //_dup and _dup2
  9401. #define dup _dup
  9402. #define dup2 _dup2
  9403. #define fileno _fileno
  9404. #else
  9405. #include <unistd.h> // dup and dup2
  9406. #endif
  9407. #endif
  9408. namespace Catch {
  9409. RedirectedStream::RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream )
  9410. : m_originalStream( originalStream ),
  9411. m_redirectionStream( redirectionStream ),
  9412. m_prevBuf( m_originalStream.rdbuf() )
  9413. {
  9414. m_originalStream.rdbuf( m_redirectionStream.rdbuf() );
  9415. }
  9416. RedirectedStream::~RedirectedStream() {
  9417. m_originalStream.rdbuf( m_prevBuf );
  9418. }
  9419. RedirectedStdOut::RedirectedStdOut() : m_cout( Catch::cout(), m_rss.get() ) {}
  9420. auto RedirectedStdOut::str() const -> std::string { return m_rss.str(); }
  9421. RedirectedStdErr::RedirectedStdErr()
  9422. : m_cerr( Catch::cerr(), m_rss.get() ),
  9423. m_clog( Catch::clog(), m_rss.get() )
  9424. {}
  9425. auto RedirectedStdErr::str() const -> std::string { return m_rss.str(); }
  9426. RedirectedStreams::RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr)
  9427. : m_redirectedCout(redirectedCout),
  9428. m_redirectedCerr(redirectedCerr)
  9429. {}
  9430. RedirectedStreams::~RedirectedStreams() {
  9431. m_redirectedCout += m_redirectedStdOut.str();
  9432. m_redirectedCerr += m_redirectedStdErr.str();
  9433. }
  9434. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  9435. #if defined(_MSC_VER)
  9436. TempFile::TempFile() {
  9437. if (tmpnam_s(m_buffer)) {
  9438. CATCH_RUNTIME_ERROR("Could not get a temp filename");
  9439. }
  9440. if (fopen_s(&m_file, m_buffer, "w")) {
  9441. char buffer[100];
  9442. if (strerror_s(buffer, errno)) {
  9443. CATCH_RUNTIME_ERROR("Could not translate errno to a string");
  9444. }
  9445. CATCH_RUNTIME_ERROR("Could not open the temp file: '" << m_buffer << "' because: " << buffer);
  9446. }
  9447. }
  9448. #else
  9449. TempFile::TempFile() {
  9450. m_file = std::tmpfile();
  9451. if (!m_file) {
  9452. CATCH_RUNTIME_ERROR("Could not create a temp file.");
  9453. }
  9454. }
  9455. #endif
  9456. TempFile::~TempFile() {
  9457. // TBD: What to do about errors here?
  9458. std::fclose(m_file);
  9459. // We manually create the file on Windows only, on Linux
  9460. // it will be autodeleted
  9461. #if defined(_MSC_VER)
  9462. std::remove(m_buffer);
  9463. #endif
  9464. }
  9465. FILE* TempFile::getFile() {
  9466. return m_file;
  9467. }
  9468. std::string TempFile::getContents() {
  9469. std::stringstream sstr;
  9470. char buffer[100] = {};
  9471. std::rewind(m_file);
  9472. while (std::fgets(buffer, sizeof(buffer), m_file)) {
  9473. sstr << buffer;
  9474. }
  9475. return sstr.str();
  9476. }
  9477. OutputRedirect::OutputRedirect(std::string& stdout_dest, std::string& stderr_dest) :
  9478. m_originalStdout(dup(1)),
  9479. m_originalStderr(dup(2)),
  9480. m_stdoutDest(stdout_dest),
  9481. m_stderrDest(stderr_dest) {
  9482. dup2(fileno(m_stdoutFile.getFile()), 1);
  9483. dup2(fileno(m_stderrFile.getFile()), 2);
  9484. }
  9485. OutputRedirect::~OutputRedirect() {
  9486. Catch::cout() << std::flush;
  9487. fflush(stdout);
  9488. // Since we support overriding these streams, we flush cerr
  9489. // even though std::cerr is unbuffered
  9490. Catch::cerr() << std::flush;
  9491. Catch::clog() << std::flush;
  9492. fflush(stderr);
  9493. dup2(m_originalStdout, 1);
  9494. dup2(m_originalStderr, 2);
  9495. m_stdoutDest += m_stdoutFile.getContents();
  9496. m_stderrDest += m_stderrFile.getContents();
  9497. }
  9498. #endif // CATCH_CONFIG_NEW_CAPTURE
  9499. } // namespace Catch
  9500. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  9501. #if defined(_MSC_VER)
  9502. #undef dup
  9503. #undef dup2
  9504. #undef fileno
  9505. #endif
  9506. #endif
  9507. // end catch_output_redirect.cpp
  9508. // start catch_polyfills.cpp
  9509. #include <cmath>
  9510. namespace Catch {
  9511. #if !defined(CATCH_CONFIG_POLYFILL_ISNAN)
  9512. bool isnan(float f) {
  9513. return std::isnan(f);
  9514. }
  9515. bool isnan(double d) {
  9516. return std::isnan(d);
  9517. }
  9518. #else
  9519. // For now we only use this for embarcadero
  9520. bool isnan(float f) {
  9521. return std::_isnan(f);
  9522. }
  9523. bool isnan(double d) {
  9524. return std::_isnan(d);
  9525. }
  9526. #endif
  9527. } // end namespace Catch
  9528. // end catch_polyfills.cpp
  9529. // start catch_random_number_generator.cpp
  9530. namespace Catch {
  9531. std::mt19937& rng() {
  9532. static std::mt19937 s_rng;
  9533. return s_rng;
  9534. }
  9535. void seedRng( IConfig const& config ) {
  9536. if( config.rngSeed() != 0 ) {
  9537. std::srand( config.rngSeed() );
  9538. rng().seed( config.rngSeed() );
  9539. }
  9540. }
  9541. unsigned int rngSeed() {
  9542. return getCurrentContext().getConfig()->rngSeed();
  9543. }
  9544. }
  9545. // end catch_random_number_generator.cpp
  9546. // start catch_registry_hub.cpp
  9547. // start catch_test_case_registry_impl.h
  9548. #include <vector>
  9549. #include <set>
  9550. #include <algorithm>
  9551. #include <ios>
  9552. namespace Catch {
  9553. class TestCase;
  9554. struct IConfig;
  9555. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases );
  9556. bool isThrowSafe( TestCase const& testCase, IConfig const& config );
  9557. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
  9558. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions );
  9559. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
  9560. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
  9561. class TestRegistry : public ITestCaseRegistry {
  9562. public:
  9563. virtual ~TestRegistry() = default;
  9564. virtual void registerTest( TestCase const& testCase );
  9565. std::vector<TestCase> const& getAllTests() const override;
  9566. std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const override;
  9567. private:
  9568. std::vector<TestCase> m_functions;
  9569. mutable RunTests::InWhatOrder m_currentSortOrder = RunTests::InDeclarationOrder;
  9570. mutable std::vector<TestCase> m_sortedFunctions;
  9571. std::size_t m_unnamedCount = 0;
  9572. std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised
  9573. };
  9574. ///////////////////////////////////////////////////////////////////////////
  9575. class TestInvokerAsFunction : public ITestInvoker {
  9576. void(*m_testAsFunction)();
  9577. public:
  9578. TestInvokerAsFunction( void(*testAsFunction)() ) noexcept;
  9579. void invoke() const override;
  9580. };
  9581. std::string extractClassName( StringRef const& classOrQualifiedMethodName );
  9582. ///////////////////////////////////////////////////////////////////////////
  9583. } // end namespace Catch
  9584. // end catch_test_case_registry_impl.h
  9585. // start catch_reporter_registry.h
  9586. #include <map>
  9587. namespace Catch {
  9588. class ReporterRegistry : public IReporterRegistry {
  9589. public:
  9590. ~ReporterRegistry() override;
  9591. IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const override;
  9592. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory );
  9593. void registerListener( IReporterFactoryPtr const& factory );
  9594. FactoryMap const& getFactories() const override;
  9595. Listeners const& getListeners() const override;
  9596. private:
  9597. FactoryMap m_factories;
  9598. Listeners m_listeners;
  9599. };
  9600. }
  9601. // end catch_reporter_registry.h
  9602. // start catch_tag_alias_registry.h
  9603. // start catch_tag_alias.h
  9604. #include <string>
  9605. namespace Catch {
  9606. struct TagAlias {
  9607. TagAlias(std::string const& _tag, SourceLineInfo _lineInfo);
  9608. std::string tag;
  9609. SourceLineInfo lineInfo;
  9610. };
  9611. } // end namespace Catch
  9612. // end catch_tag_alias.h
  9613. #include <map>
  9614. namespace Catch {
  9615. class TagAliasRegistry : public ITagAliasRegistry {
  9616. public:
  9617. ~TagAliasRegistry() override;
  9618. TagAlias const* find( std::string const& alias ) const override;
  9619. std::string expandAliases( std::string const& unexpandedTestSpec ) const override;
  9620. void add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo );
  9621. private:
  9622. std::map<std::string, TagAlias> m_registry;
  9623. };
  9624. } // end namespace Catch
  9625. // end catch_tag_alias_registry.h
  9626. // start catch_startup_exception_registry.h
  9627. #include <vector>
  9628. #include <exception>
  9629. namespace Catch {
  9630. class StartupExceptionRegistry {
  9631. public:
  9632. void add(std::exception_ptr const& exception) noexcept;
  9633. std::vector<std::exception_ptr> const& getExceptions() const noexcept;
  9634. private:
  9635. std::vector<std::exception_ptr> m_exceptions;
  9636. };
  9637. } // end namespace Catch
  9638. // end catch_startup_exception_registry.h
  9639. // start catch_singletons.hpp
  9640. namespace Catch {
  9641. struct ISingleton {
  9642. virtual ~ISingleton();
  9643. };
  9644. void addSingleton( ISingleton* singleton );
  9645. void cleanupSingletons();
  9646. template<typename SingletonImplT, typename InterfaceT = SingletonImplT, typename MutableInterfaceT = InterfaceT>
  9647. class Singleton : SingletonImplT, public ISingleton {
  9648. static auto getInternal() -> Singleton* {
  9649. static Singleton* s_instance = nullptr;
  9650. if( !s_instance ) {
  9651. s_instance = new Singleton;
  9652. addSingleton( s_instance );
  9653. }
  9654. return s_instance;
  9655. }
  9656. public:
  9657. static auto get() -> InterfaceT const& {
  9658. return *getInternal();
  9659. }
  9660. static auto getMutable() -> MutableInterfaceT& {
  9661. return *getInternal();
  9662. }
  9663. };
  9664. } // namespace Catch
  9665. // end catch_singletons.hpp
  9666. namespace Catch {
  9667. namespace {
  9668. class RegistryHub : public IRegistryHub, public IMutableRegistryHub,
  9669. private NonCopyable {
  9670. public: // IRegistryHub
  9671. RegistryHub() = default;
  9672. IReporterRegistry const& getReporterRegistry() const override {
  9673. return m_reporterRegistry;
  9674. }
  9675. ITestCaseRegistry const& getTestCaseRegistry() const override {
  9676. return m_testCaseRegistry;
  9677. }
  9678. IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const override {
  9679. return m_exceptionTranslatorRegistry;
  9680. }
  9681. ITagAliasRegistry const& getTagAliasRegistry() const override {
  9682. return m_tagAliasRegistry;
  9683. }
  9684. StartupExceptionRegistry const& getStartupExceptionRegistry() const override {
  9685. return m_exceptionRegistry;
  9686. }
  9687. public: // IMutableRegistryHub
  9688. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) override {
  9689. m_reporterRegistry.registerReporter( name, factory );
  9690. }
  9691. void registerListener( IReporterFactoryPtr const& factory ) override {
  9692. m_reporterRegistry.registerListener( factory );
  9693. }
  9694. void registerTest( TestCase const& testInfo ) override {
  9695. m_testCaseRegistry.registerTest( testInfo );
  9696. }
  9697. void registerTranslator( const IExceptionTranslator* translator ) override {
  9698. m_exceptionTranslatorRegistry.registerTranslator( translator );
  9699. }
  9700. void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) override {
  9701. m_tagAliasRegistry.add( alias, tag, lineInfo );
  9702. }
  9703. void registerStartupException() noexcept override {
  9704. m_exceptionRegistry.add(std::current_exception());
  9705. }
  9706. IMutableEnumValuesRegistry& getMutableEnumValuesRegistry() override {
  9707. return m_enumValuesRegistry;
  9708. }
  9709. private:
  9710. TestRegistry m_testCaseRegistry;
  9711. ReporterRegistry m_reporterRegistry;
  9712. ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
  9713. TagAliasRegistry m_tagAliasRegistry;
  9714. StartupExceptionRegistry m_exceptionRegistry;
  9715. Detail::EnumValuesRegistry m_enumValuesRegistry;
  9716. };
  9717. }
  9718. using RegistryHubSingleton = Singleton<RegistryHub, IRegistryHub, IMutableRegistryHub>;
  9719. IRegistryHub const& getRegistryHub() {
  9720. return RegistryHubSingleton::get();
  9721. }
  9722. IMutableRegistryHub& getMutableRegistryHub() {
  9723. return RegistryHubSingleton::getMutable();
  9724. }
  9725. void cleanUp() {
  9726. cleanupSingletons();
  9727. cleanUpContext();
  9728. }
  9729. std::string translateActiveException() {
  9730. return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException();
  9731. }
  9732. } // end namespace Catch
  9733. // end catch_registry_hub.cpp
  9734. // start catch_reporter_registry.cpp
  9735. namespace Catch {
  9736. ReporterRegistry::~ReporterRegistry() = default;
  9737. IStreamingReporterPtr ReporterRegistry::create( std::string const& name, IConfigPtr const& config ) const {
  9738. auto it = m_factories.find( name );
  9739. if( it == m_factories.end() )
  9740. return nullptr;
  9741. return it->second->create( ReporterConfig( config ) );
  9742. }
  9743. void ReporterRegistry::registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) {
  9744. m_factories.emplace(name, factory);
  9745. }
  9746. void ReporterRegistry::registerListener( IReporterFactoryPtr const& factory ) {
  9747. m_listeners.push_back( factory );
  9748. }
  9749. IReporterRegistry::FactoryMap const& ReporterRegistry::getFactories() const {
  9750. return m_factories;
  9751. }
  9752. IReporterRegistry::Listeners const& ReporterRegistry::getListeners() const {
  9753. return m_listeners;
  9754. }
  9755. }
  9756. // end catch_reporter_registry.cpp
  9757. // start catch_result_type.cpp
  9758. namespace Catch {
  9759. bool isOk( ResultWas::OfType resultType ) {
  9760. return ( resultType & ResultWas::FailureBit ) == 0;
  9761. }
  9762. bool isJustInfo( int flags ) {
  9763. return flags == ResultWas::Info;
  9764. }
  9765. ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) {
  9766. return static_cast<ResultDisposition::Flags>( static_cast<int>( lhs ) | static_cast<int>( rhs ) );
  9767. }
  9768. bool shouldContinueOnFailure( int flags ) { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; }
  9769. bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; }
  9770. } // end namespace Catch
  9771. // end catch_result_type.cpp
  9772. // start catch_run_context.cpp
  9773. #include <cassert>
  9774. #include <algorithm>
  9775. #include <sstream>
  9776. namespace Catch {
  9777. namespace Generators {
  9778. struct GeneratorTracker : TestCaseTracking::TrackerBase, IGeneratorTracker {
  9779. GeneratorBasePtr m_generator;
  9780. GeneratorTracker( TestCaseTracking::NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  9781. : TrackerBase( nameAndLocation, ctx, parent )
  9782. {}
  9783. ~GeneratorTracker();
  9784. static GeneratorTracker& acquire( TrackerContext& ctx, TestCaseTracking::NameAndLocation const& nameAndLocation ) {
  9785. std::shared_ptr<GeneratorTracker> tracker;
  9786. ITracker& currentTracker = ctx.currentTracker();
  9787. if( TestCaseTracking::ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  9788. assert( childTracker );
  9789. assert( childTracker->isGeneratorTracker() );
  9790. tracker = std::static_pointer_cast<GeneratorTracker>( childTracker );
  9791. }
  9792. else {
  9793. tracker = std::make_shared<GeneratorTracker>( nameAndLocation, ctx, &currentTracker );
  9794. currentTracker.addChild( tracker );
  9795. }
  9796. if( !ctx.completedCycle() && !tracker->isComplete() ) {
  9797. tracker->open();
  9798. }
  9799. return *tracker;
  9800. }
  9801. // TrackerBase interface
  9802. bool isGeneratorTracker() const override { return true; }
  9803. auto hasGenerator() const -> bool override {
  9804. return !!m_generator;
  9805. }
  9806. void close() override {
  9807. TrackerBase::close();
  9808. // Generator interface only finds out if it has another item on atual move
  9809. if (m_runState == CompletedSuccessfully && m_generator->next()) {
  9810. m_children.clear();
  9811. m_runState = Executing;
  9812. }
  9813. }
  9814. // IGeneratorTracker interface
  9815. auto getGenerator() const -> GeneratorBasePtr const& override {
  9816. return m_generator;
  9817. }
  9818. void setGenerator( GeneratorBasePtr&& generator ) override {
  9819. m_generator = std::move( generator );
  9820. }
  9821. };
  9822. GeneratorTracker::~GeneratorTracker() {}
  9823. }
  9824. RunContext::RunContext(IConfigPtr const& _config, IStreamingReporterPtr&& reporter)
  9825. : m_runInfo(_config->name()),
  9826. m_context(getCurrentMutableContext()),
  9827. m_config(_config),
  9828. m_reporter(std::move(reporter)),
  9829. m_lastAssertionInfo{ StringRef(), SourceLineInfo("",0), StringRef(), ResultDisposition::Normal },
  9830. m_includeSuccessfulResults( m_config->includeSuccessfulResults() || m_reporter->getPreferences().shouldReportAllAssertions )
  9831. {
  9832. m_context.setRunner(this);
  9833. m_context.setConfig(m_config);
  9834. m_context.setResultCapture(this);
  9835. m_reporter->testRunStarting(m_runInfo);
  9836. }
  9837. RunContext::~RunContext() {
  9838. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting()));
  9839. }
  9840. void RunContext::testGroupStarting(std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount) {
  9841. m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount));
  9842. }
  9843. void RunContext::testGroupEnded(std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount) {
  9844. m_reporter->testGroupEnded(TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting()));
  9845. }
  9846. Totals RunContext::runTest(TestCase const& testCase) {
  9847. Totals prevTotals = m_totals;
  9848. std::string redirectedCout;
  9849. std::string redirectedCerr;
  9850. auto const& testInfo = testCase.getTestCaseInfo();
  9851. m_reporter->testCaseStarting(testInfo);
  9852. m_activeTestCase = &testCase;
  9853. ITracker& rootTracker = m_trackerContext.startRun();
  9854. assert(rootTracker.isSectionTracker());
  9855. static_cast<SectionTracker&>(rootTracker).addInitialFilters(m_config->getSectionsToRun());
  9856. do {
  9857. m_trackerContext.startCycle();
  9858. m_testCaseTracker = &SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo));
  9859. runCurrentTest(redirectedCout, redirectedCerr);
  9860. } while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting());
  9861. Totals deltaTotals = m_totals.delta(prevTotals);
  9862. if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) {
  9863. deltaTotals.assertions.failed++;
  9864. deltaTotals.testCases.passed--;
  9865. deltaTotals.testCases.failed++;
  9866. }
  9867. m_totals.testCases += deltaTotals.testCases;
  9868. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  9869. deltaTotals,
  9870. redirectedCout,
  9871. redirectedCerr,
  9872. aborting()));
  9873. m_activeTestCase = nullptr;
  9874. m_testCaseTracker = nullptr;
  9875. return deltaTotals;
  9876. }
  9877. IConfigPtr RunContext::config() const {
  9878. return m_config;
  9879. }
  9880. IStreamingReporter& RunContext::reporter() const {
  9881. return *m_reporter;
  9882. }
  9883. void RunContext::assertionEnded(AssertionResult const & result) {
  9884. if (result.getResultType() == ResultWas::Ok) {
  9885. m_totals.assertions.passed++;
  9886. m_lastAssertionPassed = true;
  9887. } else if (!result.isOk()) {
  9888. m_lastAssertionPassed = false;
  9889. if( m_activeTestCase->getTestCaseInfo().okToFail() )
  9890. m_totals.assertions.failedButOk++;
  9891. else
  9892. m_totals.assertions.failed++;
  9893. }
  9894. else {
  9895. m_lastAssertionPassed = true;
  9896. }
  9897. // We have no use for the return value (whether messages should be cleared), because messages were made scoped
  9898. // and should be let to clear themselves out.
  9899. static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals)));
  9900. if (result.getResultType() != ResultWas::Warning)
  9901. m_messageScopes.clear();
  9902. // Reset working state
  9903. resetAssertionInfo();
  9904. m_lastResult = result;
  9905. }
  9906. void RunContext::resetAssertionInfo() {
  9907. m_lastAssertionInfo.macroName = StringRef();
  9908. m_lastAssertionInfo.capturedExpression = "{Unknown expression after the reported line}"_sr;
  9909. }
  9910. bool RunContext::sectionStarted(SectionInfo const & sectionInfo, Counts & assertions) {
  9911. ITracker& sectionTracker = SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(sectionInfo.name, sectionInfo.lineInfo));
  9912. if (!sectionTracker.isOpen())
  9913. return false;
  9914. m_activeSections.push_back(&sectionTracker);
  9915. m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;
  9916. m_reporter->sectionStarting(sectionInfo);
  9917. assertions = m_totals.assertions;
  9918. return true;
  9919. }
  9920. auto RunContext::acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
  9921. using namespace Generators;
  9922. GeneratorTracker& tracker = GeneratorTracker::acquire( m_trackerContext, TestCaseTracking::NameAndLocation( "generator", lineInfo ) );
  9923. assert( tracker.isOpen() );
  9924. m_lastAssertionInfo.lineInfo = lineInfo;
  9925. return tracker;
  9926. }
  9927. bool RunContext::testForMissingAssertions(Counts& assertions) {
  9928. if (assertions.total() != 0)
  9929. return false;
  9930. if (!m_config->warnAboutMissingAssertions())
  9931. return false;
  9932. if (m_trackerContext.currentTracker().hasChildren())
  9933. return false;
  9934. m_totals.assertions.failed++;
  9935. assertions.failed++;
  9936. return true;
  9937. }
  9938. void RunContext::sectionEnded(SectionEndInfo const & endInfo) {
  9939. Counts assertions = m_totals.assertions - endInfo.prevAssertions;
  9940. bool missingAssertions = testForMissingAssertions(assertions);
  9941. if (!m_activeSections.empty()) {
  9942. m_activeSections.back()->close();
  9943. m_activeSections.pop_back();
  9944. }
  9945. m_reporter->sectionEnded(SectionStats(endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions));
  9946. m_messages.clear();
  9947. m_messageScopes.clear();
  9948. }
  9949. void RunContext::sectionEndedEarly(SectionEndInfo const & endInfo) {
  9950. if (m_unfinishedSections.empty())
  9951. m_activeSections.back()->fail();
  9952. else
  9953. m_activeSections.back()->close();
  9954. m_activeSections.pop_back();
  9955. m_unfinishedSections.push_back(endInfo);
  9956. }
  9957. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  9958. void RunContext::benchmarkPreparing(std::string const& name) {
  9959. m_reporter->benchmarkPreparing(name);
  9960. }
  9961. void RunContext::benchmarkStarting( BenchmarkInfo const& info ) {
  9962. m_reporter->benchmarkStarting( info );
  9963. }
  9964. void RunContext::benchmarkEnded( BenchmarkStats<> const& stats ) {
  9965. m_reporter->benchmarkEnded( stats );
  9966. }
  9967. void RunContext::benchmarkFailed(std::string const & error) {
  9968. m_reporter->benchmarkFailed(error);
  9969. }
  9970. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  9971. void RunContext::pushScopedMessage(MessageInfo const & message) {
  9972. m_messages.push_back(message);
  9973. }
  9974. void RunContext::popScopedMessage(MessageInfo const & message) {
  9975. m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end());
  9976. }
  9977. void RunContext::emplaceUnscopedMessage( MessageBuilder const& builder ) {
  9978. m_messageScopes.emplace_back( builder );
  9979. }
  9980. std::string RunContext::getCurrentTestName() const {
  9981. return m_activeTestCase
  9982. ? m_activeTestCase->getTestCaseInfo().name
  9983. : std::string();
  9984. }
  9985. const AssertionResult * RunContext::getLastResult() const {
  9986. return &(*m_lastResult);
  9987. }
  9988. void RunContext::exceptionEarlyReported() {
  9989. m_shouldReportUnexpected = false;
  9990. }
  9991. void RunContext::handleFatalErrorCondition( StringRef message ) {
  9992. // First notify reporter that bad things happened
  9993. m_reporter->fatalErrorEncountered(message);
  9994. // Don't rebuild the result -- the stringification itself can cause more fatal errors
  9995. // Instead, fake a result data.
  9996. AssertionResultData tempResult( ResultWas::FatalErrorCondition, { false } );
  9997. tempResult.message = message;
  9998. AssertionResult result(m_lastAssertionInfo, tempResult);
  9999. assertionEnded(result);
  10000. handleUnfinishedSections();
  10001. // Recreate section for test case (as we will lose the one that was in scope)
  10002. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  10003. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
  10004. Counts assertions;
  10005. assertions.failed = 1;
  10006. SectionStats testCaseSectionStats(testCaseSection, assertions, 0, false);
  10007. m_reporter->sectionEnded(testCaseSectionStats);
  10008. auto const& testInfo = m_activeTestCase->getTestCaseInfo();
  10009. Totals deltaTotals;
  10010. deltaTotals.testCases.failed = 1;
  10011. deltaTotals.assertions.failed = 1;
  10012. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  10013. deltaTotals,
  10014. std::string(),
  10015. std::string(),
  10016. false));
  10017. m_totals.testCases.failed++;
  10018. testGroupEnded(std::string(), m_totals, 1, 1);
  10019. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, false));
  10020. }
  10021. bool RunContext::lastAssertionPassed() {
  10022. return m_lastAssertionPassed;
  10023. }
  10024. void RunContext::assertionPassed() {
  10025. m_lastAssertionPassed = true;
  10026. ++m_totals.assertions.passed;
  10027. resetAssertionInfo();
  10028. m_messageScopes.clear();
  10029. }
  10030. bool RunContext::aborting() const {
  10031. return m_totals.assertions.failed >= static_cast<std::size_t>(m_config->abortAfter());
  10032. }
  10033. void RunContext::runCurrentTest(std::string & redirectedCout, std::string & redirectedCerr) {
  10034. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  10035. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
  10036. m_reporter->sectionStarting(testCaseSection);
  10037. Counts prevAssertions = m_totals.assertions;
  10038. double duration = 0;
  10039. m_shouldReportUnexpected = true;
  10040. m_lastAssertionInfo = { "TEST_CASE"_sr, testCaseInfo.lineInfo, StringRef(), ResultDisposition::Normal };
  10041. seedRng(*m_config);
  10042. Timer timer;
  10043. CATCH_TRY {
  10044. if (m_reporter->getPreferences().shouldRedirectStdOut) {
  10045. #if !defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
  10046. RedirectedStreams redirectedStreams(redirectedCout, redirectedCerr);
  10047. timer.start();
  10048. invokeActiveTestCase();
  10049. #else
  10050. OutputRedirect r(redirectedCout, redirectedCerr);
  10051. timer.start();
  10052. invokeActiveTestCase();
  10053. #endif
  10054. } else {
  10055. timer.start();
  10056. invokeActiveTestCase();
  10057. }
  10058. duration = timer.getElapsedSeconds();
  10059. } CATCH_CATCH_ANON (TestFailureException&) {
  10060. // This just means the test was aborted due to failure
  10061. } CATCH_CATCH_ALL {
  10062. // Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under REQUIRE assertions
  10063. // are reported without translation at the point of origin.
  10064. if( m_shouldReportUnexpected ) {
  10065. AssertionReaction dummyReaction;
  10066. handleUnexpectedInflightException( m_lastAssertionInfo, translateActiveException(), dummyReaction );
  10067. }
  10068. }
  10069. Counts assertions = m_totals.assertions - prevAssertions;
  10070. bool missingAssertions = testForMissingAssertions(assertions);
  10071. m_testCaseTracker->close();
  10072. handleUnfinishedSections();
  10073. m_messages.clear();
  10074. m_messageScopes.clear();
  10075. SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions);
  10076. m_reporter->sectionEnded(testCaseSectionStats);
  10077. }
  10078. void RunContext::invokeActiveTestCase() {
  10079. FatalConditionHandler fatalConditionHandler; // Handle signals
  10080. m_activeTestCase->invoke();
  10081. fatalConditionHandler.reset();
  10082. }
  10083. void RunContext::handleUnfinishedSections() {
  10084. // If sections ended prematurely due to an exception we stored their
  10085. // infos here so we can tear them down outside the unwind process.
  10086. for (auto it = m_unfinishedSections.rbegin(),
  10087. itEnd = m_unfinishedSections.rend();
  10088. it != itEnd;
  10089. ++it)
  10090. sectionEnded(*it);
  10091. m_unfinishedSections.clear();
  10092. }
  10093. void RunContext::handleExpr(
  10094. AssertionInfo const& info,
  10095. ITransientExpression const& expr,
  10096. AssertionReaction& reaction
  10097. ) {
  10098. m_reporter->assertionStarting( info );
  10099. bool negated = isFalseTest( info.resultDisposition );
  10100. bool result = expr.getResult() != negated;
  10101. if( result ) {
  10102. if (!m_includeSuccessfulResults) {
  10103. assertionPassed();
  10104. }
  10105. else {
  10106. reportExpr(info, ResultWas::Ok, &expr, negated);
  10107. }
  10108. }
  10109. else {
  10110. reportExpr(info, ResultWas::ExpressionFailed, &expr, negated );
  10111. populateReaction( reaction );
  10112. }
  10113. }
  10114. void RunContext::reportExpr(
  10115. AssertionInfo const &info,
  10116. ResultWas::OfType resultType,
  10117. ITransientExpression const *expr,
  10118. bool negated ) {
  10119. m_lastAssertionInfo = info;
  10120. AssertionResultData data( resultType, LazyExpression( negated ) );
  10121. AssertionResult assertionResult{ info, data };
  10122. assertionResult.m_resultData.lazyExpression.m_transientExpression = expr;
  10123. assertionEnded( assertionResult );
  10124. }
  10125. void RunContext::handleMessage(
  10126. AssertionInfo const& info,
  10127. ResultWas::OfType resultType,
  10128. StringRef const& message,
  10129. AssertionReaction& reaction
  10130. ) {
  10131. m_reporter->assertionStarting( info );
  10132. m_lastAssertionInfo = info;
  10133. AssertionResultData data( resultType, LazyExpression( false ) );
  10134. data.message = message;
  10135. AssertionResult assertionResult{ m_lastAssertionInfo, data };
  10136. assertionEnded( assertionResult );
  10137. if( !assertionResult.isOk() )
  10138. populateReaction( reaction );
  10139. }
  10140. void RunContext::handleUnexpectedExceptionNotThrown(
  10141. AssertionInfo const& info,
  10142. AssertionReaction& reaction
  10143. ) {
  10144. handleNonExpr(info, Catch::ResultWas::DidntThrowException, reaction);
  10145. }
  10146. void RunContext::handleUnexpectedInflightException(
  10147. AssertionInfo const& info,
  10148. std::string const& message,
  10149. AssertionReaction& reaction
  10150. ) {
  10151. m_lastAssertionInfo = info;
  10152. AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
  10153. data.message = message;
  10154. AssertionResult assertionResult{ info, data };
  10155. assertionEnded( assertionResult );
  10156. populateReaction( reaction );
  10157. }
  10158. void RunContext::populateReaction( AssertionReaction& reaction ) {
  10159. reaction.shouldDebugBreak = m_config->shouldDebugBreak();
  10160. reaction.shouldThrow = aborting() || (m_lastAssertionInfo.resultDisposition & ResultDisposition::Normal);
  10161. }
  10162. void RunContext::handleIncomplete(
  10163. AssertionInfo const& info
  10164. ) {
  10165. m_lastAssertionInfo = info;
  10166. AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
  10167. data.message = "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE";
  10168. AssertionResult assertionResult{ info, data };
  10169. assertionEnded( assertionResult );
  10170. }
  10171. void RunContext::handleNonExpr(
  10172. AssertionInfo const &info,
  10173. ResultWas::OfType resultType,
  10174. AssertionReaction &reaction
  10175. ) {
  10176. m_lastAssertionInfo = info;
  10177. AssertionResultData data( resultType, LazyExpression( false ) );
  10178. AssertionResult assertionResult{ info, data };
  10179. assertionEnded( assertionResult );
  10180. if( !assertionResult.isOk() )
  10181. populateReaction( reaction );
  10182. }
  10183. IResultCapture& getResultCapture() {
  10184. if (auto* capture = getCurrentContext().getResultCapture())
  10185. return *capture;
  10186. else
  10187. CATCH_INTERNAL_ERROR("No result capture instance");
  10188. }
  10189. }
  10190. // end catch_run_context.cpp
  10191. // start catch_section.cpp
  10192. namespace Catch {
  10193. Section::Section( SectionInfo const& info )
  10194. : m_info( info ),
  10195. m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) )
  10196. {
  10197. m_timer.start();
  10198. }
  10199. Section::~Section() {
  10200. if( m_sectionIncluded ) {
  10201. SectionEndInfo endInfo{ m_info, m_assertions, m_timer.getElapsedSeconds() };
  10202. if( uncaught_exceptions() )
  10203. getResultCapture().sectionEndedEarly( endInfo );
  10204. else
  10205. getResultCapture().sectionEnded( endInfo );
  10206. }
  10207. }
  10208. // This indicates whether the section should be executed or not
  10209. Section::operator bool() const {
  10210. return m_sectionIncluded;
  10211. }
  10212. } // end namespace Catch
  10213. // end catch_section.cpp
  10214. // start catch_section_info.cpp
  10215. namespace Catch {
  10216. SectionInfo::SectionInfo
  10217. ( SourceLineInfo const& _lineInfo,
  10218. std::string const& _name )
  10219. : name( _name ),
  10220. lineInfo( _lineInfo )
  10221. {}
  10222. } // end namespace Catch
  10223. // end catch_section_info.cpp
  10224. // start catch_session.cpp
  10225. // start catch_session.h
  10226. #include <memory>
  10227. namespace Catch {
  10228. class Session : NonCopyable {
  10229. public:
  10230. Session();
  10231. ~Session() override;
  10232. void showHelp() const;
  10233. void libIdentify();
  10234. int applyCommandLine( int argc, char const * const * argv );
  10235. #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)
  10236. int applyCommandLine( int argc, wchar_t const * const * argv );
  10237. #endif
  10238. void useConfigData( ConfigData const& configData );
  10239. template<typename CharT>
  10240. int run(int argc, CharT const * const argv[]) {
  10241. if (m_startupExceptions)
  10242. return 1;
  10243. int returnCode = applyCommandLine(argc, argv);
  10244. if (returnCode == 0)
  10245. returnCode = run();
  10246. return returnCode;
  10247. }
  10248. int run();
  10249. clara::Parser const& cli() const;
  10250. void cli( clara::Parser const& newParser );
  10251. ConfigData& configData();
  10252. Config& config();
  10253. private:
  10254. int runInternal();
  10255. clara::Parser m_cli;
  10256. ConfigData m_configData;
  10257. std::shared_ptr<Config> m_config;
  10258. bool m_startupExceptions = false;
  10259. };
  10260. } // end namespace Catch
  10261. // end catch_session.h
  10262. // start catch_version.h
  10263. #include <iosfwd>
  10264. namespace Catch {
  10265. // Versioning information
  10266. struct Version {
  10267. Version( Version const& ) = delete;
  10268. Version& operator=( Version const& ) = delete;
  10269. Version( unsigned int _majorVersion,
  10270. unsigned int _minorVersion,
  10271. unsigned int _patchNumber,
  10272. char const * const _branchName,
  10273. unsigned int _buildNumber );
  10274. unsigned int const majorVersion;
  10275. unsigned int const minorVersion;
  10276. unsigned int const patchNumber;
  10277. // buildNumber is only used if branchName is not null
  10278. char const * const branchName;
  10279. unsigned int const buildNumber;
  10280. friend std::ostream& operator << ( std::ostream& os, Version const& version );
  10281. };
  10282. Version const& libraryVersion();
  10283. }
  10284. // end catch_version.h
  10285. #include <cstdlib>
  10286. #include <iomanip>
  10287. #include <set>
  10288. #include <iterator>
  10289. namespace Catch {
  10290. namespace {
  10291. const int MaxExitCode = 255;
  10292. IStreamingReporterPtr createReporter(std::string const& reporterName, IConfigPtr const& config) {
  10293. auto reporter = Catch::getRegistryHub().getReporterRegistry().create(reporterName, config);
  10294. CATCH_ENFORCE(reporter, "No reporter registered with name: '" << reporterName << "'");
  10295. return reporter;
  10296. }
  10297. IStreamingReporterPtr makeReporter(std::shared_ptr<Config> const& config) {
  10298. if (Catch::getRegistryHub().getReporterRegistry().getListeners().empty()) {
  10299. return createReporter(config->getReporterName(), config);
  10300. }
  10301. // On older platforms, returning std::unique_ptr<ListeningReporter>
  10302. // when the return type is std::unique_ptr<IStreamingReporter>
  10303. // doesn't compile without a std::move call. However, this causes
  10304. // a warning on newer platforms. Thus, we have to work around
  10305. // it a bit and downcast the pointer manually.
  10306. auto ret = std::unique_ptr<IStreamingReporter>(new ListeningReporter);
  10307. auto& multi = static_cast<ListeningReporter&>(*ret);
  10308. auto const& listeners = Catch::getRegistryHub().getReporterRegistry().getListeners();
  10309. for (auto const& listener : listeners) {
  10310. multi.addListener(listener->create(Catch::ReporterConfig(config)));
  10311. }
  10312. multi.addReporter(createReporter(config->getReporterName(), config));
  10313. return ret;
  10314. }
  10315. class TestGroup {
  10316. public:
  10317. explicit TestGroup(std::shared_ptr<Config> const& config)
  10318. : m_config{config}
  10319. , m_context{config, makeReporter(config)}
  10320. {
  10321. auto const& allTestCases = getAllTestCasesSorted(*m_config);
  10322. m_matches = m_config->testSpec().matchesByFilter(allTestCases, *m_config);
  10323. if (m_matches.empty()) {
  10324. for (auto const& test : allTestCases)
  10325. if (!test.isHidden())
  10326. m_tests.emplace(&test);
  10327. } else {
  10328. for (auto const& match : m_matches)
  10329. m_tests.insert(match.tests.begin(), match.tests.end());
  10330. }
  10331. }
  10332. Totals execute() {
  10333. Totals totals;
  10334. m_context.testGroupStarting(m_config->name(), 1, 1);
  10335. for (auto const& testCase : m_tests) {
  10336. if (!m_context.aborting())
  10337. totals += m_context.runTest(*testCase);
  10338. else
  10339. m_context.reporter().skipTest(*testCase);
  10340. }
  10341. for (auto const& match : m_matches) {
  10342. if (match.tests.empty()) {
  10343. m_context.reporter().noMatchingTestCases(match.name);
  10344. totals.error = -1;
  10345. }
  10346. }
  10347. m_context.testGroupEnded(m_config->name(), totals, 1, 1);
  10348. return totals;
  10349. }
  10350. private:
  10351. using Tests = std::set<TestCase const*>;
  10352. std::shared_ptr<Config> m_config;
  10353. RunContext m_context;
  10354. Tests m_tests;
  10355. TestSpec::Matches m_matches;
  10356. };
  10357. void applyFilenamesAsTags(Catch::IConfig const& config) {
  10358. auto& tests = const_cast<std::vector<TestCase>&>(getAllTestCasesSorted(config));
  10359. for (auto& testCase : tests) {
  10360. auto tags = testCase.tags;
  10361. std::string filename = testCase.lineInfo.file;
  10362. auto lastSlash = filename.find_last_of("\\/");
  10363. if (lastSlash != std::string::npos) {
  10364. filename.erase(0, lastSlash);
  10365. filename[0] = '#';
  10366. }
  10367. auto lastDot = filename.find_last_of('.');
  10368. if (lastDot != std::string::npos) {
  10369. filename.erase(lastDot);
  10370. }
  10371. tags.push_back(std::move(filename));
  10372. setTags(testCase, tags);
  10373. }
  10374. }
  10375. } // anon namespace
  10376. Session::Session() {
  10377. static bool alreadyInstantiated = false;
  10378. if( alreadyInstantiated ) {
  10379. CATCH_TRY { CATCH_INTERNAL_ERROR( "Only one instance of Catch::Session can ever be used" ); }
  10380. CATCH_CATCH_ALL { getMutableRegistryHub().registerStartupException(); }
  10381. }
  10382. // There cannot be exceptions at startup in no-exception mode.
  10383. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  10384. const auto& exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions();
  10385. if ( !exceptions.empty() ) {
  10386. config();
  10387. getCurrentMutableContext().setConfig(m_config);
  10388. m_startupExceptions = true;
  10389. Colour colourGuard( Colour::Red );
  10390. Catch::cerr() << "Errors occurred during startup!" << '\n';
  10391. // iterate over all exceptions and notify user
  10392. for ( const auto& ex_ptr : exceptions ) {
  10393. try {
  10394. std::rethrow_exception(ex_ptr);
  10395. } catch ( std::exception const& ex ) {
  10396. Catch::cerr() << Column( ex.what() ).indent(2) << '\n';
  10397. }
  10398. }
  10399. }
  10400. #endif
  10401. alreadyInstantiated = true;
  10402. m_cli = makeCommandLineParser( m_configData );
  10403. }
  10404. Session::~Session() {
  10405. Catch::cleanUp();
  10406. }
  10407. void Session::showHelp() const {
  10408. Catch::cout()
  10409. << "\nCatch v" << libraryVersion() << "\n"
  10410. << m_cli << std::endl
  10411. << "For more detailed usage please see the project docs\n" << std::endl;
  10412. }
  10413. void Session::libIdentify() {
  10414. Catch::cout()
  10415. << std::left << std::setw(16) << "description: " << "A Catch test executable\n"
  10416. << std::left << std::setw(16) << "category: " << "testframework\n"
  10417. << std::left << std::setw(16) << "framework: " << "Catch Test\n"
  10418. << std::left << std::setw(16) << "version: " << libraryVersion() << std::endl;
  10419. }
  10420. int Session::applyCommandLine( int argc, char const * const * argv ) {
  10421. if( m_startupExceptions )
  10422. return 1;
  10423. auto result = m_cli.parse( clara::Args( argc, argv ) );
  10424. if( !result ) {
  10425. config();
  10426. getCurrentMutableContext().setConfig(m_config);
  10427. Catch::cerr()
  10428. << Colour( Colour::Red )
  10429. << "\nError(s) in input:\n"
  10430. << Column( result.errorMessage() ).indent( 2 )
  10431. << "\n\n";
  10432. Catch::cerr() << "Run with -? for usage\n" << std::endl;
  10433. return MaxExitCode;
  10434. }
  10435. if( m_configData.showHelp )
  10436. showHelp();
  10437. if( m_configData.libIdentify )
  10438. libIdentify();
  10439. m_config.reset();
  10440. return 0;
  10441. }
  10442. #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)
  10443. int Session::applyCommandLine( int argc, wchar_t const * const * argv ) {
  10444. char **utf8Argv = new char *[ argc ];
  10445. for ( int i = 0; i < argc; ++i ) {
  10446. int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, NULL, 0, NULL, NULL );
  10447. utf8Argv[ i ] = new char[ bufSize ];
  10448. WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, NULL, NULL );
  10449. }
  10450. int returnCode = applyCommandLine( argc, utf8Argv );
  10451. for ( int i = 0; i < argc; ++i )
  10452. delete [] utf8Argv[ i ];
  10453. delete [] utf8Argv;
  10454. return returnCode;
  10455. }
  10456. #endif
  10457. void Session::useConfigData( ConfigData const& configData ) {
  10458. m_configData = configData;
  10459. m_config.reset();
  10460. }
  10461. int Session::run() {
  10462. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeStart ) != 0 ) {
  10463. Catch::cout() << "...waiting for enter/ return before starting" << std::endl;
  10464. static_cast<void>(std::getchar());
  10465. }
  10466. int exitCode = runInternal();
  10467. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeExit ) != 0 ) {
  10468. Catch::cout() << "...waiting for enter/ return before exiting, with code: " << exitCode << std::endl;
  10469. static_cast<void>(std::getchar());
  10470. }
  10471. return exitCode;
  10472. }
  10473. clara::Parser const& Session::cli() const {
  10474. return m_cli;
  10475. }
  10476. void Session::cli( clara::Parser const& newParser ) {
  10477. m_cli = newParser;
  10478. }
  10479. ConfigData& Session::configData() {
  10480. return m_configData;
  10481. }
  10482. Config& Session::config() {
  10483. if( !m_config )
  10484. m_config = std::make_shared<Config>( m_configData );
  10485. return *m_config;
  10486. }
  10487. int Session::runInternal() {
  10488. if( m_startupExceptions )
  10489. return 1;
  10490. if (m_configData.showHelp || m_configData.libIdentify) {
  10491. return 0;
  10492. }
  10493. CATCH_TRY {
  10494. config(); // Force config to be constructed
  10495. seedRng( *m_config );
  10496. if( m_configData.filenamesAsTags )
  10497. applyFilenamesAsTags( *m_config );
  10498. // Handle list request
  10499. if( Option<std::size_t> listed = list( m_config ) )
  10500. return static_cast<int>( *listed );
  10501. TestGroup tests { m_config };
  10502. auto const totals = tests.execute();
  10503. if( m_config->warnAboutNoTests() && totals.error == -1 )
  10504. return 2;
  10505. // Note that on unices only the lower 8 bits are usually used, clamping
  10506. // the return value to 255 prevents false negative when some multiple
  10507. // of 256 tests has failed
  10508. return (std::min) (MaxExitCode, (std::max) (totals.error, static_cast<int>(totals.assertions.failed)));
  10509. }
  10510. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  10511. catch( std::exception& ex ) {
  10512. Catch::cerr() << ex.what() << std::endl;
  10513. return MaxExitCode;
  10514. }
  10515. #endif
  10516. }
  10517. } // end namespace Catch
  10518. // end catch_session.cpp
  10519. // start catch_singletons.cpp
  10520. #include <vector>
  10521. namespace Catch {
  10522. namespace {
  10523. static auto getSingletons() -> std::vector<ISingleton*>*& {
  10524. static std::vector<ISingleton*>* g_singletons = nullptr;
  10525. if( !g_singletons )
  10526. g_singletons = new std::vector<ISingleton*>();
  10527. return g_singletons;
  10528. }
  10529. }
  10530. ISingleton::~ISingleton() {}
  10531. void addSingleton(ISingleton* singleton ) {
  10532. getSingletons()->push_back( singleton );
  10533. }
  10534. void cleanupSingletons() {
  10535. auto& singletons = getSingletons();
  10536. for( auto singleton : *singletons )
  10537. delete singleton;
  10538. delete singletons;
  10539. singletons = nullptr;
  10540. }
  10541. } // namespace Catch
  10542. // end catch_singletons.cpp
  10543. // start catch_startup_exception_registry.cpp
  10544. namespace Catch {
  10545. void StartupExceptionRegistry::add( std::exception_ptr const& exception ) noexcept {
  10546. CATCH_TRY {
  10547. m_exceptions.push_back(exception);
  10548. } CATCH_CATCH_ALL {
  10549. // If we run out of memory during start-up there's really not a lot more we can do about it
  10550. std::terminate();
  10551. }
  10552. }
  10553. std::vector<std::exception_ptr> const& StartupExceptionRegistry::getExceptions() const noexcept {
  10554. return m_exceptions;
  10555. }
  10556. } // end namespace Catch
  10557. // end catch_startup_exception_registry.cpp
  10558. // start catch_stream.cpp
  10559. #include <cstdio>
  10560. #include <iostream>
  10561. #include <fstream>
  10562. #include <sstream>
  10563. #include <vector>
  10564. #include <memory>
  10565. namespace Catch {
  10566. Catch::IStream::~IStream() = default;
  10567. namespace Detail { namespace {
  10568. template<typename WriterF, std::size_t bufferSize=256>
  10569. class StreamBufImpl : public std::streambuf {
  10570. char data[bufferSize];
  10571. WriterF m_writer;
  10572. public:
  10573. StreamBufImpl() {
  10574. setp( data, data + sizeof(data) );
  10575. }
  10576. ~StreamBufImpl() noexcept {
  10577. StreamBufImpl::sync();
  10578. }
  10579. private:
  10580. int overflow( int c ) override {
  10581. sync();
  10582. if( c != EOF ) {
  10583. if( pbase() == epptr() )
  10584. m_writer( std::string( 1, static_cast<char>( c ) ) );
  10585. else
  10586. sputc( static_cast<char>( c ) );
  10587. }
  10588. return 0;
  10589. }
  10590. int sync() override {
  10591. if( pbase() != pptr() ) {
  10592. m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) );
  10593. setp( pbase(), epptr() );
  10594. }
  10595. return 0;
  10596. }
  10597. };
  10598. ///////////////////////////////////////////////////////////////////////////
  10599. struct OutputDebugWriter {
  10600. void operator()( std::string const&str ) {
  10601. writeToDebugConsole( str );
  10602. }
  10603. };
  10604. ///////////////////////////////////////////////////////////////////////////
  10605. class FileStream : public IStream {
  10606. mutable std::ofstream m_ofs;
  10607. public:
  10608. FileStream( StringRef filename ) {
  10609. m_ofs.open( filename.c_str() );
  10610. CATCH_ENFORCE( !m_ofs.fail(), "Unable to open file: '" << filename << "'" );
  10611. }
  10612. ~FileStream() override = default;
  10613. public: // IStream
  10614. std::ostream& stream() const override {
  10615. return m_ofs;
  10616. }
  10617. };
  10618. ///////////////////////////////////////////////////////////////////////////
  10619. class CoutStream : public IStream {
  10620. mutable std::ostream m_os;
  10621. public:
  10622. // Store the streambuf from cout up-front because
  10623. // cout may get redirected when running tests
  10624. CoutStream() : m_os( Catch::cout().rdbuf() ) {}
  10625. ~CoutStream() override = default;
  10626. public: // IStream
  10627. std::ostream& stream() const override { return m_os; }
  10628. };
  10629. ///////////////////////////////////////////////////////////////////////////
  10630. class DebugOutStream : public IStream {
  10631. std::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf;
  10632. mutable std::ostream m_os;
  10633. public:
  10634. DebugOutStream()
  10635. : m_streamBuf( new StreamBufImpl<OutputDebugWriter>() ),
  10636. m_os( m_streamBuf.get() )
  10637. {}
  10638. ~DebugOutStream() override = default;
  10639. public: // IStream
  10640. std::ostream& stream() const override { return m_os; }
  10641. };
  10642. }} // namespace anon::detail
  10643. ///////////////////////////////////////////////////////////////////////////
  10644. auto makeStream( StringRef const &filename ) -> IStream const* {
  10645. if( filename.empty() )
  10646. return new Detail::CoutStream();
  10647. else if( filename[0] == '%' ) {
  10648. if( filename == "%debug" )
  10649. return new Detail::DebugOutStream();
  10650. else
  10651. CATCH_ERROR( "Unrecognised stream: '" << filename << "'" );
  10652. }
  10653. else
  10654. return new Detail::FileStream( filename );
  10655. }
  10656. // This class encapsulates the idea of a pool of ostringstreams that can be reused.
  10657. struct StringStreams {
  10658. std::vector<std::unique_ptr<std::ostringstream>> m_streams;
  10659. std::vector<std::size_t> m_unused;
  10660. std::ostringstream m_referenceStream; // Used for copy state/ flags from
  10661. auto add() -> std::size_t {
  10662. if( m_unused.empty() ) {
  10663. m_streams.push_back( std::unique_ptr<std::ostringstream>( new std::ostringstream ) );
  10664. return m_streams.size()-1;
  10665. }
  10666. else {
  10667. auto index = m_unused.back();
  10668. m_unused.pop_back();
  10669. return index;
  10670. }
  10671. }
  10672. void release( std::size_t index ) {
  10673. m_streams[index]->copyfmt( m_referenceStream ); // Restore initial flags and other state
  10674. m_unused.push_back(index);
  10675. }
  10676. };
  10677. ReusableStringStream::ReusableStringStream()
  10678. : m_index( Singleton<StringStreams>::getMutable().add() ),
  10679. m_oss( Singleton<StringStreams>::getMutable().m_streams[m_index].get() )
  10680. {}
  10681. ReusableStringStream::~ReusableStringStream() {
  10682. static_cast<std::ostringstream*>( m_oss )->str("");
  10683. m_oss->clear();
  10684. Singleton<StringStreams>::getMutable().release( m_index );
  10685. }
  10686. auto ReusableStringStream::str() const -> std::string {
  10687. return static_cast<std::ostringstream*>( m_oss )->str();
  10688. }
  10689. ///////////////////////////////////////////////////////////////////////////
  10690. #ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions
  10691. std::ostream& cout() { return std::cout; }
  10692. std::ostream& cerr() { return std::cerr; }
  10693. std::ostream& clog() { return std::clog; }
  10694. #endif
  10695. }
  10696. // end catch_stream.cpp
  10697. // start catch_string_manip.cpp
  10698. #include <algorithm>
  10699. #include <ostream>
  10700. #include <cstring>
  10701. #include <cctype>
  10702. #include <vector>
  10703. namespace Catch {
  10704. namespace {
  10705. char toLowerCh(char c) {
  10706. return static_cast<char>( std::tolower( c ) );
  10707. }
  10708. }
  10709. bool startsWith( std::string const& s, std::string const& prefix ) {
  10710. return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
  10711. }
  10712. bool startsWith( std::string const& s, char prefix ) {
  10713. return !s.empty() && s[0] == prefix;
  10714. }
  10715. bool endsWith( std::string const& s, std::string const& suffix ) {
  10716. return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
  10717. }
  10718. bool endsWith( std::string const& s, char suffix ) {
  10719. return !s.empty() && s[s.size()-1] == suffix;
  10720. }
  10721. bool contains( std::string const& s, std::string const& infix ) {
  10722. return s.find( infix ) != std::string::npos;
  10723. }
  10724. void toLowerInPlace( std::string& s ) {
  10725. std::transform( s.begin(), s.end(), s.begin(), toLowerCh );
  10726. }
  10727. std::string toLower( std::string const& s ) {
  10728. std::string lc = s;
  10729. toLowerInPlace( lc );
  10730. return lc;
  10731. }
  10732. std::string trim( std::string const& str ) {
  10733. static char const* whitespaceChars = "\n\r\t ";
  10734. std::string::size_type start = str.find_first_not_of( whitespaceChars );
  10735. std::string::size_type end = str.find_last_not_of( whitespaceChars );
  10736. return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string();
  10737. }
  10738. bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) {
  10739. bool replaced = false;
  10740. std::size_t i = str.find( replaceThis );
  10741. while( i != std::string::npos ) {
  10742. replaced = true;
  10743. str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() );
  10744. if( i < str.size()-withThis.size() )
  10745. i = str.find( replaceThis, i+withThis.size() );
  10746. else
  10747. i = std::string::npos;
  10748. }
  10749. return replaced;
  10750. }
  10751. std::vector<StringRef> splitStringRef( StringRef str, char delimiter ) {
  10752. std::vector<StringRef> subStrings;
  10753. std::size_t start = 0;
  10754. for(std::size_t pos = 0; pos < str.size(); ++pos ) {
  10755. if( str[pos] == delimiter ) {
  10756. if( pos - start > 1 )
  10757. subStrings.push_back( str.substr( start, pos-start ) );
  10758. start = pos+1;
  10759. }
  10760. }
  10761. if( start < str.size() )
  10762. subStrings.push_back( str.substr( start, str.size()-start ) );
  10763. return subStrings;
  10764. }
  10765. pluralise::pluralise( std::size_t count, std::string const& label )
  10766. : m_count( count ),
  10767. m_label( label )
  10768. {}
  10769. std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) {
  10770. os << pluraliser.m_count << ' ' << pluraliser.m_label;
  10771. if( pluraliser.m_count != 1 )
  10772. os << 's';
  10773. return os;
  10774. }
  10775. }
  10776. // end catch_string_manip.cpp
  10777. // start catch_stringref.cpp
  10778. #if defined(__clang__)
  10779. # pragma clang diagnostic push
  10780. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  10781. #endif
  10782. #include <ostream>
  10783. #include <cstring>
  10784. #include <cstdint>
  10785. namespace {
  10786. const uint32_t byte_2_lead = 0xC0;
  10787. const uint32_t byte_3_lead = 0xE0;
  10788. const uint32_t byte_4_lead = 0xF0;
  10789. }
  10790. namespace Catch {
  10791. StringRef::StringRef( char const* rawChars ) noexcept
  10792. : StringRef( rawChars, static_cast<StringRef::size_type>(std::strlen(rawChars) ) )
  10793. {}
  10794. StringRef::operator std::string() const {
  10795. return std::string( m_start, m_size );
  10796. }
  10797. void StringRef::swap( StringRef& other ) noexcept {
  10798. std::swap( m_start, other.m_start );
  10799. std::swap( m_size, other.m_size );
  10800. std::swap( m_data, other.m_data );
  10801. }
  10802. auto StringRef::c_str() const -> char const* {
  10803. if( !isSubstring() )
  10804. return m_start;
  10805. const_cast<StringRef *>( this )->takeOwnership();
  10806. return m_data;
  10807. }
  10808. auto StringRef::currentData() const noexcept -> char const* {
  10809. return m_start;
  10810. }
  10811. auto StringRef::isOwned() const noexcept -> bool {
  10812. return m_data != nullptr;
  10813. }
  10814. auto StringRef::isSubstring() const noexcept -> bool {
  10815. return m_start[m_size] != '\0';
  10816. }
  10817. void StringRef::takeOwnership() {
  10818. if( !isOwned() ) {
  10819. m_data = new char[m_size+1];
  10820. memcpy( m_data, m_start, m_size );
  10821. m_data[m_size] = '\0';
  10822. }
  10823. }
  10824. auto StringRef::substr( size_type start, size_type size ) const noexcept -> StringRef {
  10825. if( start < m_size )
  10826. return StringRef( m_start+start, size );
  10827. else
  10828. return StringRef();
  10829. }
  10830. auto StringRef::operator == ( StringRef const& other ) const noexcept -> bool {
  10831. return
  10832. size() == other.size() &&
  10833. (std::strncmp( m_start, other.m_start, size() ) == 0);
  10834. }
  10835. auto StringRef::operator != ( StringRef const& other ) const noexcept -> bool {
  10836. return !operator==( other );
  10837. }
  10838. auto StringRef::operator[](size_type index) const noexcept -> char {
  10839. return m_start[index];
  10840. }
  10841. auto StringRef::numberOfCharacters() const noexcept -> size_type {
  10842. size_type noChars = m_size;
  10843. // Make adjustments for uft encodings
  10844. for( size_type i=0; i < m_size; ++i ) {
  10845. char c = m_start[i];
  10846. if( ( c & byte_2_lead ) == byte_2_lead ) {
  10847. noChars--;
  10848. if (( c & byte_3_lead ) == byte_3_lead )
  10849. noChars--;
  10850. if( ( c & byte_4_lead ) == byte_4_lead )
  10851. noChars--;
  10852. }
  10853. }
  10854. return noChars;
  10855. }
  10856. auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string {
  10857. std::string str;
  10858. str.reserve( lhs.size() + rhs.size() );
  10859. str += lhs;
  10860. str += rhs;
  10861. return str;
  10862. }
  10863. auto operator + ( StringRef const& lhs, const char* rhs ) -> std::string {
  10864. return std::string( lhs ) + std::string( rhs );
  10865. }
  10866. auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string {
  10867. return std::string( lhs ) + std::string( rhs );
  10868. }
  10869. auto operator << ( std::ostream& os, StringRef const& str ) -> std::ostream& {
  10870. return os.write(str.currentData(), str.size());
  10871. }
  10872. auto operator+=( std::string& lhs, StringRef const& rhs ) -> std::string& {
  10873. lhs.append(rhs.currentData(), rhs.size());
  10874. return lhs;
  10875. }
  10876. } // namespace Catch
  10877. #if defined(__clang__)
  10878. # pragma clang diagnostic pop
  10879. #endif
  10880. // end catch_stringref.cpp
  10881. // start catch_tag_alias.cpp
  10882. namespace Catch {
  10883. TagAlias::TagAlias(std::string const & _tag, SourceLineInfo _lineInfo): tag(_tag), lineInfo(_lineInfo) {}
  10884. }
  10885. // end catch_tag_alias.cpp
  10886. // start catch_tag_alias_autoregistrar.cpp
  10887. namespace Catch {
  10888. RegistrarForTagAliases::RegistrarForTagAliases(char const* alias, char const* tag, SourceLineInfo const& lineInfo) {
  10889. CATCH_TRY {
  10890. getMutableRegistryHub().registerTagAlias(alias, tag, lineInfo);
  10891. } CATCH_CATCH_ALL {
  10892. // Do not throw when constructing global objects, instead register the exception to be processed later
  10893. getMutableRegistryHub().registerStartupException();
  10894. }
  10895. }
  10896. }
  10897. // end catch_tag_alias_autoregistrar.cpp
  10898. // start catch_tag_alias_registry.cpp
  10899. #include <sstream>
  10900. namespace Catch {
  10901. TagAliasRegistry::~TagAliasRegistry() {}
  10902. TagAlias const* TagAliasRegistry::find( std::string const& alias ) const {
  10903. auto it = m_registry.find( alias );
  10904. if( it != m_registry.end() )
  10905. return &(it->second);
  10906. else
  10907. return nullptr;
  10908. }
  10909. std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const {
  10910. std::string expandedTestSpec = unexpandedTestSpec;
  10911. for( auto const& registryKvp : m_registry ) {
  10912. std::size_t pos = expandedTestSpec.find( registryKvp.first );
  10913. if( pos != std::string::npos ) {
  10914. expandedTestSpec = expandedTestSpec.substr( 0, pos ) +
  10915. registryKvp.second.tag +
  10916. expandedTestSpec.substr( pos + registryKvp.first.size() );
  10917. }
  10918. }
  10919. return expandedTestSpec;
  10920. }
  10921. void TagAliasRegistry::add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) {
  10922. CATCH_ENFORCE( startsWith(alias, "[@") && endsWith(alias, ']'),
  10923. "error: tag alias, '" << alias << "' is not of the form [@alias name].\n" << lineInfo );
  10924. CATCH_ENFORCE( m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second,
  10925. "error: tag alias, '" << alias << "' already registered.\n"
  10926. << "\tFirst seen at: " << find(alias)->lineInfo << "\n"
  10927. << "\tRedefined at: " << lineInfo );
  10928. }
  10929. ITagAliasRegistry::~ITagAliasRegistry() {}
  10930. ITagAliasRegistry const& ITagAliasRegistry::get() {
  10931. return getRegistryHub().getTagAliasRegistry();
  10932. }
  10933. } // end namespace Catch
  10934. // end catch_tag_alias_registry.cpp
  10935. // start catch_test_case_info.cpp
  10936. #include <cctype>
  10937. #include <exception>
  10938. #include <algorithm>
  10939. #include <sstream>
  10940. namespace Catch {
  10941. namespace {
  10942. TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) {
  10943. if( startsWith( tag, '.' ) ||
  10944. tag == "!hide" )
  10945. return TestCaseInfo::IsHidden;
  10946. else if( tag == "!throws" )
  10947. return TestCaseInfo::Throws;
  10948. else if( tag == "!shouldfail" )
  10949. return TestCaseInfo::ShouldFail;
  10950. else if( tag == "!mayfail" )
  10951. return TestCaseInfo::MayFail;
  10952. else if( tag == "!nonportable" )
  10953. return TestCaseInfo::NonPortable;
  10954. else if( tag == "!benchmark" )
  10955. return static_cast<TestCaseInfo::SpecialProperties>( TestCaseInfo::Benchmark | TestCaseInfo::IsHidden );
  10956. else
  10957. return TestCaseInfo::None;
  10958. }
  10959. bool isReservedTag( std::string const& tag ) {
  10960. return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !std::isalnum( static_cast<unsigned char>(tag[0]) );
  10961. }
  10962. void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) {
  10963. CATCH_ENFORCE( !isReservedTag(tag),
  10964. "Tag name: [" << tag << "] is not allowed.\n"
  10965. << "Tag names starting with non alphanumeric characters are reserved\n"
  10966. << _lineInfo );
  10967. }
  10968. }
  10969. TestCase makeTestCase( ITestInvoker* _testCase,
  10970. std::string const& _className,
  10971. NameAndTags const& nameAndTags,
  10972. SourceLineInfo const& _lineInfo )
  10973. {
  10974. bool isHidden = false;
  10975. // Parse out tags
  10976. std::vector<std::string> tags;
  10977. std::string desc, tag;
  10978. bool inTag = false;
  10979. std::string _descOrTags = nameAndTags.tags;
  10980. for (char c : _descOrTags) {
  10981. if( !inTag ) {
  10982. if( c == '[' )
  10983. inTag = true;
  10984. else
  10985. desc += c;
  10986. }
  10987. else {
  10988. if( c == ']' ) {
  10989. TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag );
  10990. if( ( prop & TestCaseInfo::IsHidden ) != 0 )
  10991. isHidden = true;
  10992. else if( prop == TestCaseInfo::None )
  10993. enforceNotReservedTag( tag, _lineInfo );
  10994. // Merged hide tags like `[.approvals]` should be added as
  10995. // `[.][approvals]`. The `[.]` is added at later point, so
  10996. // we only strip the prefix
  10997. if (startsWith(tag, '.') && tag.size() > 1) {
  10998. tag.erase(0, 1);
  10999. }
  11000. tags.push_back( tag );
  11001. tag.clear();
  11002. inTag = false;
  11003. }
  11004. else
  11005. tag += c;
  11006. }
  11007. }
  11008. if( isHidden ) {
  11009. tags.push_back( "." );
  11010. }
  11011. TestCaseInfo info( nameAndTags.name, _className, desc, tags, _lineInfo );
  11012. return TestCase( _testCase, std::move(info) );
  11013. }
  11014. void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags ) {
  11015. std::sort(begin(tags), end(tags));
  11016. tags.erase(std::unique(begin(tags), end(tags)), end(tags));
  11017. testCaseInfo.lcaseTags.clear();
  11018. for( auto const& tag : tags ) {
  11019. std::string lcaseTag = toLower( tag );
  11020. testCaseInfo.properties = static_cast<TestCaseInfo::SpecialProperties>( testCaseInfo.properties | parseSpecialTag( lcaseTag ) );
  11021. testCaseInfo.lcaseTags.push_back( lcaseTag );
  11022. }
  11023. testCaseInfo.tags = std::move(tags);
  11024. }
  11025. TestCaseInfo::TestCaseInfo( std::string const& _name,
  11026. std::string const& _className,
  11027. std::string const& _description,
  11028. std::vector<std::string> const& _tags,
  11029. SourceLineInfo const& _lineInfo )
  11030. : name( _name ),
  11031. className( _className ),
  11032. description( _description ),
  11033. lineInfo( _lineInfo ),
  11034. properties( None )
  11035. {
  11036. setTags( *this, _tags );
  11037. }
  11038. bool TestCaseInfo::isHidden() const {
  11039. return ( properties & IsHidden ) != 0;
  11040. }
  11041. bool TestCaseInfo::throws() const {
  11042. return ( properties & Throws ) != 0;
  11043. }
  11044. bool TestCaseInfo::okToFail() const {
  11045. return ( properties & (ShouldFail | MayFail ) ) != 0;
  11046. }
  11047. bool TestCaseInfo::expectedToFail() const {
  11048. return ( properties & (ShouldFail ) ) != 0;
  11049. }
  11050. std::string TestCaseInfo::tagsAsString() const {
  11051. std::string ret;
  11052. // '[' and ']' per tag
  11053. std::size_t full_size = 2 * tags.size();
  11054. for (const auto& tag : tags) {
  11055. full_size += tag.size();
  11056. }
  11057. ret.reserve(full_size);
  11058. for (const auto& tag : tags) {
  11059. ret.push_back('[');
  11060. ret.append(tag);
  11061. ret.push_back(']');
  11062. }
  11063. return ret;
  11064. }
  11065. TestCase::TestCase( ITestInvoker* testCase, TestCaseInfo&& info ) : TestCaseInfo( std::move(info) ), test( testCase ) {}
  11066. TestCase TestCase::withName( std::string const& _newName ) const {
  11067. TestCase other( *this );
  11068. other.name = _newName;
  11069. return other;
  11070. }
  11071. void TestCase::invoke() const {
  11072. test->invoke();
  11073. }
  11074. bool TestCase::operator == ( TestCase const& other ) const {
  11075. return test.get() == other.test.get() &&
  11076. name == other.name &&
  11077. className == other.className;
  11078. }
  11079. bool TestCase::operator < ( TestCase const& other ) const {
  11080. return name < other.name;
  11081. }
  11082. TestCaseInfo const& TestCase::getTestCaseInfo() const
  11083. {
  11084. return *this;
  11085. }
  11086. } // end namespace Catch
  11087. // end catch_test_case_info.cpp
  11088. // start catch_test_case_registry_impl.cpp
  11089. #include <sstream>
  11090. namespace Catch {
  11091. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases ) {
  11092. std::vector<TestCase> sorted = unsortedTestCases;
  11093. switch( config.runOrder() ) {
  11094. case RunTests::InLexicographicalOrder:
  11095. std::sort( sorted.begin(), sorted.end() );
  11096. break;
  11097. case RunTests::InRandomOrder:
  11098. seedRng( config );
  11099. std::shuffle( sorted.begin(), sorted.end(), rng() );
  11100. break;
  11101. case RunTests::InDeclarationOrder:
  11102. // already in declaration order
  11103. break;
  11104. }
  11105. return sorted;
  11106. }
  11107. bool isThrowSafe( TestCase const& testCase, IConfig const& config ) {
  11108. return !testCase.throws() || config.allowThrows();
  11109. }
  11110. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ) {
  11111. return testSpec.matches( testCase ) && isThrowSafe( testCase, config );
  11112. }
  11113. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions ) {
  11114. std::set<TestCase> seenFunctions;
  11115. for( auto const& function : functions ) {
  11116. auto prev = seenFunctions.insert( function );
  11117. CATCH_ENFORCE( prev.second,
  11118. "error: TEST_CASE( \"" << function.name << "\" ) already defined.\n"
  11119. << "\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo << "\n"
  11120. << "\tRedefined at " << function.getTestCaseInfo().lineInfo );
  11121. }
  11122. }
  11123. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config ) {
  11124. std::vector<TestCase> filtered;
  11125. filtered.reserve( testCases.size() );
  11126. for (auto const& testCase : testCases) {
  11127. if ((!testSpec.hasFilters() && !testCase.isHidden()) ||
  11128. (testSpec.hasFilters() && matchTest(testCase, testSpec, config))) {
  11129. filtered.push_back(testCase);
  11130. }
  11131. }
  11132. return filtered;
  11133. }
  11134. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config ) {
  11135. return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config );
  11136. }
  11137. void TestRegistry::registerTest( TestCase const& testCase ) {
  11138. std::string name = testCase.getTestCaseInfo().name;
  11139. if( name.empty() ) {
  11140. ReusableStringStream rss;
  11141. rss << "Anonymous test case " << ++m_unnamedCount;
  11142. return registerTest( testCase.withName( rss.str() ) );
  11143. }
  11144. m_functions.push_back( testCase );
  11145. }
  11146. std::vector<TestCase> const& TestRegistry::getAllTests() const {
  11147. return m_functions;
  11148. }
  11149. std::vector<TestCase> const& TestRegistry::getAllTestsSorted( IConfig const& config ) const {
  11150. if( m_sortedFunctions.empty() )
  11151. enforceNoDuplicateTestCases( m_functions );
  11152. if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) {
  11153. m_sortedFunctions = sortTests( config, m_functions );
  11154. m_currentSortOrder = config.runOrder();
  11155. }
  11156. return m_sortedFunctions;
  11157. }
  11158. ///////////////////////////////////////////////////////////////////////////
  11159. TestInvokerAsFunction::TestInvokerAsFunction( void(*testAsFunction)() ) noexcept : m_testAsFunction( testAsFunction ) {}
  11160. void TestInvokerAsFunction::invoke() const {
  11161. m_testAsFunction();
  11162. }
  11163. std::string extractClassName( StringRef const& classOrQualifiedMethodName ) {
  11164. std::string className = classOrQualifiedMethodName;
  11165. if( startsWith( className, '&' ) )
  11166. {
  11167. std::size_t lastColons = className.rfind( "::" );
  11168. std::size_t penultimateColons = className.rfind( "::", lastColons-1 );
  11169. if( penultimateColons == std::string::npos )
  11170. penultimateColons = 1;
  11171. className = className.substr( penultimateColons, lastColons-penultimateColons );
  11172. }
  11173. return className;
  11174. }
  11175. } // end namespace Catch
  11176. // end catch_test_case_registry_impl.cpp
  11177. // start catch_test_case_tracker.cpp
  11178. #include <algorithm>
  11179. #include <cassert>
  11180. #include <stdexcept>
  11181. #include <memory>
  11182. #include <sstream>
  11183. #if defined(__clang__)
  11184. # pragma clang diagnostic push
  11185. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  11186. #endif
  11187. namespace Catch {
  11188. namespace TestCaseTracking {
  11189. NameAndLocation::NameAndLocation( std::string const& _name, SourceLineInfo const& _location )
  11190. : name( _name ),
  11191. location( _location )
  11192. {}
  11193. ITracker::~ITracker() = default;
  11194. ITracker& TrackerContext::startRun() {
  11195. m_rootTracker = std::make_shared<SectionTracker>( NameAndLocation( "{root}", CATCH_INTERNAL_LINEINFO ), *this, nullptr );
  11196. m_currentTracker = nullptr;
  11197. m_runState = Executing;
  11198. return *m_rootTracker;
  11199. }
  11200. void TrackerContext::endRun() {
  11201. m_rootTracker.reset();
  11202. m_currentTracker = nullptr;
  11203. m_runState = NotStarted;
  11204. }
  11205. void TrackerContext::startCycle() {
  11206. m_currentTracker = m_rootTracker.get();
  11207. m_runState = Executing;
  11208. }
  11209. void TrackerContext::completeCycle() {
  11210. m_runState = CompletedCycle;
  11211. }
  11212. bool TrackerContext::completedCycle() const {
  11213. return m_runState == CompletedCycle;
  11214. }
  11215. ITracker& TrackerContext::currentTracker() {
  11216. return *m_currentTracker;
  11217. }
  11218. void TrackerContext::setCurrentTracker( ITracker* tracker ) {
  11219. m_currentTracker = tracker;
  11220. }
  11221. TrackerBase::TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  11222. : m_nameAndLocation( nameAndLocation ),
  11223. m_ctx( ctx ),
  11224. m_parent( parent )
  11225. {}
  11226. NameAndLocation const& TrackerBase::nameAndLocation() const {
  11227. return m_nameAndLocation;
  11228. }
  11229. bool TrackerBase::isComplete() const {
  11230. return m_runState == CompletedSuccessfully || m_runState == Failed;
  11231. }
  11232. bool TrackerBase::isSuccessfullyCompleted() const {
  11233. return m_runState == CompletedSuccessfully;
  11234. }
  11235. bool TrackerBase::isOpen() const {
  11236. return m_runState != NotStarted && !isComplete();
  11237. }
  11238. bool TrackerBase::hasChildren() const {
  11239. return !m_children.empty();
  11240. }
  11241. void TrackerBase::addChild( ITrackerPtr const& child ) {
  11242. m_children.push_back( child );
  11243. }
  11244. ITrackerPtr TrackerBase::findChild( NameAndLocation const& nameAndLocation ) {
  11245. auto it = std::find_if( m_children.begin(), m_children.end(),
  11246. [&nameAndLocation]( ITrackerPtr const& tracker ){
  11247. return
  11248. tracker->nameAndLocation().location == nameAndLocation.location &&
  11249. tracker->nameAndLocation().name == nameAndLocation.name;
  11250. } );
  11251. return( it != m_children.end() )
  11252. ? *it
  11253. : nullptr;
  11254. }
  11255. ITracker& TrackerBase::parent() {
  11256. assert( m_parent ); // Should always be non-null except for root
  11257. return *m_parent;
  11258. }
  11259. void TrackerBase::openChild() {
  11260. if( m_runState != ExecutingChildren ) {
  11261. m_runState = ExecutingChildren;
  11262. if( m_parent )
  11263. m_parent->openChild();
  11264. }
  11265. }
  11266. bool TrackerBase::isSectionTracker() const { return false; }
  11267. bool TrackerBase::isGeneratorTracker() const { return false; }
  11268. void TrackerBase::open() {
  11269. m_runState = Executing;
  11270. moveToThis();
  11271. if( m_parent )
  11272. m_parent->openChild();
  11273. }
  11274. void TrackerBase::close() {
  11275. // Close any still open children (e.g. generators)
  11276. while( &m_ctx.currentTracker() != this )
  11277. m_ctx.currentTracker().close();
  11278. switch( m_runState ) {
  11279. case NeedsAnotherRun:
  11280. break;
  11281. case Executing:
  11282. m_runState = CompletedSuccessfully;
  11283. break;
  11284. case ExecutingChildren:
  11285. if( std::all_of(m_children.begin(), m_children.end(), [](ITrackerPtr const& t){ return t->isComplete(); }) )
  11286. m_runState = CompletedSuccessfully;
  11287. break;
  11288. case NotStarted:
  11289. case CompletedSuccessfully:
  11290. case Failed:
  11291. CATCH_INTERNAL_ERROR( "Illogical state: " << m_runState );
  11292. default:
  11293. CATCH_INTERNAL_ERROR( "Unknown state: " << m_runState );
  11294. }
  11295. moveToParent();
  11296. m_ctx.completeCycle();
  11297. }
  11298. void TrackerBase::fail() {
  11299. m_runState = Failed;
  11300. if( m_parent )
  11301. m_parent->markAsNeedingAnotherRun();
  11302. moveToParent();
  11303. m_ctx.completeCycle();
  11304. }
  11305. void TrackerBase::markAsNeedingAnotherRun() {
  11306. m_runState = NeedsAnotherRun;
  11307. }
  11308. void TrackerBase::moveToParent() {
  11309. assert( m_parent );
  11310. m_ctx.setCurrentTracker( m_parent );
  11311. }
  11312. void TrackerBase::moveToThis() {
  11313. m_ctx.setCurrentTracker( this );
  11314. }
  11315. SectionTracker::SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  11316. : TrackerBase( nameAndLocation, ctx, parent )
  11317. {
  11318. if( parent ) {
  11319. while( !parent->isSectionTracker() )
  11320. parent = &parent->parent();
  11321. SectionTracker& parentSection = static_cast<SectionTracker&>( *parent );
  11322. addNextFilters( parentSection.m_filters );
  11323. }
  11324. }
  11325. bool SectionTracker::isComplete() const {
  11326. bool complete = true;
  11327. if ((m_filters.empty() || m_filters[0] == "") ||
  11328. std::find(m_filters.begin(), m_filters.end(),
  11329. m_nameAndLocation.name) != m_filters.end())
  11330. complete = TrackerBase::isComplete();
  11331. return complete;
  11332. }
  11333. bool SectionTracker::isSectionTracker() const { return true; }
  11334. SectionTracker& SectionTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ) {
  11335. std::shared_ptr<SectionTracker> section;
  11336. ITracker& currentTracker = ctx.currentTracker();
  11337. if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  11338. assert( childTracker );
  11339. assert( childTracker->isSectionTracker() );
  11340. section = std::static_pointer_cast<SectionTracker>( childTracker );
  11341. }
  11342. else {
  11343. section = std::make_shared<SectionTracker>( nameAndLocation, ctx, &currentTracker );
  11344. currentTracker.addChild( section );
  11345. }
  11346. if( !ctx.completedCycle() )
  11347. section->tryOpen();
  11348. return *section;
  11349. }
  11350. void SectionTracker::tryOpen() {
  11351. if( !isComplete() && (m_filters.empty() || m_filters[0].empty() || m_filters[0] == m_nameAndLocation.name ) )
  11352. open();
  11353. }
  11354. void SectionTracker::addInitialFilters( std::vector<std::string> const& filters ) {
  11355. if( !filters.empty() ) {
  11356. m_filters.push_back(""); // Root - should never be consulted
  11357. m_filters.push_back(""); // Test Case - not a section filter
  11358. m_filters.insert( m_filters.end(), filters.begin(), filters.end() );
  11359. }
  11360. }
  11361. void SectionTracker::addNextFilters( std::vector<std::string> const& filters ) {
  11362. if( filters.size() > 1 )
  11363. m_filters.insert( m_filters.end(), ++filters.begin(), filters.end() );
  11364. }
  11365. } // namespace TestCaseTracking
  11366. using TestCaseTracking::ITracker;
  11367. using TestCaseTracking::TrackerContext;
  11368. using TestCaseTracking::SectionTracker;
  11369. } // namespace Catch
  11370. #if defined(__clang__)
  11371. # pragma clang diagnostic pop
  11372. #endif
  11373. // end catch_test_case_tracker.cpp
  11374. // start catch_test_registry.cpp
  11375. namespace Catch {
  11376. auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker* {
  11377. return new(std::nothrow) TestInvokerAsFunction( testAsFunction );
  11378. }
  11379. NameAndTags::NameAndTags( StringRef const& name_ , StringRef const& tags_ ) noexcept : name( name_ ), tags( tags_ ) {}
  11380. AutoReg::AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept {
  11381. CATCH_TRY {
  11382. getMutableRegistryHub()
  11383. .registerTest(
  11384. makeTestCase(
  11385. invoker,
  11386. extractClassName( classOrMethod ),
  11387. nameAndTags,
  11388. lineInfo));
  11389. } CATCH_CATCH_ALL {
  11390. // Do not throw when constructing global objects, instead register the exception to be processed later
  11391. getMutableRegistryHub().registerStartupException();
  11392. }
  11393. }
  11394. AutoReg::~AutoReg() = default;
  11395. }
  11396. // end catch_test_registry.cpp
  11397. // start catch_test_spec.cpp
  11398. #include <algorithm>
  11399. #include <string>
  11400. #include <vector>
  11401. #include <memory>
  11402. namespace Catch {
  11403. TestSpec::Pattern::Pattern( std::string const& name )
  11404. : m_name( name )
  11405. {}
  11406. TestSpec::Pattern::~Pattern() = default;
  11407. std::string const& TestSpec::Pattern::name() const {
  11408. return m_name;
  11409. }
  11410. TestSpec::NamePattern::NamePattern( std::string const& name, std::string const& filterString )
  11411. : Pattern( filterString )
  11412. , m_wildcardPattern( toLower( name ), CaseSensitive::No )
  11413. {}
  11414. bool TestSpec::NamePattern::matches( TestCaseInfo const& testCase ) const {
  11415. return m_wildcardPattern.matches( toLower( testCase.name ) );
  11416. }
  11417. TestSpec::TagPattern::TagPattern( std::string const& tag, std::string const& filterString )
  11418. : Pattern( filterString )
  11419. , m_tag( toLower( tag ) )
  11420. {}
  11421. bool TestSpec::TagPattern::matches( TestCaseInfo const& testCase ) const {
  11422. return std::find(begin(testCase.lcaseTags),
  11423. end(testCase.lcaseTags),
  11424. m_tag) != end(testCase.lcaseTags);
  11425. }
  11426. TestSpec::ExcludedPattern::ExcludedPattern( PatternPtr const& underlyingPattern )
  11427. : Pattern( underlyingPattern->name() )
  11428. , m_underlyingPattern( underlyingPattern )
  11429. {}
  11430. bool TestSpec::ExcludedPattern::matches( TestCaseInfo const& testCase ) const {
  11431. return !m_underlyingPattern->matches( testCase );
  11432. }
  11433. bool TestSpec::Filter::matches( TestCaseInfo const& testCase ) const {
  11434. return std::all_of( m_patterns.begin(), m_patterns.end(), [&]( PatternPtr const& p ){ return p->matches( testCase ); } );
  11435. }
  11436. std::string TestSpec::Filter::name() const {
  11437. std::string name;
  11438. for( auto const& p : m_patterns )
  11439. name += p->name();
  11440. return name;
  11441. }
  11442. bool TestSpec::hasFilters() const {
  11443. return !m_filters.empty();
  11444. }
  11445. bool TestSpec::matches( TestCaseInfo const& testCase ) const {
  11446. return std::any_of( m_filters.begin(), m_filters.end(), [&]( Filter const& f ){ return f.matches( testCase ); } );
  11447. }
  11448. TestSpec::Matches TestSpec::matchesByFilter( std::vector<TestCase> const& testCases, IConfig const& config ) const
  11449. {
  11450. Matches matches( m_filters.size() );
  11451. std::transform( m_filters.begin(), m_filters.end(), matches.begin(), [&]( Filter const& filter ){
  11452. std::vector<TestCase const*> currentMatches;
  11453. for( auto const& test : testCases )
  11454. if( isThrowSafe( test, config ) && filter.matches( test ) )
  11455. currentMatches.emplace_back( &test );
  11456. return FilterMatch{ filter.name(), currentMatches };
  11457. } );
  11458. return matches;
  11459. }
  11460. }
  11461. // end catch_test_spec.cpp
  11462. // start catch_test_spec_parser.cpp
  11463. namespace Catch {
  11464. TestSpecParser::TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {}
  11465. TestSpecParser& TestSpecParser::parse( std::string const& arg ) {
  11466. m_mode = None;
  11467. m_exclusion = false;
  11468. m_arg = m_tagAliases->expandAliases( arg );
  11469. m_escapeChars.clear();
  11470. m_substring.reserve(m_arg.size());
  11471. m_patternName.reserve(m_arg.size());
  11472. for( m_pos = 0; m_pos < m_arg.size(); ++m_pos )
  11473. visitChar( m_arg[m_pos] );
  11474. endMode();
  11475. return *this;
  11476. }
  11477. TestSpec TestSpecParser::testSpec() {
  11478. addFilter();
  11479. return m_testSpec;
  11480. }
  11481. void TestSpecParser::visitChar( char c ) {
  11482. if( c == ',' ) {
  11483. endMode();
  11484. addFilter();
  11485. return;
  11486. }
  11487. switch( m_mode ) {
  11488. case None:
  11489. if( processNoneChar( c ) )
  11490. return;
  11491. break;
  11492. case Name:
  11493. processNameChar( c );
  11494. break;
  11495. case EscapedName:
  11496. endMode();
  11497. break;
  11498. default:
  11499. case Tag:
  11500. case QuotedName:
  11501. if( processOtherChar( c ) )
  11502. return;
  11503. break;
  11504. }
  11505. m_substring += c;
  11506. if( !isControlChar( c ) )
  11507. m_patternName += c;
  11508. }
  11509. // Two of the processing methods return true to signal the caller to return
  11510. // without adding the given character to the current pattern strings
  11511. bool TestSpecParser::processNoneChar( char c ) {
  11512. switch( c ) {
  11513. case ' ':
  11514. return true;
  11515. case '~':
  11516. m_exclusion = true;
  11517. return false;
  11518. case '[':
  11519. startNewMode( Tag );
  11520. return false;
  11521. case '"':
  11522. startNewMode( QuotedName );
  11523. return false;
  11524. case '\\':
  11525. escape();
  11526. return true;
  11527. default:
  11528. startNewMode( Name );
  11529. return false;
  11530. }
  11531. }
  11532. void TestSpecParser::processNameChar( char c ) {
  11533. if( c == '[' ) {
  11534. if( m_substring == "exclude:" )
  11535. m_exclusion = true;
  11536. else
  11537. endMode();
  11538. startNewMode( Tag );
  11539. }
  11540. }
  11541. bool TestSpecParser::processOtherChar( char c ) {
  11542. if( !isControlChar( c ) )
  11543. return false;
  11544. m_substring += c;
  11545. endMode();
  11546. return true;
  11547. }
  11548. void TestSpecParser::startNewMode( Mode mode ) {
  11549. m_mode = mode;
  11550. }
  11551. void TestSpecParser::endMode() {
  11552. switch( m_mode ) {
  11553. case Name:
  11554. case QuotedName:
  11555. return addPattern<TestSpec::NamePattern>();
  11556. case Tag:
  11557. return addPattern<TestSpec::TagPattern>();
  11558. case EscapedName:
  11559. return startNewMode( Name );
  11560. case None:
  11561. default:
  11562. return startNewMode( None );
  11563. }
  11564. }
  11565. void TestSpecParser::escape() {
  11566. m_mode = EscapedName;
  11567. m_escapeChars.push_back( m_pos );
  11568. }
  11569. bool TestSpecParser::isControlChar( char c ) const {
  11570. switch( m_mode ) {
  11571. default:
  11572. return false;
  11573. case None:
  11574. return c == '~';
  11575. case Name:
  11576. return c == '[';
  11577. case EscapedName:
  11578. return true;
  11579. case QuotedName:
  11580. return c == '"';
  11581. case Tag:
  11582. return c == '[' || c == ']';
  11583. }
  11584. }
  11585. void TestSpecParser::addFilter() {
  11586. if( !m_currentFilter.m_patterns.empty() ) {
  11587. m_testSpec.m_filters.push_back( m_currentFilter );
  11588. m_currentFilter = TestSpec::Filter();
  11589. }
  11590. }
  11591. TestSpec parseTestSpec( std::string const& arg ) {
  11592. return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec();
  11593. }
  11594. } // namespace Catch
  11595. // end catch_test_spec_parser.cpp
  11596. // start catch_timer.cpp
  11597. #include <chrono>
  11598. static const uint64_t nanosecondsInSecond = 1000000000;
  11599. namespace Catch {
  11600. auto getCurrentNanosecondsSinceEpoch() -> uint64_t {
  11601. return std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::high_resolution_clock::now().time_since_epoch() ).count();
  11602. }
  11603. namespace {
  11604. auto estimateClockResolution() -> uint64_t {
  11605. uint64_t sum = 0;
  11606. static const uint64_t iterations = 1000000;
  11607. auto startTime = getCurrentNanosecondsSinceEpoch();
  11608. for( std::size_t i = 0; i < iterations; ++i ) {
  11609. uint64_t ticks;
  11610. uint64_t baseTicks = getCurrentNanosecondsSinceEpoch();
  11611. do {
  11612. ticks = getCurrentNanosecondsSinceEpoch();
  11613. } while( ticks == baseTicks );
  11614. auto delta = ticks - baseTicks;
  11615. sum += delta;
  11616. // If we have been calibrating for over 3 seconds -- the clock
  11617. // is terrible and we should move on.
  11618. // TBD: How to signal that the measured resolution is probably wrong?
  11619. if (ticks > startTime + 3 * nanosecondsInSecond) {
  11620. return sum / ( i + 1u );
  11621. }
  11622. }
  11623. // We're just taking the mean, here. To do better we could take the std. dev and exclude outliers
  11624. // - and potentially do more iterations if there's a high variance.
  11625. return sum/iterations;
  11626. }
  11627. }
  11628. auto getEstimatedClockResolution() -> uint64_t {
  11629. static auto s_resolution = estimateClockResolution();
  11630. return s_resolution;
  11631. }
  11632. void Timer::start() {
  11633. m_nanoseconds = getCurrentNanosecondsSinceEpoch();
  11634. }
  11635. auto Timer::getElapsedNanoseconds() const -> uint64_t {
  11636. return getCurrentNanosecondsSinceEpoch() - m_nanoseconds;
  11637. }
  11638. auto Timer::getElapsedMicroseconds() const -> uint64_t {
  11639. return getElapsedNanoseconds()/1000;
  11640. }
  11641. auto Timer::getElapsedMilliseconds() const -> unsigned int {
  11642. return static_cast<unsigned int>(getElapsedMicroseconds()/1000);
  11643. }
  11644. auto Timer::getElapsedSeconds() const -> double {
  11645. return getElapsedMicroseconds()/1000000.0;
  11646. }
  11647. } // namespace Catch
  11648. // end catch_timer.cpp
  11649. // start catch_tostring.cpp
  11650. #if defined(__clang__)
  11651. # pragma clang diagnostic push
  11652. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  11653. # pragma clang diagnostic ignored "-Wglobal-constructors"
  11654. #endif
  11655. // Enable specific decls locally
  11656. #if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  11657. #define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  11658. #endif
  11659. #include <cmath>
  11660. #include <iomanip>
  11661. namespace Catch {
  11662. namespace Detail {
  11663. const std::string unprintableString = "{?}";
  11664. namespace {
  11665. const int hexThreshold = 255;
  11666. struct Endianness {
  11667. enum Arch { Big, Little };
  11668. static Arch which() {
  11669. union _{
  11670. int asInt;
  11671. char asChar[sizeof (int)];
  11672. } u;
  11673. u.asInt = 1;
  11674. return ( u.asChar[sizeof(int)-1] == 1 ) ? Big : Little;
  11675. }
  11676. };
  11677. }
  11678. std::string rawMemoryToString( const void *object, std::size_t size ) {
  11679. // Reverse order for little endian architectures
  11680. int i = 0, end = static_cast<int>( size ), inc = 1;
  11681. if( Endianness::which() == Endianness::Little ) {
  11682. i = end-1;
  11683. end = inc = -1;
  11684. }
  11685. unsigned char const *bytes = static_cast<unsigned char const *>(object);
  11686. ReusableStringStream rss;
  11687. rss << "0x" << std::setfill('0') << std::hex;
  11688. for( ; i != end; i += inc )
  11689. rss << std::setw(2) << static_cast<unsigned>(bytes[i]);
  11690. return rss.str();
  11691. }
  11692. }
  11693. template<typename T>
  11694. std::string fpToString( T value, int precision ) {
  11695. if (Catch::isnan(value)) {
  11696. return "nan";
  11697. }
  11698. ReusableStringStream rss;
  11699. rss << std::setprecision( precision )
  11700. << std::fixed
  11701. << value;
  11702. std::string d = rss.str();
  11703. std::size_t i = d.find_last_not_of( '0' );
  11704. if( i != std::string::npos && i != d.size()-1 ) {
  11705. if( d[i] == '.' )
  11706. i++;
  11707. d = d.substr( 0, i+1 );
  11708. }
  11709. return d;
  11710. }
  11711. //// ======================================================= ////
  11712. //
  11713. // Out-of-line defs for full specialization of StringMaker
  11714. //
  11715. //// ======================================================= ////
  11716. std::string StringMaker<std::string>::convert(const std::string& str) {
  11717. if (!getCurrentContext().getConfig()->showInvisibles()) {
  11718. return '"' + str + '"';
  11719. }
  11720. std::string s("\"");
  11721. for (char c : str) {
  11722. switch (c) {
  11723. case '\n':
  11724. s.append("\\n");
  11725. break;
  11726. case '\t':
  11727. s.append("\\t");
  11728. break;
  11729. default:
  11730. s.push_back(c);
  11731. break;
  11732. }
  11733. }
  11734. s.append("\"");
  11735. return s;
  11736. }
  11737. #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  11738. std::string StringMaker<std::string_view>::convert(std::string_view str) {
  11739. return ::Catch::Detail::stringify(std::string{ str });
  11740. }
  11741. #endif
  11742. std::string StringMaker<char const*>::convert(char const* str) {
  11743. if (str) {
  11744. return ::Catch::Detail::stringify(std::string{ str });
  11745. } else {
  11746. return{ "{null string}" };
  11747. }
  11748. }
  11749. std::string StringMaker<char*>::convert(char* str) {
  11750. if (str) {
  11751. return ::Catch::Detail::stringify(std::string{ str });
  11752. } else {
  11753. return{ "{null string}" };
  11754. }
  11755. }
  11756. #ifdef CATCH_CONFIG_WCHAR
  11757. std::string StringMaker<std::wstring>::convert(const std::wstring& wstr) {
  11758. std::string s;
  11759. s.reserve(wstr.size());
  11760. for (auto c : wstr) {
  11761. s += (c <= 0xff) ? static_cast<char>(c) : '?';
  11762. }
  11763. return ::Catch::Detail::stringify(s);
  11764. }
  11765. # ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  11766. std::string StringMaker<std::wstring_view>::convert(std::wstring_view str) {
  11767. return StringMaker<std::wstring>::convert(std::wstring(str));
  11768. }
  11769. # endif
  11770. std::string StringMaker<wchar_t const*>::convert(wchar_t const * str) {
  11771. if (str) {
  11772. return ::Catch::Detail::stringify(std::wstring{ str });
  11773. } else {
  11774. return{ "{null string}" };
  11775. }
  11776. }
  11777. std::string StringMaker<wchar_t *>::convert(wchar_t * str) {
  11778. if (str) {
  11779. return ::Catch::Detail::stringify(std::wstring{ str });
  11780. } else {
  11781. return{ "{null string}" };
  11782. }
  11783. }
  11784. #endif
  11785. #if defined(CATCH_CONFIG_CPP17_BYTE)
  11786. #include <cstddef>
  11787. std::string StringMaker<std::byte>::convert(std::byte value) {
  11788. return ::Catch::Detail::stringify(std::to_integer<unsigned long long>(value));
  11789. }
  11790. #endif // defined(CATCH_CONFIG_CPP17_BYTE)
  11791. std::string StringMaker<int>::convert(int value) {
  11792. return ::Catch::Detail::stringify(static_cast<long long>(value));
  11793. }
  11794. std::string StringMaker<long>::convert(long value) {
  11795. return ::Catch::Detail::stringify(static_cast<long long>(value));
  11796. }
  11797. std::string StringMaker<long long>::convert(long long value) {
  11798. ReusableStringStream rss;
  11799. rss << value;
  11800. if (value > Detail::hexThreshold) {
  11801. rss << " (0x" << std::hex << value << ')';
  11802. }
  11803. return rss.str();
  11804. }
  11805. std::string StringMaker<unsigned int>::convert(unsigned int value) {
  11806. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  11807. }
  11808. std::string StringMaker<unsigned long>::convert(unsigned long value) {
  11809. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  11810. }
  11811. std::string StringMaker<unsigned long long>::convert(unsigned long long value) {
  11812. ReusableStringStream rss;
  11813. rss << value;
  11814. if (value > Detail::hexThreshold) {
  11815. rss << " (0x" << std::hex << value << ')';
  11816. }
  11817. return rss.str();
  11818. }
  11819. std::string StringMaker<bool>::convert(bool b) {
  11820. return b ? "true" : "false";
  11821. }
  11822. std::string StringMaker<signed char>::convert(signed char value) {
  11823. if (value == '\r') {
  11824. return "'\\r'";
  11825. } else if (value == '\f') {
  11826. return "'\\f'";
  11827. } else if (value == '\n') {
  11828. return "'\\n'";
  11829. } else if (value == '\t') {
  11830. return "'\\t'";
  11831. } else if ('\0' <= value && value < ' ') {
  11832. return ::Catch::Detail::stringify(static_cast<unsigned int>(value));
  11833. } else {
  11834. char chstr[] = "' '";
  11835. chstr[1] = value;
  11836. return chstr;
  11837. }
  11838. }
  11839. std::string StringMaker<char>::convert(char c) {
  11840. return ::Catch::Detail::stringify(static_cast<signed char>(c));
  11841. }
  11842. std::string StringMaker<unsigned char>::convert(unsigned char c) {
  11843. return ::Catch::Detail::stringify(static_cast<char>(c));
  11844. }
  11845. std::string StringMaker<std::nullptr_t>::convert(std::nullptr_t) {
  11846. return "nullptr";
  11847. }
  11848. int StringMaker<float>::precision = 5;
  11849. std::string StringMaker<float>::convert(float value) {
  11850. return fpToString(value, precision) + 'f';
  11851. }
  11852. int StringMaker<double>::precision = 10;
  11853. std::string StringMaker<double>::convert(double value) {
  11854. return fpToString(value, precision);
  11855. }
  11856. std::string ratio_string<std::atto>::symbol() { return "a"; }
  11857. std::string ratio_string<std::femto>::symbol() { return "f"; }
  11858. std::string ratio_string<std::pico>::symbol() { return "p"; }
  11859. std::string ratio_string<std::nano>::symbol() { return "n"; }
  11860. std::string ratio_string<std::micro>::symbol() { return "u"; }
  11861. std::string ratio_string<std::milli>::symbol() { return "m"; }
  11862. } // end namespace Catch
  11863. #if defined(__clang__)
  11864. # pragma clang diagnostic pop
  11865. #endif
  11866. // end catch_tostring.cpp
  11867. // start catch_totals.cpp
  11868. namespace Catch {
  11869. Counts Counts::operator - ( Counts const& other ) const {
  11870. Counts diff;
  11871. diff.passed = passed - other.passed;
  11872. diff.failed = failed - other.failed;
  11873. diff.failedButOk = failedButOk - other.failedButOk;
  11874. return diff;
  11875. }
  11876. Counts& Counts::operator += ( Counts const& other ) {
  11877. passed += other.passed;
  11878. failed += other.failed;
  11879. failedButOk += other.failedButOk;
  11880. return *this;
  11881. }
  11882. std::size_t Counts::total() const {
  11883. return passed + failed + failedButOk;
  11884. }
  11885. bool Counts::allPassed() const {
  11886. return failed == 0 && failedButOk == 0;
  11887. }
  11888. bool Counts::allOk() const {
  11889. return failed == 0;
  11890. }
  11891. Totals Totals::operator - ( Totals const& other ) const {
  11892. Totals diff;
  11893. diff.assertions = assertions - other.assertions;
  11894. diff.testCases = testCases - other.testCases;
  11895. return diff;
  11896. }
  11897. Totals& Totals::operator += ( Totals const& other ) {
  11898. assertions += other.assertions;
  11899. testCases += other.testCases;
  11900. return *this;
  11901. }
  11902. Totals Totals::delta( Totals const& prevTotals ) const {
  11903. Totals diff = *this - prevTotals;
  11904. if( diff.assertions.failed > 0 )
  11905. ++diff.testCases.failed;
  11906. else if( diff.assertions.failedButOk > 0 )
  11907. ++diff.testCases.failedButOk;
  11908. else
  11909. ++diff.testCases.passed;
  11910. return diff;
  11911. }
  11912. }
  11913. // end catch_totals.cpp
  11914. // start catch_uncaught_exceptions.cpp
  11915. #include <exception>
  11916. namespace Catch {
  11917. bool uncaught_exceptions() {
  11918. #if defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
  11919. return std::uncaught_exceptions() > 0;
  11920. #else
  11921. return std::uncaught_exception();
  11922. #endif
  11923. }
  11924. } // end namespace Catch
  11925. // end catch_uncaught_exceptions.cpp
  11926. // start catch_version.cpp
  11927. #include <ostream>
  11928. namespace Catch {
  11929. Version::Version
  11930. ( unsigned int _majorVersion,
  11931. unsigned int _minorVersion,
  11932. unsigned int _patchNumber,
  11933. char const * const _branchName,
  11934. unsigned int _buildNumber )
  11935. : majorVersion( _majorVersion ),
  11936. minorVersion( _minorVersion ),
  11937. patchNumber( _patchNumber ),
  11938. branchName( _branchName ),
  11939. buildNumber( _buildNumber )
  11940. {}
  11941. std::ostream& operator << ( std::ostream& os, Version const& version ) {
  11942. os << version.majorVersion << '.'
  11943. << version.minorVersion << '.'
  11944. << version.patchNumber;
  11945. // branchName is never null -> 0th char is \0 if it is empty
  11946. if (version.branchName[0]) {
  11947. os << '-' << version.branchName
  11948. << '.' << version.buildNumber;
  11949. }
  11950. return os;
  11951. }
  11952. Version const& libraryVersion() {
  11953. static Version version( 2, 9, 2, "", 0 );
  11954. return version;
  11955. }
  11956. }
  11957. // end catch_version.cpp
  11958. // start catch_wildcard_pattern.cpp
  11959. #include <sstream>
  11960. namespace Catch {
  11961. WildcardPattern::WildcardPattern( std::string const& pattern,
  11962. CaseSensitive::Choice caseSensitivity )
  11963. : m_caseSensitivity( caseSensitivity ),
  11964. m_pattern( adjustCase( pattern ) )
  11965. {
  11966. if( startsWith( m_pattern, '*' ) ) {
  11967. m_pattern = m_pattern.substr( 1 );
  11968. m_wildcard = WildcardAtStart;
  11969. }
  11970. if( endsWith( m_pattern, '*' ) ) {
  11971. m_pattern = m_pattern.substr( 0, m_pattern.size()-1 );
  11972. m_wildcard = static_cast<WildcardPosition>( m_wildcard | WildcardAtEnd );
  11973. }
  11974. }
  11975. bool WildcardPattern::matches( std::string const& str ) const {
  11976. switch( m_wildcard ) {
  11977. case NoWildcard:
  11978. return m_pattern == adjustCase( str );
  11979. case WildcardAtStart:
  11980. return endsWith( adjustCase( str ), m_pattern );
  11981. case WildcardAtEnd:
  11982. return startsWith( adjustCase( str ), m_pattern );
  11983. case WildcardAtBothEnds:
  11984. return contains( adjustCase( str ), m_pattern );
  11985. default:
  11986. CATCH_INTERNAL_ERROR( "Unknown enum" );
  11987. }
  11988. }
  11989. std::string WildcardPattern::adjustCase( std::string const& str ) const {
  11990. return m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str;
  11991. }
  11992. }
  11993. // end catch_wildcard_pattern.cpp
  11994. // start catch_xmlwriter.cpp
  11995. #include <iomanip>
  11996. using uchar = unsigned char;
  11997. namespace Catch {
  11998. namespace {
  11999. size_t trailingBytes(unsigned char c) {
  12000. if ((c & 0xE0) == 0xC0) {
  12001. return 2;
  12002. }
  12003. if ((c & 0xF0) == 0xE0) {
  12004. return 3;
  12005. }
  12006. if ((c & 0xF8) == 0xF0) {
  12007. return 4;
  12008. }
  12009. CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
  12010. }
  12011. uint32_t headerValue(unsigned char c) {
  12012. if ((c & 0xE0) == 0xC0) {
  12013. return c & 0x1F;
  12014. }
  12015. if ((c & 0xF0) == 0xE0) {
  12016. return c & 0x0F;
  12017. }
  12018. if ((c & 0xF8) == 0xF0) {
  12019. return c & 0x07;
  12020. }
  12021. CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
  12022. }
  12023. void hexEscapeChar(std::ostream& os, unsigned char c) {
  12024. std::ios_base::fmtflags f(os.flags());
  12025. os << "\\x"
  12026. << std::uppercase << std::hex << std::setfill('0') << std::setw(2)
  12027. << static_cast<int>(c);
  12028. os.flags(f);
  12029. }
  12030. } // anonymous namespace
  12031. XmlEncode::XmlEncode( std::string const& str, ForWhat forWhat )
  12032. : m_str( str ),
  12033. m_forWhat( forWhat )
  12034. {}
  12035. void XmlEncode::encodeTo( std::ostream& os ) const {
  12036. // Apostrophe escaping not necessary if we always use " to write attributes
  12037. // (see: http://www.w3.org/TR/xml/#syntax)
  12038. for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) {
  12039. uchar c = m_str[idx];
  12040. switch (c) {
  12041. case '<': os << "&lt;"; break;
  12042. case '&': os << "&amp;"; break;
  12043. case '>':
  12044. // See: http://www.w3.org/TR/xml/#syntax
  12045. if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']')
  12046. os << "&gt;";
  12047. else
  12048. os << c;
  12049. break;
  12050. case '\"':
  12051. if (m_forWhat == ForAttributes)
  12052. os << "&quot;";
  12053. else
  12054. os << c;
  12055. break;
  12056. default:
  12057. // Check for control characters and invalid utf-8
  12058. // Escape control characters in standard ascii
  12059. // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0
  12060. if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) {
  12061. hexEscapeChar(os, c);
  12062. break;
  12063. }
  12064. // Plain ASCII: Write it to stream
  12065. if (c < 0x7F) {
  12066. os << c;
  12067. break;
  12068. }
  12069. // UTF-8 territory
  12070. // Check if the encoding is valid and if it is not, hex escape bytes.
  12071. // Important: We do not check the exact decoded values for validity, only the encoding format
  12072. // First check that this bytes is a valid lead byte:
  12073. // This means that it is not encoded as 1111 1XXX
  12074. // Or as 10XX XXXX
  12075. if (c < 0xC0 ||
  12076. c >= 0xF8) {
  12077. hexEscapeChar(os, c);
  12078. break;
  12079. }
  12080. auto encBytes = trailingBytes(c);
  12081. // Are there enough bytes left to avoid accessing out-of-bounds memory?
  12082. if (idx + encBytes - 1 >= m_str.size()) {
  12083. hexEscapeChar(os, c);
  12084. break;
  12085. }
  12086. // The header is valid, check data
  12087. // The next encBytes bytes must together be a valid utf-8
  12088. // This means: bitpattern 10XX XXXX and the extracted value is sane (ish)
  12089. bool valid = true;
  12090. uint32_t value = headerValue(c);
  12091. for (std::size_t n = 1; n < encBytes; ++n) {
  12092. uchar nc = m_str[idx + n];
  12093. valid &= ((nc & 0xC0) == 0x80);
  12094. value = (value << 6) | (nc & 0x3F);
  12095. }
  12096. if (
  12097. // Wrong bit pattern of following bytes
  12098. (!valid) ||
  12099. // Overlong encodings
  12100. (value < 0x80) ||
  12101. (0x80 <= value && value < 0x800 && encBytes > 2) ||
  12102. (0x800 < value && value < 0x10000 && encBytes > 3) ||
  12103. // Encoded value out of range
  12104. (value >= 0x110000)
  12105. ) {
  12106. hexEscapeChar(os, c);
  12107. break;
  12108. }
  12109. // If we got here, this is in fact a valid(ish) utf-8 sequence
  12110. for (std::size_t n = 0; n < encBytes; ++n) {
  12111. os << m_str[idx + n];
  12112. }
  12113. idx += encBytes - 1;
  12114. break;
  12115. }
  12116. }
  12117. }
  12118. std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) {
  12119. xmlEncode.encodeTo( os );
  12120. return os;
  12121. }
  12122. XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer )
  12123. : m_writer( writer )
  12124. {}
  12125. XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept
  12126. : m_writer( other.m_writer ){
  12127. other.m_writer = nullptr;
  12128. }
  12129. XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) noexcept {
  12130. if ( m_writer ) {
  12131. m_writer->endElement();
  12132. }
  12133. m_writer = other.m_writer;
  12134. other.m_writer = nullptr;
  12135. return *this;
  12136. }
  12137. XmlWriter::ScopedElement::~ScopedElement() {
  12138. if( m_writer )
  12139. m_writer->endElement();
  12140. }
  12141. XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string const& text, bool indent ) {
  12142. m_writer->writeText( text, indent );
  12143. return *this;
  12144. }
  12145. XmlWriter::XmlWriter( std::ostream& os ) : m_os( os )
  12146. {
  12147. writeDeclaration();
  12148. }
  12149. XmlWriter::~XmlWriter() {
  12150. while( !m_tags.empty() )
  12151. endElement();
  12152. }
  12153. XmlWriter& XmlWriter::startElement( std::string const& name ) {
  12154. ensureTagClosed();
  12155. newlineIfNecessary();
  12156. m_os << m_indent << '<' << name;
  12157. m_tags.push_back( name );
  12158. m_indent += " ";
  12159. m_tagIsOpen = true;
  12160. return *this;
  12161. }
  12162. XmlWriter::ScopedElement XmlWriter::scopedElement( std::string const& name ) {
  12163. ScopedElement scoped( this );
  12164. startElement( name );
  12165. return scoped;
  12166. }
  12167. XmlWriter& XmlWriter::endElement() {
  12168. newlineIfNecessary();
  12169. m_indent = m_indent.substr( 0, m_indent.size()-2 );
  12170. if( m_tagIsOpen ) {
  12171. m_os << "/>";
  12172. m_tagIsOpen = false;
  12173. }
  12174. else {
  12175. m_os << m_indent << "</" << m_tags.back() << ">";
  12176. }
  12177. m_os << std::endl;
  12178. m_tags.pop_back();
  12179. return *this;
  12180. }
  12181. XmlWriter& XmlWriter::writeAttribute( std::string const& name, std::string const& attribute ) {
  12182. if( !name.empty() && !attribute.empty() )
  12183. m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"';
  12184. return *this;
  12185. }
  12186. XmlWriter& XmlWriter::writeAttribute( std::string const& name, bool attribute ) {
  12187. m_os << ' ' << name << "=\"" << ( attribute ? "true" : "false" ) << '"';
  12188. return *this;
  12189. }
  12190. XmlWriter& XmlWriter::writeText( std::string const& text, bool indent ) {
  12191. if( !text.empty() ){
  12192. bool tagWasOpen = m_tagIsOpen;
  12193. ensureTagClosed();
  12194. if( tagWasOpen && indent )
  12195. m_os << m_indent;
  12196. m_os << XmlEncode( text );
  12197. m_needsNewline = true;
  12198. }
  12199. return *this;
  12200. }
  12201. XmlWriter& XmlWriter::writeComment( std::string const& text ) {
  12202. ensureTagClosed();
  12203. m_os << m_indent << "<!--" << text << "-->";
  12204. m_needsNewline = true;
  12205. return *this;
  12206. }
  12207. void XmlWriter::writeStylesheetRef( std::string const& url ) {
  12208. m_os << "<?xml-stylesheet type=\"text/xsl\" href=\"" << url << "\"?>\n";
  12209. }
  12210. XmlWriter& XmlWriter::writeBlankLine() {
  12211. ensureTagClosed();
  12212. m_os << '\n';
  12213. return *this;
  12214. }
  12215. void XmlWriter::ensureTagClosed() {
  12216. if( m_tagIsOpen ) {
  12217. m_os << ">" << std::endl;
  12218. m_tagIsOpen = false;
  12219. }
  12220. }
  12221. void XmlWriter::writeDeclaration() {
  12222. m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
  12223. }
  12224. void XmlWriter::newlineIfNecessary() {
  12225. if( m_needsNewline ) {
  12226. m_os << std::endl;
  12227. m_needsNewline = false;
  12228. }
  12229. }
  12230. }
  12231. // end catch_xmlwriter.cpp
  12232. // start catch_reporter_bases.cpp
  12233. #include <cstring>
  12234. #include <cfloat>
  12235. #include <cstdio>
  12236. #include <cassert>
  12237. #include <memory>
  12238. namespace Catch {
  12239. void prepareExpandedExpression(AssertionResult& result) {
  12240. result.getExpandedExpression();
  12241. }
  12242. // Because formatting using c++ streams is stateful, drop down to C is required
  12243. // Alternatively we could use stringstream, but its performance is... not good.
  12244. std::string getFormattedDuration( double duration ) {
  12245. // Max exponent + 1 is required to represent the whole part
  12246. // + 1 for decimal point
  12247. // + 3 for the 3 decimal places
  12248. // + 1 for null terminator
  12249. const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1;
  12250. char buffer[maxDoubleSize];
  12251. // Save previous errno, to prevent sprintf from overwriting it
  12252. ErrnoGuard guard;
  12253. #ifdef _MSC_VER
  12254. sprintf_s(buffer, "%.3f", duration);
  12255. #else
  12256. std::sprintf(buffer, "%.3f", duration);
  12257. #endif
  12258. return std::string(buffer);
  12259. }
  12260. std::string serializeFilters( std::vector<std::string> const& container ) {
  12261. ReusableStringStream oss;
  12262. bool first = true;
  12263. for (auto&& filter : container)
  12264. {
  12265. if (!first)
  12266. oss << ' ';
  12267. else
  12268. first = false;
  12269. oss << filter;
  12270. }
  12271. return oss.str();
  12272. }
  12273. TestEventListenerBase::TestEventListenerBase(ReporterConfig const & _config)
  12274. :StreamingReporterBase(_config) {}
  12275. std::set<Verbosity> TestEventListenerBase::getSupportedVerbosities() {
  12276. return { Verbosity::Quiet, Verbosity::Normal, Verbosity::High };
  12277. }
  12278. void TestEventListenerBase::assertionStarting(AssertionInfo const &) {}
  12279. bool TestEventListenerBase::assertionEnded(AssertionStats const &) {
  12280. return false;
  12281. }
  12282. } // end namespace Catch
  12283. // end catch_reporter_bases.cpp
  12284. // start catch_reporter_compact.cpp
  12285. namespace {
  12286. #ifdef CATCH_PLATFORM_MAC
  12287. const char* failedString() { return "FAILED"; }
  12288. const char* passedString() { return "PASSED"; }
  12289. #else
  12290. const char* failedString() { return "failed"; }
  12291. const char* passedString() { return "passed"; }
  12292. #endif
  12293. // Colour::LightGrey
  12294. Catch::Colour::Code dimColour() { return Catch::Colour::FileName; }
  12295. std::string bothOrAll( std::size_t count ) {
  12296. return count == 1 ? std::string() :
  12297. count == 2 ? "both " : "all " ;
  12298. }
  12299. } // anon namespace
  12300. namespace Catch {
  12301. namespace {
  12302. // Colour, message variants:
  12303. // - white: No tests ran.
  12304. // - red: Failed [both/all] N test cases, failed [both/all] M assertions.
  12305. // - white: Passed [both/all] N test cases (no assertions).
  12306. // - red: Failed N tests cases, failed M assertions.
  12307. // - green: Passed [both/all] N tests cases with M assertions.
  12308. void printTotals(std::ostream& out, const Totals& totals) {
  12309. if (totals.testCases.total() == 0) {
  12310. out << "No tests ran.";
  12311. } else if (totals.testCases.failed == totals.testCases.total()) {
  12312. Colour colour(Colour::ResultError);
  12313. const std::string qualify_assertions_failed =
  12314. totals.assertions.failed == totals.assertions.total() ?
  12315. bothOrAll(totals.assertions.failed) : std::string();
  12316. out <<
  12317. "Failed " << bothOrAll(totals.testCases.failed)
  12318. << pluralise(totals.testCases.failed, "test case") << ", "
  12319. "failed " << qualify_assertions_failed <<
  12320. pluralise(totals.assertions.failed, "assertion") << '.';
  12321. } else if (totals.assertions.total() == 0) {
  12322. out <<
  12323. "Passed " << bothOrAll(totals.testCases.total())
  12324. << pluralise(totals.testCases.total(), "test case")
  12325. << " (no assertions).";
  12326. } else if (totals.assertions.failed) {
  12327. Colour colour(Colour::ResultError);
  12328. out <<
  12329. "Failed " << pluralise(totals.testCases.failed, "test case") << ", "
  12330. "failed " << pluralise(totals.assertions.failed, "assertion") << '.';
  12331. } else {
  12332. Colour colour(Colour::ResultSuccess);
  12333. out <<
  12334. "Passed " << bothOrAll(totals.testCases.passed)
  12335. << pluralise(totals.testCases.passed, "test case") <<
  12336. " with " << pluralise(totals.assertions.passed, "assertion") << '.';
  12337. }
  12338. }
  12339. // Implementation of CompactReporter formatting
  12340. class AssertionPrinter {
  12341. public:
  12342. AssertionPrinter& operator= (AssertionPrinter const&) = delete;
  12343. AssertionPrinter(AssertionPrinter const&) = delete;
  12344. AssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
  12345. : stream(_stream)
  12346. , result(_stats.assertionResult)
  12347. , messages(_stats.infoMessages)
  12348. , itMessage(_stats.infoMessages.begin())
  12349. , printInfoMessages(_printInfoMessages) {}
  12350. void print() {
  12351. printSourceInfo();
  12352. itMessage = messages.begin();
  12353. switch (result.getResultType()) {
  12354. case ResultWas::Ok:
  12355. printResultType(Colour::ResultSuccess, passedString());
  12356. printOriginalExpression();
  12357. printReconstructedExpression();
  12358. if (!result.hasExpression())
  12359. printRemainingMessages(Colour::None);
  12360. else
  12361. printRemainingMessages();
  12362. break;
  12363. case ResultWas::ExpressionFailed:
  12364. if (result.isOk())
  12365. printResultType(Colour::ResultSuccess, failedString() + std::string(" - but was ok"));
  12366. else
  12367. printResultType(Colour::Error, failedString());
  12368. printOriginalExpression();
  12369. printReconstructedExpression();
  12370. printRemainingMessages();
  12371. break;
  12372. case ResultWas::ThrewException:
  12373. printResultType(Colour::Error, failedString());
  12374. printIssue("unexpected exception with message:");
  12375. printMessage();
  12376. printExpressionWas();
  12377. printRemainingMessages();
  12378. break;
  12379. case ResultWas::FatalErrorCondition:
  12380. printResultType(Colour::Error, failedString());
  12381. printIssue("fatal error condition with message:");
  12382. printMessage();
  12383. printExpressionWas();
  12384. printRemainingMessages();
  12385. break;
  12386. case ResultWas::DidntThrowException:
  12387. printResultType(Colour::Error, failedString());
  12388. printIssue("expected exception, got none");
  12389. printExpressionWas();
  12390. printRemainingMessages();
  12391. break;
  12392. case ResultWas::Info:
  12393. printResultType(Colour::None, "info");
  12394. printMessage();
  12395. printRemainingMessages();
  12396. break;
  12397. case ResultWas::Warning:
  12398. printResultType(Colour::None, "warning");
  12399. printMessage();
  12400. printRemainingMessages();
  12401. break;
  12402. case ResultWas::ExplicitFailure:
  12403. printResultType(Colour::Error, failedString());
  12404. printIssue("explicitly");
  12405. printRemainingMessages(Colour::None);
  12406. break;
  12407. // These cases are here to prevent compiler warnings
  12408. case ResultWas::Unknown:
  12409. case ResultWas::FailureBit:
  12410. case ResultWas::Exception:
  12411. printResultType(Colour::Error, "** internal error **");
  12412. break;
  12413. }
  12414. }
  12415. private:
  12416. void printSourceInfo() const {
  12417. Colour colourGuard(Colour::FileName);
  12418. stream << result.getSourceInfo() << ':';
  12419. }
  12420. void printResultType(Colour::Code colour, std::string const& passOrFail) const {
  12421. if (!passOrFail.empty()) {
  12422. {
  12423. Colour colourGuard(colour);
  12424. stream << ' ' << passOrFail;
  12425. }
  12426. stream << ':';
  12427. }
  12428. }
  12429. void printIssue(std::string const& issue) const {
  12430. stream << ' ' << issue;
  12431. }
  12432. void printExpressionWas() {
  12433. if (result.hasExpression()) {
  12434. stream << ';';
  12435. {
  12436. Colour colour(dimColour());
  12437. stream << " expression was:";
  12438. }
  12439. printOriginalExpression();
  12440. }
  12441. }
  12442. void printOriginalExpression() const {
  12443. if (result.hasExpression()) {
  12444. stream << ' ' << result.getExpression();
  12445. }
  12446. }
  12447. void printReconstructedExpression() const {
  12448. if (result.hasExpandedExpression()) {
  12449. {
  12450. Colour colour(dimColour());
  12451. stream << " for: ";
  12452. }
  12453. stream << result.getExpandedExpression();
  12454. }
  12455. }
  12456. void printMessage() {
  12457. if (itMessage != messages.end()) {
  12458. stream << " '" << itMessage->message << '\'';
  12459. ++itMessage;
  12460. }
  12461. }
  12462. void printRemainingMessages(Colour::Code colour = dimColour()) {
  12463. if (itMessage == messages.end())
  12464. return;
  12465. const auto itEnd = messages.cend();
  12466. const auto N = static_cast<std::size_t>(std::distance(itMessage, itEnd));
  12467. {
  12468. Colour colourGuard(colour);
  12469. stream << " with " << pluralise(N, "message") << ':';
  12470. }
  12471. while (itMessage != itEnd) {
  12472. // If this assertion is a warning ignore any INFO messages
  12473. if (printInfoMessages || itMessage->type != ResultWas::Info) {
  12474. printMessage();
  12475. if (itMessage != itEnd) {
  12476. Colour colourGuard(dimColour());
  12477. stream << " and";
  12478. }
  12479. continue;
  12480. }
  12481. ++itMessage;
  12482. }
  12483. }
  12484. private:
  12485. std::ostream& stream;
  12486. AssertionResult const& result;
  12487. std::vector<MessageInfo> messages;
  12488. std::vector<MessageInfo>::const_iterator itMessage;
  12489. bool printInfoMessages;
  12490. };
  12491. } // anon namespace
  12492. std::string CompactReporter::getDescription() {
  12493. return "Reports test results on a single line, suitable for IDEs";
  12494. }
  12495. ReporterPreferences CompactReporter::getPreferences() const {
  12496. return m_reporterPrefs;
  12497. }
  12498. void CompactReporter::noMatchingTestCases( std::string const& spec ) {
  12499. stream << "No test cases matched '" << spec << '\'' << std::endl;
  12500. }
  12501. void CompactReporter::assertionStarting( AssertionInfo const& ) {}
  12502. bool CompactReporter::assertionEnded( AssertionStats const& _assertionStats ) {
  12503. AssertionResult const& result = _assertionStats.assertionResult;
  12504. bool printInfoMessages = true;
  12505. // Drop out if result was successful and we're not printing those
  12506. if( !m_config->includeSuccessfulResults() && result.isOk() ) {
  12507. if( result.getResultType() != ResultWas::Warning )
  12508. return false;
  12509. printInfoMessages = false;
  12510. }
  12511. AssertionPrinter printer( stream, _assertionStats, printInfoMessages );
  12512. printer.print();
  12513. stream << std::endl;
  12514. return true;
  12515. }
  12516. void CompactReporter::sectionEnded(SectionStats const& _sectionStats) {
  12517. if (m_config->showDurations() == ShowDurations::Always) {
  12518. stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  12519. }
  12520. }
  12521. void CompactReporter::testRunEnded( TestRunStats const& _testRunStats ) {
  12522. printTotals( stream, _testRunStats.totals );
  12523. stream << '\n' << std::endl;
  12524. StreamingReporterBase::testRunEnded( _testRunStats );
  12525. }
  12526. CompactReporter::~CompactReporter() {}
  12527. CATCH_REGISTER_REPORTER( "compact", CompactReporter )
  12528. } // end namespace Catch
  12529. // end catch_reporter_compact.cpp
  12530. // start catch_reporter_console.cpp
  12531. #include <cfloat>
  12532. #include <cstdio>
  12533. #if defined(_MSC_VER)
  12534. #pragma warning(push)
  12535. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  12536. // Note that 4062 (not all labels are handled and default is missing) is enabled
  12537. #endif
  12538. #if defined(__clang__)
  12539. # pragma clang diagnostic push
  12540. // For simplicity, benchmarking-only helpers are always enabled
  12541. # pragma clang diagnostic ignored "-Wunused-function"
  12542. #endif
  12543. namespace Catch {
  12544. namespace {
  12545. // Formatter impl for ConsoleReporter
  12546. class ConsoleAssertionPrinter {
  12547. public:
  12548. ConsoleAssertionPrinter& operator= (ConsoleAssertionPrinter const&) = delete;
  12549. ConsoleAssertionPrinter(ConsoleAssertionPrinter const&) = delete;
  12550. ConsoleAssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
  12551. : stream(_stream),
  12552. stats(_stats),
  12553. result(_stats.assertionResult),
  12554. colour(Colour::None),
  12555. message(result.getMessage()),
  12556. messages(_stats.infoMessages),
  12557. printInfoMessages(_printInfoMessages) {
  12558. switch (result.getResultType()) {
  12559. case ResultWas::Ok:
  12560. colour = Colour::Success;
  12561. passOrFail = "PASSED";
  12562. //if( result.hasMessage() )
  12563. if (_stats.infoMessages.size() == 1)
  12564. messageLabel = "with message";
  12565. if (_stats.infoMessages.size() > 1)
  12566. messageLabel = "with messages";
  12567. break;
  12568. case ResultWas::ExpressionFailed:
  12569. if (result.isOk()) {
  12570. colour = Colour::Success;
  12571. passOrFail = "FAILED - but was ok";
  12572. } else {
  12573. colour = Colour::Error;
  12574. passOrFail = "FAILED";
  12575. }
  12576. if (_stats.infoMessages.size() == 1)
  12577. messageLabel = "with message";
  12578. if (_stats.infoMessages.size() > 1)
  12579. messageLabel = "with messages";
  12580. break;
  12581. case ResultWas::ThrewException:
  12582. colour = Colour::Error;
  12583. passOrFail = "FAILED";
  12584. messageLabel = "due to unexpected exception with ";
  12585. if (_stats.infoMessages.size() == 1)
  12586. messageLabel += "message";
  12587. if (_stats.infoMessages.size() > 1)
  12588. messageLabel += "messages";
  12589. break;
  12590. case ResultWas::FatalErrorCondition:
  12591. colour = Colour::Error;
  12592. passOrFail = "FAILED";
  12593. messageLabel = "due to a fatal error condition";
  12594. break;
  12595. case ResultWas::DidntThrowException:
  12596. colour = Colour::Error;
  12597. passOrFail = "FAILED";
  12598. messageLabel = "because no exception was thrown where one was expected";
  12599. break;
  12600. case ResultWas::Info:
  12601. messageLabel = "info";
  12602. break;
  12603. case ResultWas::Warning:
  12604. messageLabel = "warning";
  12605. break;
  12606. case ResultWas::ExplicitFailure:
  12607. passOrFail = "FAILED";
  12608. colour = Colour::Error;
  12609. if (_stats.infoMessages.size() == 1)
  12610. messageLabel = "explicitly with message";
  12611. if (_stats.infoMessages.size() > 1)
  12612. messageLabel = "explicitly with messages";
  12613. break;
  12614. // These cases are here to prevent compiler warnings
  12615. case ResultWas::Unknown:
  12616. case ResultWas::FailureBit:
  12617. case ResultWas::Exception:
  12618. passOrFail = "** internal error **";
  12619. colour = Colour::Error;
  12620. break;
  12621. }
  12622. }
  12623. void print() const {
  12624. printSourceInfo();
  12625. if (stats.totals.assertions.total() > 0) {
  12626. printResultType();
  12627. printOriginalExpression();
  12628. printReconstructedExpression();
  12629. } else {
  12630. stream << '\n';
  12631. }
  12632. printMessage();
  12633. }
  12634. private:
  12635. void printResultType() const {
  12636. if (!passOrFail.empty()) {
  12637. Colour colourGuard(colour);
  12638. stream << passOrFail << ":\n";
  12639. }
  12640. }
  12641. void printOriginalExpression() const {
  12642. if (result.hasExpression()) {
  12643. Colour colourGuard(Colour::OriginalExpression);
  12644. stream << " ";
  12645. stream << result.getExpressionInMacro();
  12646. stream << '\n';
  12647. }
  12648. }
  12649. void printReconstructedExpression() const {
  12650. if (result.hasExpandedExpression()) {
  12651. stream << "with expansion:\n";
  12652. Colour colourGuard(Colour::ReconstructedExpression);
  12653. stream << Column(result.getExpandedExpression()).indent(2) << '\n';
  12654. }
  12655. }
  12656. void printMessage() const {
  12657. if (!messageLabel.empty())
  12658. stream << messageLabel << ':' << '\n';
  12659. for (auto const& msg : messages) {
  12660. // If this assertion is a warning ignore any INFO messages
  12661. if (printInfoMessages || msg.type != ResultWas::Info)
  12662. stream << Column(msg.message).indent(2) << '\n';
  12663. }
  12664. }
  12665. void printSourceInfo() const {
  12666. Colour colourGuard(Colour::FileName);
  12667. stream << result.getSourceInfo() << ": ";
  12668. }
  12669. std::ostream& stream;
  12670. AssertionStats const& stats;
  12671. AssertionResult const& result;
  12672. Colour::Code colour;
  12673. std::string passOrFail;
  12674. std::string messageLabel;
  12675. std::string message;
  12676. std::vector<MessageInfo> messages;
  12677. bool printInfoMessages;
  12678. };
  12679. std::size_t makeRatio(std::size_t number, std::size_t total) {
  12680. std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0;
  12681. return (ratio == 0 && number > 0) ? 1 : ratio;
  12682. }
  12683. std::size_t& findMax(std::size_t& i, std::size_t& j, std::size_t& k) {
  12684. if (i > j && i > k)
  12685. return i;
  12686. else if (j > k)
  12687. return j;
  12688. else
  12689. return k;
  12690. }
  12691. struct ColumnInfo {
  12692. enum Justification { Left, Right };
  12693. std::string name;
  12694. int width;
  12695. Justification justification;
  12696. };
  12697. struct ColumnBreak {};
  12698. struct RowBreak {};
  12699. class Duration {
  12700. enum class Unit {
  12701. Auto,
  12702. Nanoseconds,
  12703. Microseconds,
  12704. Milliseconds,
  12705. Seconds,
  12706. Minutes
  12707. };
  12708. static const uint64_t s_nanosecondsInAMicrosecond = 1000;
  12709. static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond;
  12710. static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond;
  12711. static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond;
  12712. uint64_t m_inNanoseconds;
  12713. Unit m_units;
  12714. public:
  12715. explicit Duration(double inNanoseconds, Unit units = Unit::Auto)
  12716. : Duration(static_cast<uint64_t>(inNanoseconds), units) {
  12717. }
  12718. explicit Duration(uint64_t inNanoseconds, Unit units = Unit::Auto)
  12719. : m_inNanoseconds(inNanoseconds),
  12720. m_units(units) {
  12721. if (m_units == Unit::Auto) {
  12722. if (m_inNanoseconds < s_nanosecondsInAMicrosecond)
  12723. m_units = Unit::Nanoseconds;
  12724. else if (m_inNanoseconds < s_nanosecondsInAMillisecond)
  12725. m_units = Unit::Microseconds;
  12726. else if (m_inNanoseconds < s_nanosecondsInASecond)
  12727. m_units = Unit::Milliseconds;
  12728. else if (m_inNanoseconds < s_nanosecondsInAMinute)
  12729. m_units = Unit::Seconds;
  12730. else
  12731. m_units = Unit::Minutes;
  12732. }
  12733. }
  12734. auto value() const -> double {
  12735. switch (m_units) {
  12736. case Unit::Microseconds:
  12737. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMicrosecond);
  12738. case Unit::Milliseconds:
  12739. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMillisecond);
  12740. case Unit::Seconds:
  12741. return m_inNanoseconds / static_cast<double>(s_nanosecondsInASecond);
  12742. case Unit::Minutes:
  12743. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMinute);
  12744. default:
  12745. return static_cast<double>(m_inNanoseconds);
  12746. }
  12747. }
  12748. auto unitsAsString() const -> std::string {
  12749. switch (m_units) {
  12750. case Unit::Nanoseconds:
  12751. return "ns";
  12752. case Unit::Microseconds:
  12753. return "us";
  12754. case Unit::Milliseconds:
  12755. return "ms";
  12756. case Unit::Seconds:
  12757. return "s";
  12758. case Unit::Minutes:
  12759. return "m";
  12760. default:
  12761. return "** internal error **";
  12762. }
  12763. }
  12764. friend auto operator << (std::ostream& os, Duration const& duration) -> std::ostream& {
  12765. return os << duration.value() << " " << duration.unitsAsString();
  12766. }
  12767. };
  12768. } // end anon namespace
  12769. class TablePrinter {
  12770. std::ostream& m_os;
  12771. std::vector<ColumnInfo> m_columnInfos;
  12772. std::ostringstream m_oss;
  12773. int m_currentColumn = -1;
  12774. bool m_isOpen = false;
  12775. public:
  12776. TablePrinter( std::ostream& os, std::vector<ColumnInfo> columnInfos )
  12777. : m_os( os ),
  12778. m_columnInfos( std::move( columnInfos ) ) {}
  12779. auto columnInfos() const -> std::vector<ColumnInfo> const& {
  12780. return m_columnInfos;
  12781. }
  12782. void open() {
  12783. if (!m_isOpen) {
  12784. m_isOpen = true;
  12785. *this << RowBreak();
  12786. Columns headerCols;
  12787. Spacer spacer(2);
  12788. for (auto const& info : m_columnInfos) {
  12789. headerCols += Column(info.name).width(static_cast<std::size_t>(info.width - 2));
  12790. headerCols += spacer;
  12791. }
  12792. m_os << headerCols << "\n";
  12793. m_os << Catch::getLineOfChars<'-'>() << "\n";
  12794. }
  12795. }
  12796. void close() {
  12797. if (m_isOpen) {
  12798. *this << RowBreak();
  12799. m_os << std::endl;
  12800. m_isOpen = false;
  12801. }
  12802. }
  12803. template<typename T>
  12804. friend TablePrinter& operator << (TablePrinter& tp, T const& value) {
  12805. tp.m_oss << value;
  12806. return tp;
  12807. }
  12808. friend TablePrinter& operator << (TablePrinter& tp, ColumnBreak) {
  12809. auto colStr = tp.m_oss.str();
  12810. // This takes account of utf8 encodings
  12811. auto strSize = Catch::StringRef(colStr).numberOfCharacters();
  12812. tp.m_oss.str("");
  12813. tp.open();
  12814. if (tp.m_currentColumn == static_cast<int>(tp.m_columnInfos.size() - 1)) {
  12815. tp.m_currentColumn = -1;
  12816. tp.m_os << "\n";
  12817. }
  12818. tp.m_currentColumn++;
  12819. auto colInfo = tp.m_columnInfos[tp.m_currentColumn];
  12820. auto padding = (strSize + 2 < static_cast<std::size_t>(colInfo.width))
  12821. ? std::string(colInfo.width - (strSize + 2), ' ')
  12822. : std::string();
  12823. if (colInfo.justification == ColumnInfo::Left)
  12824. tp.m_os << colStr << padding << " ";
  12825. else
  12826. tp.m_os << padding << colStr << " ";
  12827. return tp;
  12828. }
  12829. friend TablePrinter& operator << (TablePrinter& tp, RowBreak) {
  12830. if (tp.m_currentColumn > 0) {
  12831. tp.m_os << "\n";
  12832. tp.m_currentColumn = -1;
  12833. }
  12834. return tp;
  12835. }
  12836. };
  12837. ConsoleReporter::ConsoleReporter(ReporterConfig const& config)
  12838. : StreamingReporterBase(config),
  12839. m_tablePrinter(new TablePrinter(config.stream(),
  12840. {
  12841. { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 32, ColumnInfo::Left },
  12842. { "samples mean std dev", 14, ColumnInfo::Right },
  12843. { "iterations low mean low std dev", 14, ColumnInfo::Right },
  12844. { "estimated high mean high std dev", 14, ColumnInfo::Right }
  12845. })) {}
  12846. ConsoleReporter::~ConsoleReporter() = default;
  12847. std::string ConsoleReporter::getDescription() {
  12848. return "Reports test results as plain lines of text";
  12849. }
  12850. void ConsoleReporter::noMatchingTestCases(std::string const& spec) {
  12851. stream << "No test cases matched '" << spec << '\'' << std::endl;
  12852. }
  12853. void ConsoleReporter::assertionStarting(AssertionInfo const&) {}
  12854. bool ConsoleReporter::assertionEnded(AssertionStats const& _assertionStats) {
  12855. AssertionResult const& result = _assertionStats.assertionResult;
  12856. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  12857. // Drop out if result was successful but we're not printing them.
  12858. if (!includeResults && result.getResultType() != ResultWas::Warning)
  12859. return false;
  12860. lazyPrint();
  12861. ConsoleAssertionPrinter printer(stream, _assertionStats, includeResults);
  12862. printer.print();
  12863. stream << std::endl;
  12864. return true;
  12865. }
  12866. void ConsoleReporter::sectionStarting(SectionInfo const& _sectionInfo) {
  12867. m_tablePrinter->close();
  12868. m_headerPrinted = false;
  12869. StreamingReporterBase::sectionStarting(_sectionInfo);
  12870. }
  12871. void ConsoleReporter::sectionEnded(SectionStats const& _sectionStats) {
  12872. m_tablePrinter->close();
  12873. if (_sectionStats.missingAssertions) {
  12874. lazyPrint();
  12875. Colour colour(Colour::ResultError);
  12876. if (m_sectionStack.size() > 1)
  12877. stream << "\nNo assertions in section";
  12878. else
  12879. stream << "\nNo assertions in test case";
  12880. stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl;
  12881. }
  12882. if (m_config->showDurations() == ShowDurations::Always) {
  12883. stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  12884. }
  12885. if (m_headerPrinted) {
  12886. m_headerPrinted = false;
  12887. }
  12888. StreamingReporterBase::sectionEnded(_sectionStats);
  12889. }
  12890. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  12891. void ConsoleReporter::benchmarkPreparing(std::string const& name) {
  12892. lazyPrintWithoutClosingBenchmarkTable();
  12893. auto nameCol = Column(name).width(static_cast<std::size_t>(m_tablePrinter->columnInfos()[0].width - 2));
  12894. bool firstLine = true;
  12895. for (auto line : nameCol) {
  12896. if (!firstLine)
  12897. (*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak();
  12898. else
  12899. firstLine = false;
  12900. (*m_tablePrinter) << line << ColumnBreak();
  12901. }
  12902. }
  12903. void ConsoleReporter::benchmarkStarting(BenchmarkInfo const& info) {
  12904. (*m_tablePrinter) << info.samples << ColumnBreak()
  12905. << info.iterations << ColumnBreak()
  12906. << Duration(info.estimatedDuration) << ColumnBreak();
  12907. }
  12908. void ConsoleReporter::benchmarkEnded(BenchmarkStats<> const& stats) {
  12909. (*m_tablePrinter) << ColumnBreak()
  12910. << Duration(stats.mean.point.count()) << ColumnBreak()
  12911. << Duration(stats.mean.lower_bound.count()) << ColumnBreak()
  12912. << Duration(stats.mean.upper_bound.count()) << ColumnBreak() << ColumnBreak()
  12913. << Duration(stats.standardDeviation.point.count()) << ColumnBreak()
  12914. << Duration(stats.standardDeviation.lower_bound.count()) << ColumnBreak()
  12915. << Duration(stats.standardDeviation.upper_bound.count()) << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak();
  12916. }
  12917. void ConsoleReporter::benchmarkFailed(std::string const& error) {
  12918. Colour colour(Colour::Red);
  12919. (*m_tablePrinter)
  12920. << "Benchmark failed (" << error << ")"
  12921. << ColumnBreak() << RowBreak();
  12922. }
  12923. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  12924. void ConsoleReporter::testCaseEnded(TestCaseStats const& _testCaseStats) {
  12925. m_tablePrinter->close();
  12926. StreamingReporterBase::testCaseEnded(_testCaseStats);
  12927. m_headerPrinted = false;
  12928. }
  12929. void ConsoleReporter::testGroupEnded(TestGroupStats const& _testGroupStats) {
  12930. if (currentGroupInfo.used) {
  12931. printSummaryDivider();
  12932. stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n";
  12933. printTotals(_testGroupStats.totals);
  12934. stream << '\n' << std::endl;
  12935. }
  12936. StreamingReporterBase::testGroupEnded(_testGroupStats);
  12937. }
  12938. void ConsoleReporter::testRunEnded(TestRunStats const& _testRunStats) {
  12939. printTotalsDivider(_testRunStats.totals);
  12940. printTotals(_testRunStats.totals);
  12941. stream << std::endl;
  12942. StreamingReporterBase::testRunEnded(_testRunStats);
  12943. }
  12944. void ConsoleReporter::testRunStarting(TestRunInfo const& _testInfo) {
  12945. StreamingReporterBase::testRunStarting(_testInfo);
  12946. printTestFilters();
  12947. }
  12948. void ConsoleReporter::lazyPrint() {
  12949. m_tablePrinter->close();
  12950. lazyPrintWithoutClosingBenchmarkTable();
  12951. }
  12952. void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() {
  12953. if (!currentTestRunInfo.used)
  12954. lazyPrintRunInfo();
  12955. if (!currentGroupInfo.used)
  12956. lazyPrintGroupInfo();
  12957. if (!m_headerPrinted) {
  12958. printTestCaseAndSectionHeader();
  12959. m_headerPrinted = true;
  12960. }
  12961. }
  12962. void ConsoleReporter::lazyPrintRunInfo() {
  12963. stream << '\n' << getLineOfChars<'~'>() << '\n';
  12964. Colour colour(Colour::SecondaryText);
  12965. stream << currentTestRunInfo->name
  12966. << " is a Catch v" << libraryVersion() << " host application.\n"
  12967. << "Run with -? for options\n\n";
  12968. if (m_config->rngSeed() != 0)
  12969. stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n";
  12970. currentTestRunInfo.used = true;
  12971. }
  12972. void ConsoleReporter::lazyPrintGroupInfo() {
  12973. if (!currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1) {
  12974. printClosedHeader("Group: " + currentGroupInfo->name);
  12975. currentGroupInfo.used = true;
  12976. }
  12977. }
  12978. void ConsoleReporter::printTestCaseAndSectionHeader() {
  12979. assert(!m_sectionStack.empty());
  12980. printOpenHeader(currentTestCaseInfo->name);
  12981. if (m_sectionStack.size() > 1) {
  12982. Colour colourGuard(Colour::Headers);
  12983. auto
  12984. it = m_sectionStack.begin() + 1, // Skip first section (test case)
  12985. itEnd = m_sectionStack.end();
  12986. for (; it != itEnd; ++it)
  12987. printHeaderString(it->name, 2);
  12988. }
  12989. SourceLineInfo lineInfo = m_sectionStack.back().lineInfo;
  12990. if (!lineInfo.empty()) {
  12991. stream << getLineOfChars<'-'>() << '\n';
  12992. Colour colourGuard(Colour::FileName);
  12993. stream << lineInfo << '\n';
  12994. }
  12995. stream << getLineOfChars<'.'>() << '\n' << std::endl;
  12996. }
  12997. void ConsoleReporter::printClosedHeader(std::string const& _name) {
  12998. printOpenHeader(_name);
  12999. stream << getLineOfChars<'.'>() << '\n';
  13000. }
  13001. void ConsoleReporter::printOpenHeader(std::string const& _name) {
  13002. stream << getLineOfChars<'-'>() << '\n';
  13003. {
  13004. Colour colourGuard(Colour::Headers);
  13005. printHeaderString(_name);
  13006. }
  13007. }
  13008. // if string has a : in first line will set indent to follow it on
  13009. // subsequent lines
  13010. void ConsoleReporter::printHeaderString(std::string const& _string, std::size_t indent) {
  13011. std::size_t i = _string.find(": ");
  13012. if (i != std::string::npos)
  13013. i += 2;
  13014. else
  13015. i = 0;
  13016. stream << Column(_string).indent(indent + i).initialIndent(indent) << '\n';
  13017. }
  13018. struct SummaryColumn {
  13019. SummaryColumn( std::string _label, Colour::Code _colour )
  13020. : label( std::move( _label ) ),
  13021. colour( _colour ) {}
  13022. SummaryColumn addRow( std::size_t count ) {
  13023. ReusableStringStream rss;
  13024. rss << count;
  13025. std::string row = rss.str();
  13026. for (auto& oldRow : rows) {
  13027. while (oldRow.size() < row.size())
  13028. oldRow = ' ' + oldRow;
  13029. while (oldRow.size() > row.size())
  13030. row = ' ' + row;
  13031. }
  13032. rows.push_back(row);
  13033. return *this;
  13034. }
  13035. std::string label;
  13036. Colour::Code colour;
  13037. std::vector<std::string> rows;
  13038. };
  13039. void ConsoleReporter::printTotals( Totals const& totals ) {
  13040. if (totals.testCases.total() == 0) {
  13041. stream << Colour(Colour::Warning) << "No tests ran\n";
  13042. } else if (totals.assertions.total() > 0 && totals.testCases.allPassed()) {
  13043. stream << Colour(Colour::ResultSuccess) << "All tests passed";
  13044. stream << " ("
  13045. << pluralise(totals.assertions.passed, "assertion") << " in "
  13046. << pluralise(totals.testCases.passed, "test case") << ')'
  13047. << '\n';
  13048. } else {
  13049. std::vector<SummaryColumn> columns;
  13050. columns.push_back(SummaryColumn("", Colour::None)
  13051. .addRow(totals.testCases.total())
  13052. .addRow(totals.assertions.total()));
  13053. columns.push_back(SummaryColumn("passed", Colour::Success)
  13054. .addRow(totals.testCases.passed)
  13055. .addRow(totals.assertions.passed));
  13056. columns.push_back(SummaryColumn("failed", Colour::ResultError)
  13057. .addRow(totals.testCases.failed)
  13058. .addRow(totals.assertions.failed));
  13059. columns.push_back(SummaryColumn("failed as expected", Colour::ResultExpectedFailure)
  13060. .addRow(totals.testCases.failedButOk)
  13061. .addRow(totals.assertions.failedButOk));
  13062. printSummaryRow("test cases", columns, 0);
  13063. printSummaryRow("assertions", columns, 1);
  13064. }
  13065. }
  13066. void ConsoleReporter::printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row) {
  13067. for (auto col : cols) {
  13068. std::string value = col.rows[row];
  13069. if (col.label.empty()) {
  13070. stream << label << ": ";
  13071. if (value != "0")
  13072. stream << value;
  13073. else
  13074. stream << Colour(Colour::Warning) << "- none -";
  13075. } else if (value != "0") {
  13076. stream << Colour(Colour::LightGrey) << " | ";
  13077. stream << Colour(col.colour)
  13078. << value << ' ' << col.label;
  13079. }
  13080. }
  13081. stream << '\n';
  13082. }
  13083. void ConsoleReporter::printTotalsDivider(Totals const& totals) {
  13084. if (totals.testCases.total() > 0) {
  13085. std::size_t failedRatio = makeRatio(totals.testCases.failed, totals.testCases.total());
  13086. std::size_t failedButOkRatio = makeRatio(totals.testCases.failedButOk, totals.testCases.total());
  13087. std::size_t passedRatio = makeRatio(totals.testCases.passed, totals.testCases.total());
  13088. while (failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1)
  13089. findMax(failedRatio, failedButOkRatio, passedRatio)++;
  13090. while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1)
  13091. findMax(failedRatio, failedButOkRatio, passedRatio)--;
  13092. stream << Colour(Colour::Error) << std::string(failedRatio, '=');
  13093. stream << Colour(Colour::ResultExpectedFailure) << std::string(failedButOkRatio, '=');
  13094. if (totals.testCases.allPassed())
  13095. stream << Colour(Colour::ResultSuccess) << std::string(passedRatio, '=');
  13096. else
  13097. stream << Colour(Colour::Success) << std::string(passedRatio, '=');
  13098. } else {
  13099. stream << Colour(Colour::Warning) << std::string(CATCH_CONFIG_CONSOLE_WIDTH - 1, '=');
  13100. }
  13101. stream << '\n';
  13102. }
  13103. void ConsoleReporter::printSummaryDivider() {
  13104. stream << getLineOfChars<'-'>() << '\n';
  13105. }
  13106. void ConsoleReporter::printTestFilters() {
  13107. if (m_config->testSpec().hasFilters())
  13108. stream << Colour(Colour::BrightYellow) << "Filters: " << serializeFilters( m_config->getTestsOrTags() ) << '\n';
  13109. }
  13110. CATCH_REGISTER_REPORTER("console", ConsoleReporter)
  13111. } // end namespace Catch
  13112. #if defined(_MSC_VER)
  13113. #pragma warning(pop)
  13114. #endif
  13115. #if defined(__clang__)
  13116. # pragma clang diagnostic pop
  13117. #endif
  13118. // end catch_reporter_console.cpp
  13119. // start catch_reporter_junit.cpp
  13120. #include <cassert>
  13121. #include <sstream>
  13122. #include <ctime>
  13123. #include <algorithm>
  13124. namespace Catch {
  13125. namespace {
  13126. std::string getCurrentTimestamp() {
  13127. // Beware, this is not reentrant because of backward compatibility issues
  13128. // Also, UTC only, again because of backward compatibility (%z is C++11)
  13129. time_t rawtime;
  13130. std::time(&rawtime);
  13131. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  13132. #ifdef _MSC_VER
  13133. std::tm timeInfo = {};
  13134. gmtime_s(&timeInfo, &rawtime);
  13135. #else
  13136. std::tm* timeInfo;
  13137. timeInfo = std::gmtime(&rawtime);
  13138. #endif
  13139. char timeStamp[timeStampSize];
  13140. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  13141. #ifdef _MSC_VER
  13142. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  13143. #else
  13144. std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
  13145. #endif
  13146. return std::string(timeStamp);
  13147. }
  13148. std::string fileNameTag(const std::vector<std::string> &tags) {
  13149. auto it = std::find_if(begin(tags),
  13150. end(tags),
  13151. [] (std::string const& tag) {return tag.front() == '#'; });
  13152. if (it != tags.end())
  13153. return it->substr(1);
  13154. return std::string();
  13155. }
  13156. } // anonymous namespace
  13157. JunitReporter::JunitReporter( ReporterConfig const& _config )
  13158. : CumulativeReporterBase( _config ),
  13159. xml( _config.stream() )
  13160. {
  13161. m_reporterPrefs.shouldRedirectStdOut = true;
  13162. m_reporterPrefs.shouldReportAllAssertions = true;
  13163. }
  13164. JunitReporter::~JunitReporter() {}
  13165. std::string JunitReporter::getDescription() {
  13166. return "Reports test results in an XML format that looks like Ant's junitreport target";
  13167. }
  13168. void JunitReporter::noMatchingTestCases( std::string const& /*spec*/ ) {}
  13169. void JunitReporter::testRunStarting( TestRunInfo const& runInfo ) {
  13170. CumulativeReporterBase::testRunStarting( runInfo );
  13171. xml.startElement( "testsuites" );
  13172. }
  13173. void JunitReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  13174. suiteTimer.start();
  13175. stdOutForSuite.clear();
  13176. stdErrForSuite.clear();
  13177. unexpectedExceptions = 0;
  13178. CumulativeReporterBase::testGroupStarting( groupInfo );
  13179. }
  13180. void JunitReporter::testCaseStarting( TestCaseInfo const& testCaseInfo ) {
  13181. m_okToFail = testCaseInfo.okToFail();
  13182. }
  13183. bool JunitReporter::assertionEnded( AssertionStats const& assertionStats ) {
  13184. if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail )
  13185. unexpectedExceptions++;
  13186. return CumulativeReporterBase::assertionEnded( assertionStats );
  13187. }
  13188. void JunitReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  13189. stdOutForSuite += testCaseStats.stdOut;
  13190. stdErrForSuite += testCaseStats.stdErr;
  13191. CumulativeReporterBase::testCaseEnded( testCaseStats );
  13192. }
  13193. void JunitReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  13194. double suiteTime = suiteTimer.getElapsedSeconds();
  13195. CumulativeReporterBase::testGroupEnded( testGroupStats );
  13196. writeGroup( *m_testGroups.back(), suiteTime );
  13197. }
  13198. void JunitReporter::testRunEndedCumulative() {
  13199. xml.endElement();
  13200. }
  13201. void JunitReporter::writeGroup( TestGroupNode const& groupNode, double suiteTime ) {
  13202. XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" );
  13203. TestGroupStats const& stats = groupNode.value;
  13204. xml.writeAttribute( "name", stats.groupInfo.name );
  13205. xml.writeAttribute( "errors", unexpectedExceptions );
  13206. xml.writeAttribute( "failures", stats.totals.assertions.failed-unexpectedExceptions );
  13207. xml.writeAttribute( "tests", stats.totals.assertions.total() );
  13208. xml.writeAttribute( "hostname", "tbd" ); // !TBD
  13209. if( m_config->showDurations() == ShowDurations::Never )
  13210. xml.writeAttribute( "time", "" );
  13211. else
  13212. xml.writeAttribute( "time", suiteTime );
  13213. xml.writeAttribute( "timestamp", getCurrentTimestamp() );
  13214. // Write properties if there are any
  13215. if (m_config->hasTestFilters() || m_config->rngSeed() != 0) {
  13216. auto properties = xml.scopedElement("properties");
  13217. if (m_config->hasTestFilters()) {
  13218. xml.scopedElement("property")
  13219. .writeAttribute("name", "filters")
  13220. .writeAttribute("value", serializeFilters(m_config->getTestsOrTags()));
  13221. }
  13222. if (m_config->rngSeed() != 0) {
  13223. xml.scopedElement("property")
  13224. .writeAttribute("name", "random-seed")
  13225. .writeAttribute("value", m_config->rngSeed());
  13226. }
  13227. }
  13228. // Write test cases
  13229. for( auto const& child : groupNode.children )
  13230. writeTestCase( *child );
  13231. xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite ), false );
  13232. xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite ), false );
  13233. }
  13234. void JunitReporter::writeTestCase( TestCaseNode const& testCaseNode ) {
  13235. TestCaseStats const& stats = testCaseNode.value;
  13236. // All test cases have exactly one section - which represents the
  13237. // test case itself. That section may have 0-n nested sections
  13238. assert( testCaseNode.children.size() == 1 );
  13239. SectionNode const& rootSection = *testCaseNode.children.front();
  13240. std::string className = stats.testInfo.className;
  13241. if( className.empty() ) {
  13242. className = fileNameTag(stats.testInfo.tags);
  13243. if ( className.empty() )
  13244. className = "global";
  13245. }
  13246. if ( !m_config->name().empty() )
  13247. className = m_config->name() + "." + className;
  13248. writeSection( className, "", rootSection );
  13249. }
  13250. void JunitReporter::writeSection( std::string const& className,
  13251. std::string const& rootName,
  13252. SectionNode const& sectionNode ) {
  13253. std::string name = trim( sectionNode.stats.sectionInfo.name );
  13254. if( !rootName.empty() )
  13255. name = rootName + '/' + name;
  13256. if( !sectionNode.assertions.empty() ||
  13257. !sectionNode.stdOut.empty() ||
  13258. !sectionNode.stdErr.empty() ) {
  13259. XmlWriter::ScopedElement e = xml.scopedElement( "testcase" );
  13260. if( className.empty() ) {
  13261. xml.writeAttribute( "classname", name );
  13262. xml.writeAttribute( "name", "root" );
  13263. }
  13264. else {
  13265. xml.writeAttribute( "classname", className );
  13266. xml.writeAttribute( "name", name );
  13267. }
  13268. xml.writeAttribute( "time", ::Catch::Detail::stringify( sectionNode.stats.durationInSeconds ) );
  13269. writeAssertions( sectionNode );
  13270. if( !sectionNode.stdOut.empty() )
  13271. xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), false );
  13272. if( !sectionNode.stdErr.empty() )
  13273. xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), false );
  13274. }
  13275. for( auto const& childNode : sectionNode.childSections )
  13276. if( className.empty() )
  13277. writeSection( name, "", *childNode );
  13278. else
  13279. writeSection( className, name, *childNode );
  13280. }
  13281. void JunitReporter::writeAssertions( SectionNode const& sectionNode ) {
  13282. for( auto const& assertion : sectionNode.assertions )
  13283. writeAssertion( assertion );
  13284. }
  13285. void JunitReporter::writeAssertion( AssertionStats const& stats ) {
  13286. AssertionResult const& result = stats.assertionResult;
  13287. if( !result.isOk() ) {
  13288. std::string elementName;
  13289. switch( result.getResultType() ) {
  13290. case ResultWas::ThrewException:
  13291. case ResultWas::FatalErrorCondition:
  13292. elementName = "error";
  13293. break;
  13294. case ResultWas::ExplicitFailure:
  13295. elementName = "failure";
  13296. break;
  13297. case ResultWas::ExpressionFailed:
  13298. elementName = "failure";
  13299. break;
  13300. case ResultWas::DidntThrowException:
  13301. elementName = "failure";
  13302. break;
  13303. // We should never see these here:
  13304. case ResultWas::Info:
  13305. case ResultWas::Warning:
  13306. case ResultWas::Ok:
  13307. case ResultWas::Unknown:
  13308. case ResultWas::FailureBit:
  13309. case ResultWas::Exception:
  13310. elementName = "internalError";
  13311. break;
  13312. }
  13313. XmlWriter::ScopedElement e = xml.scopedElement( elementName );
  13314. xml.writeAttribute( "message", result.getExpandedExpression() );
  13315. xml.writeAttribute( "type", result.getTestMacroName() );
  13316. ReusableStringStream rss;
  13317. if( !result.getMessage().empty() )
  13318. rss << result.getMessage() << '\n';
  13319. for( auto const& msg : stats.infoMessages )
  13320. if( msg.type == ResultWas::Info )
  13321. rss << msg.message << '\n';
  13322. rss << "at " << result.getSourceInfo();
  13323. xml.writeText( rss.str(), false );
  13324. }
  13325. }
  13326. CATCH_REGISTER_REPORTER( "junit", JunitReporter )
  13327. } // end namespace Catch
  13328. // end catch_reporter_junit.cpp
  13329. // start catch_reporter_listening.cpp
  13330. #include <cassert>
  13331. namespace Catch {
  13332. ListeningReporter::ListeningReporter() {
  13333. // We will assume that listeners will always want all assertions
  13334. m_preferences.shouldReportAllAssertions = true;
  13335. }
  13336. void ListeningReporter::addListener( IStreamingReporterPtr&& listener ) {
  13337. m_listeners.push_back( std::move( listener ) );
  13338. }
  13339. void ListeningReporter::addReporter(IStreamingReporterPtr&& reporter) {
  13340. assert(!m_reporter && "Listening reporter can wrap only 1 real reporter");
  13341. m_reporter = std::move( reporter );
  13342. m_preferences.shouldRedirectStdOut = m_reporter->getPreferences().shouldRedirectStdOut;
  13343. }
  13344. ReporterPreferences ListeningReporter::getPreferences() const {
  13345. return m_preferences;
  13346. }
  13347. std::set<Verbosity> ListeningReporter::getSupportedVerbosities() {
  13348. return std::set<Verbosity>{ };
  13349. }
  13350. void ListeningReporter::noMatchingTestCases( std::string const& spec ) {
  13351. for ( auto const& listener : m_listeners ) {
  13352. listener->noMatchingTestCases( spec );
  13353. }
  13354. m_reporter->noMatchingTestCases( spec );
  13355. }
  13356. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  13357. void ListeningReporter::benchmarkPreparing( std::string const& name ) {
  13358. for (auto const& listener : m_listeners) {
  13359. listener->benchmarkPreparing(name);
  13360. }
  13361. m_reporter->benchmarkPreparing(name);
  13362. }
  13363. void ListeningReporter::benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) {
  13364. for ( auto const& listener : m_listeners ) {
  13365. listener->benchmarkStarting( benchmarkInfo );
  13366. }
  13367. m_reporter->benchmarkStarting( benchmarkInfo );
  13368. }
  13369. void ListeningReporter::benchmarkEnded( BenchmarkStats<> const& benchmarkStats ) {
  13370. for ( auto const& listener : m_listeners ) {
  13371. listener->benchmarkEnded( benchmarkStats );
  13372. }
  13373. m_reporter->benchmarkEnded( benchmarkStats );
  13374. }
  13375. void ListeningReporter::benchmarkFailed( std::string const& error ) {
  13376. for (auto const& listener : m_listeners) {
  13377. listener->benchmarkFailed(error);
  13378. }
  13379. m_reporter->benchmarkFailed(error);
  13380. }
  13381. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  13382. void ListeningReporter::testRunStarting( TestRunInfo const& testRunInfo ) {
  13383. for ( auto const& listener : m_listeners ) {
  13384. listener->testRunStarting( testRunInfo );
  13385. }
  13386. m_reporter->testRunStarting( testRunInfo );
  13387. }
  13388. void ListeningReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  13389. for ( auto const& listener : m_listeners ) {
  13390. listener->testGroupStarting( groupInfo );
  13391. }
  13392. m_reporter->testGroupStarting( groupInfo );
  13393. }
  13394. void ListeningReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
  13395. for ( auto const& listener : m_listeners ) {
  13396. listener->testCaseStarting( testInfo );
  13397. }
  13398. m_reporter->testCaseStarting( testInfo );
  13399. }
  13400. void ListeningReporter::sectionStarting( SectionInfo const& sectionInfo ) {
  13401. for ( auto const& listener : m_listeners ) {
  13402. listener->sectionStarting( sectionInfo );
  13403. }
  13404. m_reporter->sectionStarting( sectionInfo );
  13405. }
  13406. void ListeningReporter::assertionStarting( AssertionInfo const& assertionInfo ) {
  13407. for ( auto const& listener : m_listeners ) {
  13408. listener->assertionStarting( assertionInfo );
  13409. }
  13410. m_reporter->assertionStarting( assertionInfo );
  13411. }
  13412. // The return value indicates if the messages buffer should be cleared:
  13413. bool ListeningReporter::assertionEnded( AssertionStats const& assertionStats ) {
  13414. for( auto const& listener : m_listeners ) {
  13415. static_cast<void>( listener->assertionEnded( assertionStats ) );
  13416. }
  13417. return m_reporter->assertionEnded( assertionStats );
  13418. }
  13419. void ListeningReporter::sectionEnded( SectionStats const& sectionStats ) {
  13420. for ( auto const& listener : m_listeners ) {
  13421. listener->sectionEnded( sectionStats );
  13422. }
  13423. m_reporter->sectionEnded( sectionStats );
  13424. }
  13425. void ListeningReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  13426. for ( auto const& listener : m_listeners ) {
  13427. listener->testCaseEnded( testCaseStats );
  13428. }
  13429. m_reporter->testCaseEnded( testCaseStats );
  13430. }
  13431. void ListeningReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  13432. for ( auto const& listener : m_listeners ) {
  13433. listener->testGroupEnded( testGroupStats );
  13434. }
  13435. m_reporter->testGroupEnded( testGroupStats );
  13436. }
  13437. void ListeningReporter::testRunEnded( TestRunStats const& testRunStats ) {
  13438. for ( auto const& listener : m_listeners ) {
  13439. listener->testRunEnded( testRunStats );
  13440. }
  13441. m_reporter->testRunEnded( testRunStats );
  13442. }
  13443. void ListeningReporter::skipTest( TestCaseInfo const& testInfo ) {
  13444. for ( auto const& listener : m_listeners ) {
  13445. listener->skipTest( testInfo );
  13446. }
  13447. m_reporter->skipTest( testInfo );
  13448. }
  13449. bool ListeningReporter::isMulti() const {
  13450. return true;
  13451. }
  13452. } // end namespace Catch
  13453. // end catch_reporter_listening.cpp
  13454. // start catch_reporter_xml.cpp
  13455. #if defined(_MSC_VER)
  13456. #pragma warning(push)
  13457. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  13458. // Note that 4062 (not all labels are handled
  13459. // and default is missing) is enabled
  13460. #endif
  13461. namespace Catch {
  13462. XmlReporter::XmlReporter( ReporterConfig const& _config )
  13463. : StreamingReporterBase( _config ),
  13464. m_xml(_config.stream())
  13465. {
  13466. m_reporterPrefs.shouldRedirectStdOut = true;
  13467. m_reporterPrefs.shouldReportAllAssertions = true;
  13468. }
  13469. XmlReporter::~XmlReporter() = default;
  13470. std::string XmlReporter::getDescription() {
  13471. return "Reports test results as an XML document";
  13472. }
  13473. std::string XmlReporter::getStylesheetRef() const {
  13474. return std::string();
  13475. }
  13476. void XmlReporter::writeSourceInfo( SourceLineInfo const& sourceInfo ) {
  13477. m_xml
  13478. .writeAttribute( "filename", sourceInfo.file )
  13479. .writeAttribute( "line", sourceInfo.line );
  13480. }
  13481. void XmlReporter::noMatchingTestCases( std::string const& s ) {
  13482. StreamingReporterBase::noMatchingTestCases( s );
  13483. }
  13484. void XmlReporter::testRunStarting( TestRunInfo const& testInfo ) {
  13485. StreamingReporterBase::testRunStarting( testInfo );
  13486. std::string stylesheetRef = getStylesheetRef();
  13487. if( !stylesheetRef.empty() )
  13488. m_xml.writeStylesheetRef( stylesheetRef );
  13489. m_xml.startElement( "Catch" );
  13490. if( !m_config->name().empty() )
  13491. m_xml.writeAttribute( "name", m_config->name() );
  13492. if (m_config->testSpec().hasFilters())
  13493. m_xml.writeAttribute( "filters", serializeFilters( m_config->getTestsOrTags() ) );
  13494. if( m_config->rngSeed() != 0 )
  13495. m_xml.scopedElement( "Randomness" )
  13496. .writeAttribute( "seed", m_config->rngSeed() );
  13497. }
  13498. void XmlReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  13499. StreamingReporterBase::testGroupStarting( groupInfo );
  13500. m_xml.startElement( "Group" )
  13501. .writeAttribute( "name", groupInfo.name );
  13502. }
  13503. void XmlReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
  13504. StreamingReporterBase::testCaseStarting(testInfo);
  13505. m_xml.startElement( "TestCase" )
  13506. .writeAttribute( "name", trim( testInfo.name ) )
  13507. .writeAttribute( "description", testInfo.description )
  13508. .writeAttribute( "tags", testInfo.tagsAsString() );
  13509. writeSourceInfo( testInfo.lineInfo );
  13510. if ( m_config->showDurations() == ShowDurations::Always )
  13511. m_testCaseTimer.start();
  13512. m_xml.ensureTagClosed();
  13513. }
  13514. void XmlReporter::sectionStarting( SectionInfo const& sectionInfo ) {
  13515. StreamingReporterBase::sectionStarting( sectionInfo );
  13516. if( m_sectionDepth++ > 0 ) {
  13517. m_xml.startElement( "Section" )
  13518. .writeAttribute( "name", trim( sectionInfo.name ) );
  13519. writeSourceInfo( sectionInfo.lineInfo );
  13520. m_xml.ensureTagClosed();
  13521. }
  13522. }
  13523. void XmlReporter::assertionStarting( AssertionInfo const& ) { }
  13524. bool XmlReporter::assertionEnded( AssertionStats const& assertionStats ) {
  13525. AssertionResult const& result = assertionStats.assertionResult;
  13526. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  13527. if( includeResults || result.getResultType() == ResultWas::Warning ) {
  13528. // Print any info messages in <Info> tags.
  13529. for( auto const& msg : assertionStats.infoMessages ) {
  13530. if( msg.type == ResultWas::Info && includeResults ) {
  13531. m_xml.scopedElement( "Info" )
  13532. .writeText( msg.message );
  13533. } else if ( msg.type == ResultWas::Warning ) {
  13534. m_xml.scopedElement( "Warning" )
  13535. .writeText( msg.message );
  13536. }
  13537. }
  13538. }
  13539. // Drop out if result was successful but we're not printing them.
  13540. if( !includeResults && result.getResultType() != ResultWas::Warning )
  13541. return true;
  13542. // Print the expression if there is one.
  13543. if( result.hasExpression() ) {
  13544. m_xml.startElement( "Expression" )
  13545. .writeAttribute( "success", result.succeeded() )
  13546. .writeAttribute( "type", result.getTestMacroName() );
  13547. writeSourceInfo( result.getSourceInfo() );
  13548. m_xml.scopedElement( "Original" )
  13549. .writeText( result.getExpression() );
  13550. m_xml.scopedElement( "Expanded" )
  13551. .writeText( result.getExpandedExpression() );
  13552. }
  13553. // And... Print a result applicable to each result type.
  13554. switch( result.getResultType() ) {
  13555. case ResultWas::ThrewException:
  13556. m_xml.startElement( "Exception" );
  13557. writeSourceInfo( result.getSourceInfo() );
  13558. m_xml.writeText( result.getMessage() );
  13559. m_xml.endElement();
  13560. break;
  13561. case ResultWas::FatalErrorCondition:
  13562. m_xml.startElement( "FatalErrorCondition" );
  13563. writeSourceInfo( result.getSourceInfo() );
  13564. m_xml.writeText( result.getMessage() );
  13565. m_xml.endElement();
  13566. break;
  13567. case ResultWas::Info:
  13568. m_xml.scopedElement( "Info" )
  13569. .writeText( result.getMessage() );
  13570. break;
  13571. case ResultWas::Warning:
  13572. // Warning will already have been written
  13573. break;
  13574. case ResultWas::ExplicitFailure:
  13575. m_xml.startElement( "Failure" );
  13576. writeSourceInfo( result.getSourceInfo() );
  13577. m_xml.writeText( result.getMessage() );
  13578. m_xml.endElement();
  13579. break;
  13580. default:
  13581. break;
  13582. }
  13583. if( result.hasExpression() )
  13584. m_xml.endElement();
  13585. return true;
  13586. }
  13587. void XmlReporter::sectionEnded( SectionStats const& sectionStats ) {
  13588. StreamingReporterBase::sectionEnded( sectionStats );
  13589. if( --m_sectionDepth > 0 ) {
  13590. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResults" );
  13591. e.writeAttribute( "successes", sectionStats.assertions.passed );
  13592. e.writeAttribute( "failures", sectionStats.assertions.failed );
  13593. e.writeAttribute( "expectedFailures", sectionStats.assertions.failedButOk );
  13594. if ( m_config->showDurations() == ShowDurations::Always )
  13595. e.writeAttribute( "durationInSeconds", sectionStats.durationInSeconds );
  13596. m_xml.endElement();
  13597. }
  13598. }
  13599. void XmlReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  13600. StreamingReporterBase::testCaseEnded( testCaseStats );
  13601. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResult" );
  13602. e.writeAttribute( "success", testCaseStats.totals.assertions.allOk() );
  13603. if ( m_config->showDurations() == ShowDurations::Always )
  13604. e.writeAttribute( "durationInSeconds", m_testCaseTimer.getElapsedSeconds() );
  13605. if( !testCaseStats.stdOut.empty() )
  13606. m_xml.scopedElement( "StdOut" ).writeText( trim( testCaseStats.stdOut ), false );
  13607. if( !testCaseStats.stdErr.empty() )
  13608. m_xml.scopedElement( "StdErr" ).writeText( trim( testCaseStats.stdErr ), false );
  13609. m_xml.endElement();
  13610. }
  13611. void XmlReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  13612. StreamingReporterBase::testGroupEnded( testGroupStats );
  13613. // TODO: Check testGroupStats.aborting and act accordingly.
  13614. m_xml.scopedElement( "OverallResults" )
  13615. .writeAttribute( "successes", testGroupStats.totals.assertions.passed )
  13616. .writeAttribute( "failures", testGroupStats.totals.assertions.failed )
  13617. .writeAttribute( "expectedFailures", testGroupStats.totals.assertions.failedButOk );
  13618. m_xml.endElement();
  13619. }
  13620. void XmlReporter::testRunEnded( TestRunStats const& testRunStats ) {
  13621. StreamingReporterBase::testRunEnded( testRunStats );
  13622. m_xml.scopedElement( "OverallResults" )
  13623. .writeAttribute( "successes", testRunStats.totals.assertions.passed )
  13624. .writeAttribute( "failures", testRunStats.totals.assertions.failed )
  13625. .writeAttribute( "expectedFailures", testRunStats.totals.assertions.failedButOk );
  13626. m_xml.endElement();
  13627. }
  13628. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  13629. void XmlReporter::benchmarkPreparing(std::string const& name) {
  13630. m_xml.startElement("BenchmarkResults")
  13631. .writeAttribute("name", name);
  13632. }
  13633. void XmlReporter::benchmarkStarting(BenchmarkInfo const &info) {
  13634. m_xml.writeAttribute("samples", info.samples)
  13635. .writeAttribute("resamples", info.resamples)
  13636. .writeAttribute("iterations", info.iterations)
  13637. .writeAttribute("clockResolution", static_cast<uint64_t>(info.clockResolution))
  13638. .writeAttribute("estimatedDuration", static_cast<uint64_t>(info.estimatedDuration))
  13639. .writeComment("All values in nano seconds");
  13640. }
  13641. void XmlReporter::benchmarkEnded(BenchmarkStats<> const& benchmarkStats) {
  13642. m_xml.startElement("mean")
  13643. .writeAttribute("value", static_cast<uint64_t>(benchmarkStats.mean.point.count()))
  13644. .writeAttribute("lowerBound", static_cast<uint64_t>(benchmarkStats.mean.lower_bound.count()))
  13645. .writeAttribute("upperBound", static_cast<uint64_t>(benchmarkStats.mean.upper_bound.count()))
  13646. .writeAttribute("ci", benchmarkStats.mean.confidence_interval);
  13647. m_xml.endElement();
  13648. m_xml.startElement("standardDeviation")
  13649. .writeAttribute("value", benchmarkStats.standardDeviation.point.count())
  13650. .writeAttribute("lowerBound", benchmarkStats.standardDeviation.lower_bound.count())
  13651. .writeAttribute("upperBound", benchmarkStats.standardDeviation.upper_bound.count())
  13652. .writeAttribute("ci", benchmarkStats.standardDeviation.confidence_interval);
  13653. m_xml.endElement();
  13654. m_xml.startElement("outliers")
  13655. .writeAttribute("variance", benchmarkStats.outlierVariance)
  13656. .writeAttribute("lowMild", benchmarkStats.outliers.low_mild)
  13657. .writeAttribute("lowSevere", benchmarkStats.outliers.low_severe)
  13658. .writeAttribute("highMild", benchmarkStats.outliers.high_mild)
  13659. .writeAttribute("highSevere", benchmarkStats.outliers.high_severe);
  13660. m_xml.endElement();
  13661. m_xml.endElement();
  13662. }
  13663. void XmlReporter::benchmarkFailed(std::string const &error) {
  13664. m_xml.scopedElement("failed").
  13665. writeAttribute("message", error);
  13666. m_xml.endElement();
  13667. }
  13668. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  13669. CATCH_REGISTER_REPORTER( "xml", XmlReporter )
  13670. } // end namespace Catch
  13671. #if defined(_MSC_VER)
  13672. #pragma warning(pop)
  13673. #endif
  13674. // end catch_reporter_xml.cpp
  13675. namespace Catch {
  13676. LeakDetector leakDetector;
  13677. }
  13678. #ifdef __clang__
  13679. #pragma clang diagnostic pop
  13680. #endif
  13681. // end catch_impl.hpp
  13682. #endif
  13683. #ifdef CATCH_CONFIG_MAIN
  13684. // start catch_default_main.hpp
  13685. #ifndef __OBJC__
  13686. #if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN)
  13687. // Standard C/C++ Win32 Unicode wmain entry point
  13688. extern "C" int wmain (int argc, wchar_t * argv[], wchar_t * []) {
  13689. #else
  13690. // Standard C/C++ main entry point
  13691. int main (int argc, char * argv[]) {
  13692. #endif
  13693. return Catch::Session().run( argc, argv );
  13694. }
  13695. #else // __OBJC__
  13696. // Objective-C entry point
  13697. int main (int argc, char * const argv[]) {
  13698. #if !CATCH_ARC_ENABLED
  13699. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  13700. #endif
  13701. Catch::registerTestMethods();
  13702. int result = Catch::Session().run( argc, (char**)argv );
  13703. #if !CATCH_ARC_ENABLED
  13704. [pool drain];
  13705. #endif
  13706. return result;
  13707. }
  13708. #endif // __OBJC__
  13709. // end catch_default_main.hpp
  13710. #endif
  13711. #if !defined(CATCH_CONFIG_IMPL_ONLY)
  13712. #ifdef CLARA_CONFIG_MAIN_NOT_DEFINED
  13713. # undef CLARA_CONFIG_MAIN
  13714. #endif
  13715. #if !defined(CATCH_CONFIG_DISABLE)
  13716. //////
  13717. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  13718. #ifdef CATCH_CONFIG_PREFIX_ALL
  13719. #define CATCH_REQUIRE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  13720. #define CATCH_REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  13721. #define CATCH_REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  13722. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  13723. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  13724. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13725. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  13726. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  13727. #define CATCH_REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  13728. #define CATCH_CHECK( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13729. #define CATCH_CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  13730. #define CATCH_CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13731. #define CATCH_CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13732. #define CATCH_CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  13733. #define CATCH_CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13734. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  13735. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  13736. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13737. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  13738. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  13739. #define CATCH_CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13740. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13741. #define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  13742. #define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  13743. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  13744. #define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg )
  13745. #define CATCH_UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "CATCH_UNSCOPED_INFO", msg )
  13746. #define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  13747. #define CATCH_CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CATCH_CAPTURE",__VA_ARGS__ )
  13748. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  13749. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13750. #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  13751. #define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  13752. #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  13753. #define CATCH_DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
  13754. #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  13755. #define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13756. #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13757. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  13758. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  13759. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  13760. #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ )
  13761. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13762. #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
  13763. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )
  13764. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ )
  13765. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13766. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
  13767. #else
  13768. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
  13769. #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) )
  13770. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  13771. #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
  13772. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )
  13773. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) )
  13774. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  13775. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
  13776. #endif
  13777. #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
  13778. #define CATCH_STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__ , #__VA_ARGS__ ); CATCH_SUCCEED( #__VA_ARGS__ )
  13779. #define CATCH_STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); CATCH_SUCCEED( #__VA_ARGS__ )
  13780. #else
  13781. #define CATCH_STATIC_REQUIRE( ... ) CATCH_REQUIRE( __VA_ARGS__ )
  13782. #define CATCH_STATIC_REQUIRE_FALSE( ... ) CATCH_REQUIRE_FALSE( __VA_ARGS__ )
  13783. #endif
  13784. // "BDD-style" convenience wrappers
  13785. #define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ )
  13786. #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  13787. #define CATCH_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
  13788. #define CATCH_AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
  13789. #define CATCH_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
  13790. #define CATCH_AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
  13791. #define CATCH_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
  13792. #define CATCH_AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
  13793. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  13794. #define CATCH_BENCHMARK(...) \
  13795. 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__,,))
  13796. #define CATCH_BENCHMARK_ADVANCED(name) \
  13797. INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), name)
  13798. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  13799. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  13800. #else
  13801. #define REQUIRE( ... ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  13802. #define REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  13803. #define REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  13804. #define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  13805. #define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  13806. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13807. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  13808. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  13809. #define REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  13810. #define CHECK( ... ) INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13811. #define CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  13812. #define CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13813. #define CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13814. #define CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  13815. #define CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13816. #define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  13817. #define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  13818. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13819. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  13820. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  13821. #define CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13822. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13823. #define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  13824. #define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  13825. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  13826. #define INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg )
  13827. #define UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "UNSCOPED_INFO", msg )
  13828. #define WARN( msg ) INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  13829. #define CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CAPTURE",__VA_ARGS__ )
  13830. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  13831. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13832. #define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  13833. #define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  13834. #define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  13835. #define DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
  13836. #define FAIL( ... ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  13837. #define FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13838. #define SUCCEED( ... ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13839. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  13840. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  13841. #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  13842. #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ )
  13843. #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13844. #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
  13845. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )
  13846. #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ )
  13847. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13848. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
  13849. #define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(__VA_ARGS__)
  13850. #define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13851. #else
  13852. #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
  13853. #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) )
  13854. #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  13855. #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
  13856. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )
  13857. #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) )
  13858. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  13859. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
  13860. #define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE( __VA_ARGS__ ) )
  13861. #define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  13862. #endif
  13863. #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
  13864. #define STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__, #__VA_ARGS__ ); SUCCEED( #__VA_ARGS__ )
  13865. #define STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); SUCCEED( "!(" #__VA_ARGS__ ")" )
  13866. #else
  13867. #define STATIC_REQUIRE( ... ) REQUIRE( __VA_ARGS__ )
  13868. #define STATIC_REQUIRE_FALSE( ... ) REQUIRE_FALSE( __VA_ARGS__ )
  13869. #endif
  13870. #endif
  13871. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature )
  13872. // "BDD-style" convenience wrappers
  13873. #define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ )
  13874. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  13875. #define GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
  13876. #define AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
  13877. #define WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
  13878. #define AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
  13879. #define THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
  13880. #define AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
  13881. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  13882. #define BENCHMARK(...) \
  13883. 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__,,))
  13884. #define BENCHMARK_ADVANCED(name) \
  13885. INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), name)
  13886. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  13887. using Catch::Detail::Approx;
  13888. #else // CATCH_CONFIG_DISABLE
  13889. //////
  13890. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  13891. #ifdef CATCH_CONFIG_PREFIX_ALL
  13892. #define CATCH_REQUIRE( ... ) (void)(0)
  13893. #define CATCH_REQUIRE_FALSE( ... ) (void)(0)
  13894. #define CATCH_REQUIRE_THROWS( ... ) (void)(0)
  13895. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  13896. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  13897. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13898. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  13899. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  13900. #define CATCH_REQUIRE_NOTHROW( ... ) (void)(0)
  13901. #define CATCH_CHECK( ... ) (void)(0)
  13902. #define CATCH_CHECK_FALSE( ... ) (void)(0)
  13903. #define CATCH_CHECKED_IF( ... ) if (__VA_ARGS__)
  13904. #define CATCH_CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  13905. #define CATCH_CHECK_NOFAIL( ... ) (void)(0)
  13906. #define CATCH_CHECK_THROWS( ... ) (void)(0)
  13907. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  13908. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  13909. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13910. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  13911. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  13912. #define CATCH_CHECK_NOTHROW( ... ) (void)(0)
  13913. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13914. #define CATCH_CHECK_THAT( arg, matcher ) (void)(0)
  13915. #define CATCH_REQUIRE_THAT( arg, matcher ) (void)(0)
  13916. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  13917. #define CATCH_INFO( msg ) (void)(0)
  13918. #define CATCH_UNSCOPED_INFO( msg ) (void)(0)
  13919. #define CATCH_WARN( msg ) (void)(0)
  13920. #define CATCH_CAPTURE( msg ) (void)(0)
  13921. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  13922. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  13923. #define CATCH_METHOD_AS_TEST_CASE( method, ... )
  13924. #define CATCH_REGISTER_TEST_CASE( Function, ... ) (void)(0)
  13925. #define CATCH_SECTION( ... )
  13926. #define CATCH_DYNAMIC_SECTION( ... )
  13927. #define CATCH_FAIL( ... ) (void)(0)
  13928. #define CATCH_FAIL_CHECK( ... ) (void)(0)
  13929. #define CATCH_SUCCEED( ... ) (void)(0)
  13930. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  13931. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  13932. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
  13933. #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
  13934. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
  13935. #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ )
  13936. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  13937. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  13938. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13939. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13940. #else
  13941. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) )
  13942. #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) )
  13943. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) )
  13944. #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) )
  13945. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  13946. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  13947. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13948. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13949. #endif
  13950. // "BDD-style" convenience wrappers
  13951. #define CATCH_SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  13952. #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 )
  13953. #define CATCH_GIVEN( desc )
  13954. #define CATCH_AND_GIVEN( desc )
  13955. #define CATCH_WHEN( desc )
  13956. #define CATCH_AND_WHEN( desc )
  13957. #define CATCH_THEN( desc )
  13958. #define CATCH_AND_THEN( desc )
  13959. #define CATCH_STATIC_REQUIRE( ... ) (void)(0)
  13960. #define CATCH_STATIC_REQUIRE_FALSE( ... ) (void)(0)
  13961. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  13962. #else
  13963. #define REQUIRE( ... ) (void)(0)
  13964. #define REQUIRE_FALSE( ... ) (void)(0)
  13965. #define REQUIRE_THROWS( ... ) (void)(0)
  13966. #define REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  13967. #define REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  13968. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13969. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  13970. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  13971. #define REQUIRE_NOTHROW( ... ) (void)(0)
  13972. #define CHECK( ... ) (void)(0)
  13973. #define CHECK_FALSE( ... ) (void)(0)
  13974. #define CHECKED_IF( ... ) if (__VA_ARGS__)
  13975. #define CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  13976. #define CHECK_NOFAIL( ... ) (void)(0)
  13977. #define CHECK_THROWS( ... ) (void)(0)
  13978. #define CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  13979. #define CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  13980. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13981. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  13982. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  13983. #define CHECK_NOTHROW( ... ) (void)(0)
  13984. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13985. #define CHECK_THAT( arg, matcher ) (void)(0)
  13986. #define REQUIRE_THAT( arg, matcher ) (void)(0)
  13987. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  13988. #define INFO( msg ) (void)(0)
  13989. #define UNSCOPED_INFO( msg ) (void)(0)
  13990. #define WARN( msg ) (void)(0)
  13991. #define CAPTURE( msg ) (void)(0)
  13992. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  13993. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  13994. #define METHOD_AS_TEST_CASE( method, ... )
  13995. #define REGISTER_TEST_CASE( Function, ... ) (void)(0)
  13996. #define SECTION( ... )
  13997. #define DYNAMIC_SECTION( ... )
  13998. #define FAIL( ... ) (void)(0)
  13999. #define FAIL_CHECK( ... ) (void)(0)
  14000. #define SUCCEED( ... ) (void)(0)
  14001. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  14002. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  14003. #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
  14004. #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
  14005. #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
  14006. #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ )
  14007. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14008. #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14009. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14010. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14011. #else
  14012. #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) )
  14013. #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) )
  14014. #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) )
  14015. #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) )
  14016. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14017. #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14018. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14019. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14020. #endif
  14021. #define STATIC_REQUIRE( ... ) (void)(0)
  14022. #define STATIC_REQUIRE_FALSE( ... ) (void)(0)
  14023. #endif
  14024. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
  14025. // "BDD-style" convenience wrappers
  14026. #define SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) )
  14027. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className )
  14028. #define GIVEN( desc )
  14029. #define AND_GIVEN( desc )
  14030. #define WHEN( desc )
  14031. #define AND_WHEN( desc )
  14032. #define THEN( desc )
  14033. #define AND_THEN( desc )
  14034. using Catch::Detail::Approx;
  14035. #endif
  14036. #endif // ! CATCH_CONFIG_IMPL_ONLY
  14037. // start catch_reenable_warnings.h
  14038. #ifdef __clang__
  14039. # ifdef __ICC // icpc defines the __clang__ macro
  14040. # pragma warning(pop)
  14041. # else
  14042. # pragma clang diagnostic pop
  14043. # endif
  14044. #elif defined __GNUC__
  14045. # pragma GCC diagnostic pop
  14046. #endif
  14047. // end catch_reenable_warnings.h
  14048. // end catch.hpp
  14049. #endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED