catch.hpp 601 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138
  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 {
  366. enum Choice {
  367. Yes,
  368. No
  369. };
  370. };
  371. class NonCopyable {
  372. NonCopyable(NonCopyable const &) = delete;
  373. NonCopyable(NonCopyable &&) = delete;
  374. NonCopyable &operator=(NonCopyable const &) = delete;
  375. NonCopyable &operator=(NonCopyable &&) = delete;
  376. protected:
  377. NonCopyable();
  378. virtual ~NonCopyable();
  379. };
  380. struct SourceLineInfo {
  381. SourceLineInfo() = delete;
  382. SourceLineInfo(char const *_file, std::size_t _line) noexcept
  383. : file(_file),
  384. line(_line) {}
  385. SourceLineInfo(SourceLineInfo const &other) = default;
  386. SourceLineInfo &operator=(SourceLineInfo const &) = default;
  387. SourceLineInfo(SourceLineInfo &&) noexcept = default;
  388. SourceLineInfo &operator=(SourceLineInfo &&) noexcept = default;
  389. bool empty() const noexcept;
  390. bool operator==(SourceLineInfo const &other) const noexcept;
  391. bool operator<(SourceLineInfo const &other) const noexcept;
  392. char const *file;
  393. std::size_t line;
  394. };
  395. std::ostream &operator<<(std::ostream &os, SourceLineInfo const &info);
  396. // Bring in operator<< from global namespace into Catch namespace
  397. // This is necessary because the overload of operator<< above makes
  398. // lookup stop at namespace Catch
  399. using ::operator<<;
  400. // Use this in variadic streaming macros to allow
  401. // >> +StreamEndStop
  402. // as well as
  403. // >> stuff +StreamEndStop
  404. struct StreamEndStop {
  405. std::string operator+() const;
  406. };
  407. template<typename T>
  408. T const &operator+(T const &value, StreamEndStop) {
  409. return value;
  410. }
  411. }
  412. #define CATCH_INTERNAL_LINEINFO \
  413. ::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) )
  414. // end catch_common.h
  415. namespace Catch {
  416. struct RegistrarForTagAliases {
  417. RegistrarForTagAliases(char const *alias, char const *tag, SourceLineInfo const &lineInfo);
  418. };
  419. } // end namespace Catch
  420. #define CATCH_REGISTER_TAG_ALIAS(alias, spec) \
  421. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  422. namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } \
  423. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  424. // end catch_tag_alias_autoregistrar.h
  425. // start catch_test_registry.h
  426. // start catch_interfaces_testcase.h
  427. #include <vector>
  428. namespace Catch {
  429. class TestSpec;
  430. struct ITestInvoker {
  431. virtual void invoke() const = 0;
  432. virtual ~ITestInvoker();
  433. };
  434. class TestCase;
  435. struct IConfig;
  436. struct ITestCaseRegistry {
  437. virtual ~ITestCaseRegistry();
  438. virtual std::vector<TestCase> const &getAllTests() const = 0;
  439. virtual std::vector<TestCase> const &getAllTestsSorted(IConfig const &config) const = 0;
  440. };
  441. bool isThrowSafe(TestCase const &testCase, IConfig const &config);
  442. bool matchTest(TestCase const &testCase, TestSpec const &testSpec, IConfig const &config);
  443. std::vector<TestCase> filterTests(std::vector<TestCase> const &testCases,
  444. TestSpec const &testSpec,
  445. IConfig const &config);
  446. std::vector<TestCase> const &getAllTestCasesSorted(IConfig const &config);
  447. }
  448. // end catch_interfaces_testcase.h
  449. // start catch_stringref.h
  450. #include <cstddef>
  451. #include <string>
  452. #include <iosfwd>
  453. namespace Catch {
  454. /// A non-owning string class (similar to the forthcoming std::string_view)
  455. /// Note that, because a StringRef may be a substring of another string,
  456. /// it may not be null terminated. c_str() must return a null terminated
  457. /// string, however, and so the StringRef will internally take ownership
  458. /// (taking a copy), if necessary. In theory this ownership is not externally
  459. /// visible - but it does mean (substring) StringRefs should not be shared between
  460. /// threads.
  461. class StringRef {
  462. public:
  463. using size_type = std::size_t;
  464. private:
  465. friend struct StringRefTestAccess;
  466. char const *m_start;
  467. size_type m_size;
  468. char *m_data = nullptr;
  469. void takeOwnership();
  470. static constexpr char const *const s_empty = "";
  471. public: // construction/ assignment
  472. StringRef() noexcept
  473. : StringRef(s_empty, 0) {}
  474. StringRef(StringRef const &other) noexcept
  475. : m_start(other.m_start),
  476. m_size(other.m_size) {}
  477. StringRef(StringRef &&other) noexcept
  478. : m_start(other.m_start),
  479. m_size(other.m_size),
  480. m_data(other.m_data) {
  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. StringRef(std::string const &stdString) noexcept
  488. : m_start(stdString.c_str()),
  489. m_size(stdString.size()) {}
  490. ~StringRef() noexcept {
  491. delete[] m_data;
  492. }
  493. auto operator=(StringRef const &other) noexcept -> StringRef & {
  494. delete[] m_data;
  495. m_data = nullptr;
  496. m_start = other.m_start;
  497. m_size = other.m_size;
  498. return *this;
  499. }
  500. operator std::string() const;
  501. void swap(StringRef &other) noexcept;
  502. public: // operators
  503. auto operator==(StringRef const &other) const noexcept -> bool;
  504. auto operator!=(StringRef const &other) const noexcept -> bool;
  505. auto operator[](size_type index) const noexcept -> char;
  506. public: // named queries
  507. auto empty() const noexcept -> bool {
  508. return m_size == 0;
  509. }
  510. auto size() const noexcept -> size_type {
  511. return m_size;
  512. }
  513. auto numberOfCharacters() const noexcept -> size_type;
  514. auto c_str() const -> char const *;
  515. public: // substrings and searches
  516. auto substr(size_type start, size_type size) const noexcept -> StringRef;
  517. // Returns the current start pointer.
  518. // Note that the pointer can change when if the StringRef is a substring
  519. auto currentData() const noexcept -> char const *;
  520. private: // ownership queries - may not be consistent between calls
  521. auto isOwned() const noexcept -> bool;
  522. auto isSubstring() const noexcept -> bool;
  523. };
  524. auto operator+(StringRef const &lhs, StringRef const &rhs) -> std::string;
  525. auto operator+(StringRef const &lhs, char const *rhs) -> std::string;
  526. auto operator+(char const *lhs, StringRef const &rhs) -> std::string;
  527. auto operator+=(std::string &lhs, StringRef const &sr) -> std::string &;
  528. auto operator<<(std::ostream &os, StringRef const &sr) -> std::ostream &;
  529. inline auto operator "" _sr(char const *rawChars, std::size_t size) noexcept -> StringRef {
  530. return StringRef(rawChars, size);
  531. }
  532. } // namespace Catch
  533. inline auto operator "" _catch_sr(char const *rawChars,
  534. std::size_t size) noexcept -> Catch::StringRef {
  535. return Catch::StringRef(rawChars, size);
  536. }
  537. // end catch_stringref.h
  538. // start catch_type_traits.hpp
  539. #include <type_traits>
  540. namespace Catch {
  541. #ifdef CATCH_CPP17_OR_GREATER
  542. template <typename...>
  543. inline constexpr auto is_unique = std::true_type{};
  544. template <typename T, typename... Rest>
  545. inline constexpr auto is_unique<T, Rest...> = std::bool_constant<
  546. (!std::is_same_v<T, Rest> && ...) && is_unique<Rest...>
  547. >{};
  548. #else
  549. template<typename...>
  550. struct is_unique : std::true_type {};
  551. template<typename T0, typename T1, typename... Rest>
  552. struct is_unique<T0, T1, Rest...> : std::integral_constant
  553. <bool,
  554. !std::is_same<T0, T1>::value
  555. && is_unique<T0, Rest...>::value
  556. && is_unique<T1, Rest...>::value
  557. > {
  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)
  782. TestInvokerAsMethod<C>( testAsMethod );
  783. }
  784. struct NameAndTags {
  785. NameAndTags(StringRef const &name_ = StringRef(), StringRef const &tags_ = StringRef()) noexcept;
  786. StringRef name;
  787. StringRef tags;
  788. };
  789. struct AutoReg : NonCopyable {
  790. AutoReg(ITestInvoker *invoker,
  791. SourceLineInfo const &lineInfo,
  792. StringRef const &classOrMethod,
  793. NameAndTags const &nameAndTags) noexcept;
  794. ~AutoReg();
  795. };
  796. } // end namespace Catch
  797. #if defined(CATCH_CONFIG_DISABLE)
  798. #define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( TestName, ... ) \
  799. static void TestName()
  800. #define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( TestName, ClassName, ... ) \
  801. namespace{ \
  802. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
  803. void test(); \
  804. }; \
  805. } \
  806. void TestName::test()
  807. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( TestName, TestFunc, Name, Tags, Signature, ... ) \
  808. INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature))
  809. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... ) \
  810. namespace{ \
  811. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
  812. INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
  813. } \
  814. } \
  815. INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))
  816. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  817. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \
  818. 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__ )
  819. #else
  820. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \
  821. 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__ ) )
  822. #endif
  823. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  824. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \
  825. 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__ )
  826. #else
  827. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \
  828. 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__ ) )
  829. #endif
  830. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  831. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \
  832. 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__ )
  833. #else
  834. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \
  835. 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__ ) )
  836. #endif
  837. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  838. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \
  839. 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__ )
  840. #else
  841. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \
  842. 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__ ) )
  843. #endif
  844. #endif
  845. ///////////////////////////////////////////////////////////////////////////////
  846. #define INTERNAL_CATCH_TESTCASE2(TestName, ...) \
  847. static void TestName(); \
  848. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  849. namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &TestName ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
  850. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  851. static void TestName()
  852. #define INTERNAL_CATCH_TESTCASE(...) \
  853. INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), __VA_ARGS__ )
  854. ///////////////////////////////////////////////////////////////////////////////
  855. #define INTERNAL_CATCH_METHOD_AS_TEST_CASE(QualifiedMethod, ...) \
  856. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  857. namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &QualifiedMethod ), CATCH_INTERNAL_LINEINFO, "&" #QualifiedMethod, Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
  858. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  859. ///////////////////////////////////////////////////////////////////////////////
  860. #define INTERNAL_CATCH_TEST_CASE_METHOD2(TestName, ClassName, ...)\
  861. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  862. namespace{ \
  863. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
  864. void test(); \
  865. }; \
  866. Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( Catch::makeTestInvoker( &TestName::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
  867. } \
  868. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  869. void TestName::test()
  870. #define INTERNAL_CATCH_TEST_CASE_METHOD(ClassName, ...) \
  871. INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, __VA_ARGS__ )
  872. ///////////////////////////////////////////////////////////////////////////////
  873. #define INTERNAL_CATCH_REGISTER_TESTCASE(Function, ...) \
  874. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  875. Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( Function ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
  876. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  877. ///////////////////////////////////////////////////////////////////////////////
  878. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_2(TestName, TestFunc, Name, Tags, Signature, ...)\
  879. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  880. CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
  881. INTERNAL_CATCH_DECLARE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
  882. namespace {\
  883. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\
  884. INTERNAL_CATCH_TYPE_GEN\
  885. INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
  886. INTERNAL_CATCH_NTTP_REG_GEN(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature))\
  887. template<typename...Types> \
  888. struct TestName{\
  889. TestName(){\
  890. int index = 0; \
  891. constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\
  892. using expander = int[];\
  893. (void)expander{(reg_test(Types{}, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++, 0)... };/* NOLINT */ \
  894. }\
  895. };\
  896. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
  897. TestName<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\
  898. return 0;\
  899. }();\
  900. }\
  901. }\
  902. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  903. CATCH_INTERNAL_UNSUPPRESS_ZERO_VARIADIC_WARNINGS \
  904. INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature))
  905. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  906. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
  907. 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__ )
  908. #else
  909. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
  910. 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__ ) )
  911. #endif
  912. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  913. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \
  914. 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__ )
  915. #else
  916. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \
  917. 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__ ) )
  918. #endif
  919. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(TestName, TestFuncName, Name, Tags, Signature, TmplTypes, TypesList) \
  920. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  921. CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
  922. template<typename TestType> static void TestFuncName(); \
  923. namespace {\
  924. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
  925. INTERNAL_CATCH_TYPE_GEN \
  926. INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature)) \
  927. template<typename... Types> \
  928. struct TestName { \
  929. void reg_tests() { \
  930. int index = 0; \
  931. using expander = int[]; \
  932. constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\
  933. constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\
  934. constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\
  935. (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 */\
  936. } \
  937. }; \
  938. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \
  939. using TestInit = decltype(create<TestName, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>(TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(INTERNAL_CATCH_REMOVE_PARENS(TypesList))>{})); \
  940. TestInit t; \
  941. t.reg_tests(); \
  942. return 0; \
  943. }(); \
  944. } \
  945. } \
  946. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  947. CATCH_INTERNAL_UNSUPPRESS_ZERO_VARIADIC_WARNINGS \
  948. template<typename TestType> \
  949. static void TestFuncName()
  950. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  951. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\
  952. 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__)
  953. #else
  954. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\
  955. 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__ ) )
  956. #endif
  957. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  958. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\
  959. 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__)
  960. #else
  961. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\
  962. 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__ ) )
  963. #endif
  964. #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2(TestName, TestFunc, Name, Tags, TmplList)\
  965. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  966. template<typename TestType> static void TestFunc(); \
  967. namespace {\
  968. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\
  969. INTERNAL_CATCH_TYPE_GEN\
  970. template<typename... Types> \
  971. struct TestName { \
  972. void reg_tests() { \
  973. int index = 0; \
  974. using expander = int[]; \
  975. (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 */\
  976. } \
  977. };\
  978. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \
  979. using TestInit = decltype(convert<TestName>(std::declval<TmplList>())); \
  980. TestInit t; \
  981. t.reg_tests(); \
  982. return 0; \
  983. }(); \
  984. }}\
  985. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  986. template<typename TestType> \
  987. static void TestFunc()
  988. #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(Name, Tags, TmplList) \
  989. 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 )
  990. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2(TestNameClass, TestName, ClassName, Name, Tags, Signature, ...) \
  991. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  992. CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
  993. namespace {\
  994. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \
  995. INTERNAL_CATCH_TYPE_GEN\
  996. INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
  997. INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
  998. INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))\
  999. template<typename...Types> \
  1000. struct TestNameClass{\
  1001. TestNameClass(){\
  1002. int index = 0; \
  1003. constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\
  1004. using expander = int[];\
  1005. (void)expander{(reg_test(Types{}, #ClassName, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++, 0)... };/* NOLINT */ \
  1006. }\
  1007. };\
  1008. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
  1009. TestNameClass<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\
  1010. return 0;\
  1011. }();\
  1012. }\
  1013. }\
  1014. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS\
  1015. CATCH_INTERNAL_UNSUPPRESS_ZERO_VARIADIC_WARNINGS\
  1016. INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))
  1017. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  1018. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD(ClassName, Name, Tags, ...) \
  1019. 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__ )
  1020. #else
  1021. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \
  1022. 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__ ) )
  1023. #endif
  1024. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  1025. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(ClassName, Name, Tags, Signature, ...) \
  1026. 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__ )
  1027. #else
  1028. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \
  1029. 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__ ) )
  1030. #endif
  1031. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2(TestNameClass, TestName, ClassName, Name, Tags, Signature, TmplTypes, TypesList)\
  1032. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  1033. CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
  1034. template<typename TestType> \
  1035. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \
  1036. void test();\
  1037. };\
  1038. namespace {\
  1039. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestNameClass) {\
  1040. INTERNAL_CATCH_TYPE_GEN \
  1041. INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
  1042. template<typename...Types>\
  1043. struct TestNameClass{\
  1044. void reg_tests(){\
  1045. int index = 0;\
  1046. using expander = int[];\
  1047. constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\
  1048. constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\
  1049. constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\
  1050. (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 */ \
  1051. }\
  1052. };\
  1053. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
  1054. using TestInit = decltype(create<TestNameClass, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>(TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(INTERNAL_CATCH_REMOVE_PARENS(TypesList))>{}));\
  1055. TestInit t;\
  1056. t.reg_tests();\
  1057. return 0;\
  1058. }(); \
  1059. }\
  1060. }\
  1061. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  1062. CATCH_INTERNAL_UNSUPPRESS_ZERO_VARIADIC_WARNINGS \
  1063. template<typename TestType> \
  1064. void TestName<TestType>::test()
  1065. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  1066. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(ClassName, Name, Tags, ...)\
  1067. 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__ )
  1068. #else
  1069. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\
  1070. 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__ ) )
  1071. #endif
  1072. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  1073. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(ClassName, Name, Tags, Signature, ...)\
  1074. 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__ )
  1075. #else
  1076. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\
  1077. 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__ ) )
  1078. #endif
  1079. #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2(TestNameClass, TestName, ClassName, Name, Tags, TmplList) \
  1080. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  1081. template<typename TestType> \
  1082. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \
  1083. void test();\
  1084. };\
  1085. namespace {\
  1086. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \
  1087. INTERNAL_CATCH_TYPE_GEN\
  1088. template<typename...Types>\
  1089. struct TestNameClass{\
  1090. void reg_tests(){\
  1091. int index = 0;\
  1092. using expander = int[];\
  1093. (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 */ \
  1094. }\
  1095. };\
  1096. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
  1097. using TestInit = decltype(convert<TestNameClass>(std::declval<TmplList>()));\
  1098. TestInit t;\
  1099. t.reg_tests();\
  1100. return 0;\
  1101. }(); \
  1102. }}\
  1103. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  1104. template<typename TestType> \
  1105. void TestName<TestType>::test()
  1106. #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD(ClassName, Name, Tags, TmplList) \
  1107. 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 )
  1108. // end catch_test_registry.h
  1109. // start catch_capture.hpp
  1110. // start catch_assertionhandler.h
  1111. // start catch_assertioninfo.h
  1112. // start catch_result_type.h
  1113. namespace Catch {
  1114. // ResultWas::OfType enum
  1115. struct ResultWas {
  1116. enum OfType {
  1117. Unknown = -1,
  1118. Ok = 0,
  1119. Info = 1,
  1120. Warning = 2,
  1121. FailureBit = 0x10,
  1122. ExpressionFailed = FailureBit | 1,
  1123. ExplicitFailure = FailureBit | 2,
  1124. Exception = 0x100 | FailureBit,
  1125. ThrewException = Exception | 1,
  1126. DidntThrowException = Exception | 2,
  1127. FatalErrorCondition = 0x200 | FailureBit
  1128. };
  1129. };
  1130. bool isOk(ResultWas::OfType resultType);
  1131. bool isJustInfo(int flags);
  1132. // ResultDisposition::Flags enum
  1133. struct ResultDisposition {
  1134. enum Flags {
  1135. Normal = 0x01,
  1136. ContinueOnFailure = 0x02, // Failures fail test, but execution continues
  1137. FalseTest = 0x04, // Prefix expression with !
  1138. SuppressFail = 0x08 // Failures are reported but do not fail the test
  1139. };
  1140. };
  1141. ResultDisposition::Flags operator|(ResultDisposition::Flags lhs, ResultDisposition::Flags rhs);
  1142. bool shouldContinueOnFailure(int flags);
  1143. inline bool isFalseTest(int flags) { return (flags & ResultDisposition::FalseTest) != 0; }
  1144. bool shouldSuppressFailure(int flags);
  1145. } // end namespace Catch
  1146. // end catch_result_type.h
  1147. namespace Catch {
  1148. struct AssertionInfo {
  1149. StringRef macroName;
  1150. SourceLineInfo lineInfo;
  1151. StringRef capturedExpression;
  1152. ResultDisposition::Flags resultDisposition;
  1153. // We want to delete this constructor but a compiler bug in 4.8 means
  1154. // the struct is then treated as non-aggregate
  1155. //AssertionInfo() = delete;
  1156. };
  1157. } // end namespace Catch
  1158. // end catch_assertioninfo.h
  1159. // start catch_decomposer.h
  1160. // start catch_tostring.h
  1161. #include <vector>
  1162. #include <cstddef>
  1163. #include <type_traits>
  1164. #include <string>
  1165. // start catch_stream.h
  1166. #include <iosfwd>
  1167. #include <cstddef>
  1168. #include <ostream>
  1169. namespace Catch {
  1170. std::ostream &cout();
  1171. std::ostream &cerr();
  1172. std::ostream &clog();
  1173. class StringRef;
  1174. struct IStream {
  1175. virtual ~IStream();
  1176. virtual std::ostream &stream() const = 0;
  1177. };
  1178. auto makeStream(StringRef const &filename) -> IStream const *;
  1179. class ReusableStringStream {
  1180. std::size_t m_index;
  1181. std::ostream *m_oss;
  1182. public:
  1183. ReusableStringStream();
  1184. ~ReusableStringStream();
  1185. auto str() const -> std::string;
  1186. template<typename T>
  1187. auto operator<<(T const &value) -> ReusableStringStream & {
  1188. *m_oss << value;
  1189. return *this;
  1190. }
  1191. auto get() -> std::ostream & { return *m_oss; }
  1192. };
  1193. }
  1194. // end catch_stream.h
  1195. // start catch_interfaces_enum_values_registry.h
  1196. #include <vector>
  1197. namespace Catch {
  1198. namespace Detail {
  1199. struct EnumInfo {
  1200. StringRef m_name;
  1201. std::vector<std::pair<int, std::string>> m_values;
  1202. ~EnumInfo();
  1203. StringRef lookup(int value) const;
  1204. };
  1205. } // namespace Detail
  1206. struct IMutableEnumValuesRegistry {
  1207. virtual ~IMutableEnumValuesRegistry();
  1208. virtual Detail::EnumInfo const &registerEnum(StringRef enumName,
  1209. StringRef allEnums,
  1210. std::vector<int> const &values) = 0;
  1211. template<typename E>
  1212. Detail::EnumInfo const &registerEnum(StringRef enumName,
  1213. StringRef allEnums,
  1214. std::initializer_list<E> values) {
  1215. std::vector<int> intValues;
  1216. intValues.reserve(values.size());
  1217. for (auto enumValue : values)
  1218. intValues.push_back(static_cast<int>( enumValue ));
  1219. return registerEnum(enumName, allEnums, intValues);
  1220. }
  1221. };
  1222. } // Catch
  1223. // end catch_interfaces_enum_values_registry.h
  1224. #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  1225. #include <string_view>
  1226. #endif
  1227. #ifdef __OBJC__
  1228. // start catch_objc_arc.hpp
  1229. #import <Foundation/Foundation.h>
  1230. #ifdef __has_feature
  1231. #define CATCH_ARC_ENABLED __has_feature(objc_arc)
  1232. #else
  1233. #define CATCH_ARC_ENABLED 0
  1234. #endif
  1235. void arcSafeRelease( NSObject* obj );
  1236. id performOptionalSelector( id obj, SEL sel );
  1237. #if !CATCH_ARC_ENABLED
  1238. inline void arcSafeRelease( NSObject* obj ) {
  1239. [obj release];
  1240. }
  1241. inline id performOptionalSelector( id obj, SEL sel ) {
  1242. if( [obj respondsToSelector: sel] )
  1243. return [obj performSelector: sel];
  1244. return nil;
  1245. }
  1246. #define CATCH_UNSAFE_UNRETAINED
  1247. #define CATCH_ARC_STRONG
  1248. #else
  1249. inline void arcSafeRelease( NSObject* ){}
  1250. inline id performOptionalSelector( id obj, SEL sel ) {
  1251. #ifdef __clang__
  1252. #pragma clang diagnostic push
  1253. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  1254. #endif
  1255. if( [obj respondsToSelector: sel] )
  1256. return [obj performSelector: sel];
  1257. #ifdef __clang__
  1258. #pragma clang diagnostic pop
  1259. #endif
  1260. return nil;
  1261. }
  1262. #define CATCH_UNSAFE_UNRETAINED __unsafe_unretained
  1263. #define CATCH_ARC_STRONG __strong
  1264. #endif
  1265. // end catch_objc_arc.hpp
  1266. #endif
  1267. #ifdef _MSC_VER
  1268. #pragma warning(push)
  1269. #pragma warning(disable:4180) // We attempt to stream a function (address) by const&, which MSVC complains about but is harmless
  1270. #endif
  1271. namespace Catch {
  1272. namespace Detail {
  1273. extern const std::string unprintableString;
  1274. std::string rawMemoryToString(const void *object, std::size_t size);
  1275. template<typename T>
  1276. std::string rawMemoryToString(const T &object) {
  1277. return rawMemoryToString(&object, sizeof(object));
  1278. }
  1279. template<typename T>
  1280. class IsStreamInsertable {
  1281. template<typename SS, typename TT>
  1282. static auto test(int)
  1283. -> decltype(std::declval<SS &>() << std::declval<TT>(), std::true_type());
  1284. template<typename, typename>
  1285. static auto test(...) -> std::false_type;
  1286. public:
  1287. static const bool value = decltype(test<std::ostream, const T &>(0))::value;
  1288. };
  1289. template<typename E>
  1290. std::string convertUnknownEnumToString(E e);
  1291. template<typename T>
  1292. typename std::enable_if<
  1293. !std::is_enum<T>::value && !std::is_base_of<std::exception, T>::value,
  1294. std::string>::type convertUnstreamable(T const &) {
  1295. return Detail::unprintableString;
  1296. }
  1297. template<typename T>
  1298. typename std::enable_if<
  1299. !std::is_enum<T>::value && std::is_base_of<std::exception, T>::value,
  1300. std::string>::type convertUnstreamable(T const &ex) {
  1301. return ex.what();
  1302. }
  1303. template<typename T>
  1304. typename std::enable_if<
  1305. std::is_enum<T>::value, std::string>::type convertUnstreamable(T const &value) {
  1306. return convertUnknownEnumToString(value);
  1307. }
  1308. #if defined(_MANAGED)
  1309. //! Convert a CLR string to a utf8 std::string
  1310. template<typename T>
  1311. std::string clrReferenceToString( T^ ref ) {
  1312. if (ref == nullptr)
  1313. return std::string("null");
  1314. auto bytes = System::Text::Encoding::UTF8->GetBytes(ref->ToString());
  1315. cli::pin_ptr<System::Byte> p = &bytes[0];
  1316. return std::string(reinterpret_cast<char const *>(p), bytes->Length);
  1317. }
  1318. #endif
  1319. } // namespace Detail
  1320. // If we decide for C++14, change these to enable_if_ts
  1321. template<typename T, typename = void>
  1322. struct StringMaker {
  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. ReusableStringStream rss;
  1328. // NB: call using the function-like syntax to avoid ambiguity with
  1329. // user-defined templated operator<< under clang.
  1330. rss.operator<<(value);
  1331. return rss.str();
  1332. }
  1333. template<typename Fake = T>
  1334. static
  1335. typename std::enable_if<!::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
  1336. convert(const Fake &value) {
  1337. #if !defined(CATCH_CONFIG_FALLBACK_STRINGIFIER)
  1338. return Detail::convertUnstreamable(value);
  1339. #else
  1340. return CATCH_CONFIG_FALLBACK_STRINGIFIER(value);
  1341. #endif
  1342. }
  1343. };
  1344. namespace Detail {
  1345. // This function dispatches all stringification requests inside of Catch.
  1346. // Should be preferably called fully qualified, like ::Catch::Detail::stringify
  1347. template<typename T>
  1348. std::string stringify(const T &e) {
  1349. return ::Catch::StringMaker<typename std::remove_cv<typename std::remove_reference<T>::type>::type>::convert(
  1350. e);
  1351. }
  1352. template<typename E>
  1353. std::string convertUnknownEnumToString(E e) {
  1354. return ::Catch::Detail::stringify(static_cast<typename std::underlying_type<E>::type>(e));
  1355. }
  1356. #if defined(_MANAGED)
  1357. template <typename T>
  1358. std::string stringify( T^ e ) {
  1359. return ::Catch::StringMaker<T^>::convert(e);
  1360. }
  1361. #endif
  1362. } // namespace Detail
  1363. // Some predefined specializations
  1364. template<>
  1365. struct StringMaker<std::string> {
  1366. static std::string convert(const std::string &str);
  1367. };
  1368. #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  1369. template<>
  1370. struct StringMaker<std::string_view> {
  1371. static std::string convert(std::string_view str);
  1372. };
  1373. #endif
  1374. template<>
  1375. struct StringMaker<char const *> {
  1376. static std::string convert(char const *str);
  1377. };
  1378. template<>
  1379. struct StringMaker<char *> {
  1380. static std::string convert(char *str);
  1381. };
  1382. #ifdef CATCH_CONFIG_WCHAR
  1383. template<>
  1384. struct StringMaker<std::wstring> {
  1385. static std::string convert(const std::wstring &wstr);
  1386. };
  1387. # ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  1388. template<>
  1389. struct StringMaker<std::wstring_view> {
  1390. static std::string convert(std::wstring_view str);
  1391. };
  1392. # endif
  1393. template<>
  1394. struct StringMaker<wchar_t const *> {
  1395. static std::string convert(wchar_t const *str);
  1396. };
  1397. template<>
  1398. struct StringMaker<wchar_t *> {
  1399. static std::string convert(wchar_t *str);
  1400. };
  1401. #endif
  1402. // TBD: Should we use `strnlen` to ensure that we don't go out of the buffer,
  1403. // while keeping string semantics?
  1404. template<int SZ>
  1405. struct StringMaker<char[SZ]> {
  1406. static std::string convert(char const *str) {
  1407. return ::Catch::Detail::stringify(std::string{str});
  1408. }
  1409. };
  1410. template<int SZ>
  1411. struct StringMaker<signed char[SZ]> {
  1412. static std::string convert(signed char const *str) {
  1413. return ::Catch::Detail::stringify(std::string{reinterpret_cast<char const *>(str)});
  1414. }
  1415. };
  1416. template<int SZ>
  1417. struct StringMaker<unsigned char[SZ]> {
  1418. static std::string convert(unsigned char const *str) {
  1419. return ::Catch::Detail::stringify(std::string{reinterpret_cast<char const *>(str)});
  1420. }
  1421. };
  1422. #if defined(CATCH_CONFIG_CPP17_BYTE)
  1423. template<>
  1424. struct StringMaker<std::byte> {
  1425. static std::string convert(std::byte value);
  1426. };
  1427. #endif // defined(CATCH_CONFIG_CPP17_BYTE)
  1428. template<>
  1429. struct StringMaker<int> {
  1430. static std::string convert(int value);
  1431. };
  1432. template<>
  1433. struct StringMaker<long> {
  1434. static std::string convert(long value);
  1435. };
  1436. template<>
  1437. struct StringMaker<long long> {
  1438. static std::string convert(long long value);
  1439. };
  1440. template<>
  1441. struct StringMaker<unsigned int> {
  1442. static std::string convert(unsigned int value);
  1443. };
  1444. template<>
  1445. struct StringMaker<unsigned long> {
  1446. static std::string convert(unsigned long value);
  1447. };
  1448. template<>
  1449. struct StringMaker<unsigned long long> {
  1450. static std::string convert(unsigned long long value);
  1451. };
  1452. template<>
  1453. struct StringMaker<bool> {
  1454. static std::string convert(bool b);
  1455. };
  1456. template<>
  1457. struct StringMaker<char> {
  1458. static std::string convert(char c);
  1459. };
  1460. template<>
  1461. struct StringMaker<signed char> {
  1462. static std::string convert(signed char c);
  1463. };
  1464. template<>
  1465. struct StringMaker<unsigned char> {
  1466. static std::string convert(unsigned char c);
  1467. };
  1468. template<>
  1469. struct StringMaker<std::nullptr_t> {
  1470. static std::string convert(std::nullptr_t);
  1471. };
  1472. template<>
  1473. struct StringMaker<float> {
  1474. static std::string convert(float value);
  1475. static int precision;
  1476. };
  1477. template<>
  1478. struct StringMaker<double> {
  1479. static std::string convert(double value);
  1480. static int precision;
  1481. };
  1482. template<typename T>
  1483. struct StringMaker<T *> {
  1484. template<typename U>
  1485. static std::string convert(U *p) {
  1486. if (p) {
  1487. return ::Catch::Detail::rawMemoryToString(p);
  1488. } else {
  1489. return "nullptr";
  1490. }
  1491. }
  1492. };
  1493. template<typename R, typename C>
  1494. struct StringMaker<R C::*> {
  1495. static std::string convert(R C::* p) {
  1496. if (p) {
  1497. return ::Catch::Detail::rawMemoryToString(p);
  1498. } else {
  1499. return "nullptr";
  1500. }
  1501. }
  1502. };
  1503. #if defined(_MANAGED)
  1504. template <typename T>
  1505. struct StringMaker<T^> {
  1506. static std::string convert( T^ ref ) {
  1507. return ::Catch::Detail::clrReferenceToString(ref);
  1508. }
  1509. };
  1510. #endif
  1511. namespace Detail {
  1512. template<typename InputIterator>
  1513. std::string rangeToString(InputIterator first, InputIterator last) {
  1514. ReusableStringStream rss;
  1515. rss << "{ ";
  1516. if (first != last) {
  1517. rss << ::Catch::Detail::stringify(*first);
  1518. for (++first; first != last; ++first)
  1519. rss << ", " << ::Catch::Detail::stringify(*first);
  1520. }
  1521. rss << " }";
  1522. return rss.str();
  1523. }
  1524. }
  1525. #ifdef __OBJC__
  1526. template<>
  1527. struct StringMaker<NSString*> {
  1528. static std::string convert(NSString * nsstring) {
  1529. if (!nsstring)
  1530. return "nil";
  1531. return std::string("@") + [nsstring UTF8String];
  1532. }
  1533. };
  1534. template<>
  1535. struct StringMaker<NSObject*> {
  1536. static std::string convert(NSObject* nsObject) {
  1537. return ::Catch::Detail::stringify([nsObject description]);
  1538. }
  1539. };
  1540. namespace Detail {
  1541. inline std::string stringify( NSString* nsstring ) {
  1542. return StringMaker<NSString*>::convert( nsstring );
  1543. }
  1544. } // namespace Detail
  1545. #endif // __OBJC__
  1546. } // namespace Catch
  1547. //////////////////////////////////////////////////////
  1548. // Separate std-lib types stringification, so it can be selectively enabled
  1549. // This means that we do not bring in
  1550. #if defined(CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS)
  1551. # define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
  1552. # define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
  1553. # define CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
  1554. # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  1555. # define CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
  1556. #endif
  1557. // Separate std::pair specialization
  1558. #if defined(CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER)
  1559. #include <utility>
  1560. namespace Catch {
  1561. template<typename T1, typename T2>
  1562. struct StringMaker<std::pair<T1, T2> > {
  1563. static std::string convert(const std::pair<T1, T2>& pair) {
  1564. ReusableStringStream rss;
  1565. rss << "{ "
  1566. << ::Catch::Detail::stringify(pair.first)
  1567. << ", "
  1568. << ::Catch::Detail::stringify(pair.second)
  1569. << " }";
  1570. return rss.str();
  1571. }
  1572. };
  1573. }
  1574. #endif // CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
  1575. #if defined(CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_OPTIONAL)
  1576. #include <optional>
  1577. namespace Catch {
  1578. template<typename T>
  1579. struct StringMaker<std::optional<T> > {
  1580. static std::string convert(const std::optional<T>& optional) {
  1581. ReusableStringStream rss;
  1582. if (optional.has_value()) {
  1583. rss << ::Catch::Detail::stringify(*optional);
  1584. } else {
  1585. rss << "{ }";
  1586. }
  1587. return rss.str();
  1588. }
  1589. };
  1590. }
  1591. #endif // CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
  1592. // Separate std::tuple specialization
  1593. #if defined(CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER)
  1594. #include <tuple>
  1595. namespace Catch {
  1596. namespace Detail {
  1597. template<
  1598. typename Tuple,
  1599. std::size_t N = 0,
  1600. bool = (N < std::tuple_size<Tuple>::value)
  1601. >
  1602. struct TupleElementPrinter {
  1603. static void print(const Tuple& tuple, std::ostream& os) {
  1604. os << (N ? ", " : " ")
  1605. << ::Catch::Detail::stringify(std::get<N>(tuple));
  1606. TupleElementPrinter<Tuple, N + 1>::print(tuple, os);
  1607. }
  1608. };
  1609. template<
  1610. typename Tuple,
  1611. std::size_t N
  1612. >
  1613. struct TupleElementPrinter<Tuple, N, false> {
  1614. static void print(const Tuple&, std::ostream&) {}
  1615. };
  1616. }
  1617. template<typename ...Types>
  1618. struct StringMaker<std::tuple<Types...>> {
  1619. static std::string convert(const std::tuple<Types...>& tuple) {
  1620. ReusableStringStream rss;
  1621. rss << '{';
  1622. Detail::TupleElementPrinter<std::tuple<Types...>>::print(tuple, rss.get());
  1623. rss << " }";
  1624. return rss.str();
  1625. }
  1626. };
  1627. }
  1628. #endif // CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
  1629. #if defined(CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_VARIANT)
  1630. #include <variant>
  1631. namespace Catch {
  1632. template<>
  1633. struct StringMaker<std::monostate> {
  1634. static std::string convert(const std::monostate&) {
  1635. return "{ }";
  1636. }
  1637. };
  1638. template<typename... Elements>
  1639. struct StringMaker<std::variant<Elements...>> {
  1640. static std::string convert(const std::variant<Elements...>& variant) {
  1641. if (variant.valueless_by_exception()) {
  1642. return "{valueless variant}";
  1643. } else {
  1644. return std::visit(
  1645. [](const auto& value) {
  1646. return ::Catch::Detail::stringify(value);
  1647. },
  1648. variant
  1649. );
  1650. }
  1651. }
  1652. };
  1653. }
  1654. #endif // CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
  1655. namespace Catch {
  1656. struct not_this_one {}; // Tag type for detecting which begin/ end are being selected
  1657. // Import begin/ end from std here so they are considered alongside the fallback (...) overloads in this namespace
  1658. using std::begin;
  1659. using std::end;
  1660. not_this_one begin(...);
  1661. not_this_one end(...);
  1662. template<typename T>
  1663. struct is_range {
  1664. static const bool value =
  1665. !std::is_same<decltype(begin(std::declval<T>())), not_this_one>::value &&
  1666. !std::is_same<decltype(end(std::declval<T>())), not_this_one>::value;
  1667. };
  1668. #if defined(_MANAGED) // Managed types are never ranges
  1669. template <typename T>
  1670. struct is_range<T^> {
  1671. static const bool value = false;
  1672. };
  1673. #endif
  1674. template<typename Range>
  1675. std::string rangeToString(Range const &range) {
  1676. return ::Catch::Detail::rangeToString(begin(range), end(range));
  1677. }
  1678. // Handle vector<bool> specially
  1679. template<typename Allocator>
  1680. std::string rangeToString(std::vector<bool, Allocator> const &v) {
  1681. ReusableStringStream rss;
  1682. rss << "{ ";
  1683. bool first = true;
  1684. for (bool b : v) {
  1685. if (first)
  1686. first = false;
  1687. else
  1688. rss << ", ";
  1689. rss << ::Catch::Detail::stringify(b);
  1690. }
  1691. rss << " }";
  1692. return rss.str();
  1693. }
  1694. template<typename R>
  1695. struct StringMaker<R,
  1696. typename std::enable_if<is_range<R>::value
  1697. && !::Catch::Detail::IsStreamInsertable<R>::value>::type> {
  1698. static std::string convert(R const &range) {
  1699. return rangeToString(range);
  1700. }
  1701. };
  1702. template<typename T, int SZ>
  1703. struct StringMaker<T[SZ]> {
  1704. static std::string convert(T const(&arr)[SZ]) {
  1705. return rangeToString(arr);
  1706. }
  1707. };
  1708. } // namespace Catch
  1709. // Separate std::chrono::duration specialization
  1710. #if defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  1711. #include <ctime>
  1712. #include <ratio>
  1713. #include <chrono>
  1714. namespace Catch {
  1715. template <class Ratio>
  1716. struct ratio_string {
  1717. static std::string symbol();
  1718. };
  1719. template <class Ratio>
  1720. std::string ratio_string<Ratio>::symbol() {
  1721. Catch::ReusableStringStream rss;
  1722. rss << '[' << Ratio::num << '/'
  1723. << Ratio::den << ']';
  1724. return rss.str();
  1725. }
  1726. template <>
  1727. struct ratio_string<std::atto> {
  1728. static std::string symbol();
  1729. };
  1730. template <>
  1731. struct ratio_string<std::femto> {
  1732. static std::string symbol();
  1733. };
  1734. template <>
  1735. struct ratio_string<std::pico> {
  1736. static std::string symbol();
  1737. };
  1738. template <>
  1739. struct ratio_string<std::nano> {
  1740. static std::string symbol();
  1741. };
  1742. template <>
  1743. struct ratio_string<std::micro> {
  1744. static std::string symbol();
  1745. };
  1746. template <>
  1747. struct ratio_string<std::milli> {
  1748. static std::string symbol();
  1749. };
  1750. ////////////
  1751. // std::chrono::duration specializations
  1752. template<typename Value, typename Ratio>
  1753. struct StringMaker<std::chrono::duration<Value, Ratio>> {
  1754. static std::string convert(std::chrono::duration<Value, Ratio> const& duration) {
  1755. ReusableStringStream rss;
  1756. rss << duration.count() << ' ' << ratio_string<Ratio>::symbol() << 's';
  1757. return rss.str();
  1758. }
  1759. };
  1760. template<typename Value>
  1761. struct StringMaker<std::chrono::duration<Value, std::ratio<1>>> {
  1762. static std::string convert(std::chrono::duration<Value, std::ratio<1>> const& duration) {
  1763. ReusableStringStream rss;
  1764. rss << duration.count() << " s";
  1765. return rss.str();
  1766. }
  1767. };
  1768. template<typename Value>
  1769. struct StringMaker<std::chrono::duration<Value, std::ratio<60>>> {
  1770. static std::string convert(std::chrono::duration<Value, std::ratio<60>> const& duration) {
  1771. ReusableStringStream rss;
  1772. rss << duration.count() << " m";
  1773. return rss.str();
  1774. }
  1775. };
  1776. template<typename Value>
  1777. struct StringMaker<std::chrono::duration<Value, std::ratio<3600>>> {
  1778. static std::string convert(std::chrono::duration<Value, std::ratio<3600>> const& duration) {
  1779. ReusableStringStream rss;
  1780. rss << duration.count() << " h";
  1781. return rss.str();
  1782. }
  1783. };
  1784. ////////////
  1785. // std::chrono::time_point specialization
  1786. // Generic time_point cannot be specialized, only std::chrono::time_point<system_clock>
  1787. template<typename Clock, typename Duration>
  1788. struct StringMaker<std::chrono::time_point<Clock, Duration>> {
  1789. static std::string convert(std::chrono::time_point<Clock, Duration> const& time_point) {
  1790. return ::Catch::Detail::stringify(time_point.time_since_epoch()) + " since epoch";
  1791. }
  1792. };
  1793. // std::chrono::time_point<system_clock> specialization
  1794. template<typename Duration>
  1795. struct StringMaker<std::chrono::time_point<std::chrono::system_clock, Duration>> {
  1796. static std::string convert(std::chrono::time_point<std::chrono::system_clock, Duration> const& time_point) {
  1797. auto converted = std::chrono::system_clock::to_time_t(time_point);
  1798. #ifdef _MSC_VER
  1799. std::tm timeInfo = {};
  1800. gmtime_s(&timeInfo, &converted);
  1801. #else
  1802. std::tm* timeInfo = std::gmtime(&converted);
  1803. #endif
  1804. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  1805. char timeStamp[timeStampSize];
  1806. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  1807. #ifdef _MSC_VER
  1808. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  1809. #else
  1810. std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
  1811. #endif
  1812. return std::string(timeStamp);
  1813. }
  1814. };
  1815. }
  1816. #endif // CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  1817. #define INTERNAL_CATCH_REGISTER_ENUM(enumName, ...) \
  1818. namespace Catch { \
  1819. template<> struct StringMaker<enumName> { \
  1820. static std::string convert( enumName value ) { \
  1821. static const auto& enumInfo = ::Catch::getMutableRegistryHub().getMutableEnumValuesRegistry().registerEnum( #enumName, #__VA_ARGS__, { __VA_ARGS__ } ); \
  1822. return enumInfo.lookup( static_cast<int>( value ) ); \
  1823. } \
  1824. }; \
  1825. }
  1826. #define CATCH_REGISTER_ENUM(enumName, ...) INTERNAL_CATCH_REGISTER_ENUM( enumName, __VA_ARGS__ )
  1827. #ifdef _MSC_VER
  1828. #pragma warning(pop)
  1829. #endif
  1830. // end catch_tostring.h
  1831. #include <iosfwd>
  1832. #ifdef _MSC_VER
  1833. #pragma warning(push)
  1834. #pragma warning(disable:4389) // '==' : signed/unsigned mismatch
  1835. #pragma warning(disable:4018) // more "signed/unsigned mismatch"
  1836. #pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform)
  1837. #pragma warning(disable:4180) // qualifier applied to function type has no meaning
  1838. #pragma warning(disable:4800) // Forcing result to true or false
  1839. #endif
  1840. namespace Catch {
  1841. struct ITransientExpression {
  1842. auto isBinaryExpression() const -> bool { return m_isBinaryExpression; }
  1843. auto getResult() const -> bool { return m_result; }
  1844. virtual void streamReconstructedExpression(std::ostream &os) const = 0;
  1845. ITransientExpression(bool isBinaryExpression, bool result)
  1846. : m_isBinaryExpression(isBinaryExpression),
  1847. m_result(result) {}
  1848. // We don't actually need a virtual destructor, but many static analysers
  1849. // complain if it's not here :-(
  1850. virtual ~ITransientExpression();
  1851. bool m_isBinaryExpression;
  1852. bool m_result;
  1853. };
  1854. void formatReconstructedExpression(std::ostream &os,
  1855. std::string const &lhs,
  1856. StringRef op,
  1857. std::string const &rhs);
  1858. template<typename LhsT, typename RhsT>
  1859. class BinaryExpr : public ITransientExpression {
  1860. LhsT m_lhs;
  1861. StringRef m_op;
  1862. RhsT m_rhs;
  1863. void streamReconstructedExpression(std::ostream &os) const override {
  1864. formatReconstructedExpression
  1865. (os, Catch::Detail::stringify(m_lhs), m_op, Catch::Detail::stringify(m_rhs));
  1866. }
  1867. public:
  1868. BinaryExpr(bool comparisonResult, LhsT lhs, StringRef op, RhsT rhs)
  1869. : ITransientExpression{true, comparisonResult},
  1870. m_lhs(lhs),
  1871. m_op(op),
  1872. m_rhs(rhs) {}
  1873. template<typename T>
  1874. auto operator&&(T) const -> BinaryExpr<LhsT, RhsT const &> const {
  1875. static_assert(always_false<T>::value,
  1876. "chained comparisons are not supported inside assertions, "
  1877. "wrap the expression inside parentheses, or decompose it");
  1878. }
  1879. template<typename T>
  1880. auto operator||(T) const -> BinaryExpr<LhsT, RhsT const &> const {
  1881. static_assert(always_false<T>::value,
  1882. "chained comparisons are not supported inside assertions, "
  1883. "wrap the expression inside parentheses, or decompose it");
  1884. }
  1885. template<typename T>
  1886. auto operator==(T) const -> BinaryExpr<LhsT, RhsT const &> const {
  1887. static_assert(always_false<T>::value,
  1888. "chained comparisons are not supported inside assertions, "
  1889. "wrap the expression inside parentheses, or decompose it");
  1890. }
  1891. template<typename T>
  1892. auto operator!=(T) const -> BinaryExpr<LhsT, RhsT const &> const {
  1893. static_assert(always_false<T>::value,
  1894. "chained comparisons are not supported inside assertions, "
  1895. "wrap the expression inside parentheses, or decompose it");
  1896. }
  1897. template<typename T>
  1898. auto operator>(T) const -> BinaryExpr<LhsT, RhsT const &> const {
  1899. static_assert(always_false<T>::value,
  1900. "chained comparisons are not supported inside assertions, "
  1901. "wrap the expression inside parentheses, or decompose it");
  1902. }
  1903. template<typename T>
  1904. auto operator<(T) const -> BinaryExpr<LhsT, RhsT const &> const {
  1905. static_assert(always_false<T>::value,
  1906. "chained comparisons are not supported inside assertions, "
  1907. "wrap the expression inside parentheses, or decompose it");
  1908. }
  1909. template<typename T>
  1910. auto operator>=(T) const -> BinaryExpr<LhsT, RhsT const &> const {
  1911. static_assert(always_false<T>::value,
  1912. "chained comparisons are not supported inside assertions, "
  1913. "wrap the expression inside parentheses, or decompose it");
  1914. }
  1915. template<typename T>
  1916. auto operator<=(T) const -> BinaryExpr<LhsT, RhsT const &> const {
  1917. static_assert(always_false<T>::value,
  1918. "chained comparisons are not supported inside assertions, "
  1919. "wrap the expression inside parentheses, or decompose it");
  1920. }
  1921. };
  1922. template<typename LhsT>
  1923. class UnaryExpr : public ITransientExpression {
  1924. LhsT m_lhs;
  1925. void streamReconstructedExpression(std::ostream &os) const override {
  1926. os << Catch::Detail::stringify(m_lhs);
  1927. }
  1928. public:
  1929. explicit UnaryExpr(LhsT lhs)
  1930. : ITransientExpression{false, static_cast<bool>(lhs)},
  1931. m_lhs(lhs) {}
  1932. };
  1933. // Specialised comparison functions to handle equality comparisons between ints and pointers (NULL deduces as an int)
  1934. template<typename LhsT, typename RhsT>
  1935. auto compareEqual(LhsT const &lhs, RhsT const &rhs) -> bool {
  1936. return static_cast<bool>(lhs == rhs);
  1937. }
  1938. template<typename T>
  1939. auto compareEqual(T *const &lhs, int rhs) -> bool {
  1940. return lhs == reinterpret_cast<void const *>( rhs );
  1941. }
  1942. template<typename T>
  1943. auto compareEqual(T *const &lhs, long rhs) -> bool {
  1944. return lhs == reinterpret_cast<void const *>( rhs );
  1945. }
  1946. template<typename T>
  1947. auto compareEqual(int lhs, T *const &rhs) -> bool {
  1948. return reinterpret_cast<void const *>( lhs ) == rhs;
  1949. }
  1950. template<typename T>
  1951. auto compareEqual(long lhs, T *const &rhs) -> bool {
  1952. return reinterpret_cast<void const *>( lhs ) == rhs;
  1953. }
  1954. template<typename LhsT, typename RhsT>
  1955. auto compareNotEqual(LhsT const &lhs, RhsT &&rhs) -> bool { return static_cast<bool>(lhs != rhs); }
  1956. template<typename T>
  1957. auto compareNotEqual(T *const &lhs, int rhs) -> bool {
  1958. return lhs != reinterpret_cast<void const *>( rhs );
  1959. }
  1960. template<typename T>
  1961. auto compareNotEqual(T *const &lhs, long rhs) -> bool {
  1962. return lhs != reinterpret_cast<void const *>( rhs );
  1963. }
  1964. template<typename T>
  1965. auto compareNotEqual(int lhs, T *const &rhs) -> bool {
  1966. return reinterpret_cast<void const *>( lhs ) != rhs;
  1967. }
  1968. template<typename T>
  1969. auto compareNotEqual(long lhs, T *const &rhs) -> bool {
  1970. return reinterpret_cast<void const *>( lhs ) != rhs;
  1971. }
  1972. template<typename LhsT>
  1973. class ExprLhs {
  1974. LhsT m_lhs;
  1975. public:
  1976. explicit ExprLhs(LhsT lhs) : m_lhs(lhs) {}
  1977. template<typename RhsT>
  1978. auto operator==(RhsT const &rhs) -> BinaryExpr<LhsT, RhsT const &> const {
  1979. return {compareEqual(m_lhs, rhs), m_lhs, "==", rhs};
  1980. }
  1981. auto operator==(bool rhs) -> BinaryExpr<LhsT, bool> const {
  1982. return {m_lhs == rhs, m_lhs, "==", rhs};
  1983. }
  1984. template<typename RhsT>
  1985. auto operator!=(RhsT const &rhs) -> BinaryExpr<LhsT, RhsT const &> const {
  1986. return {compareNotEqual(m_lhs, rhs), m_lhs, "!=", rhs};
  1987. }
  1988. auto operator!=(bool rhs) -> BinaryExpr<LhsT, bool> const {
  1989. return {m_lhs != rhs, m_lhs, "!=", rhs};
  1990. }
  1991. template<typename RhsT>
  1992. auto operator>(RhsT const &rhs) -> BinaryExpr<LhsT, RhsT const &> const {
  1993. return {static_cast<bool>(m_lhs > rhs), m_lhs, ">", rhs};
  1994. }
  1995. template<typename RhsT>
  1996. auto operator<(RhsT const &rhs) -> BinaryExpr<LhsT, RhsT const &> const {
  1997. return {static_cast<bool>(m_lhs < rhs), m_lhs, "<", rhs};
  1998. }
  1999. template<typename RhsT>
  2000. auto operator>=(RhsT const &rhs) -> BinaryExpr<LhsT, RhsT const &> const {
  2001. return {static_cast<bool>(m_lhs >= rhs), m_lhs, ">=", rhs};
  2002. }
  2003. template<typename RhsT>
  2004. auto operator<=(RhsT const &rhs) -> BinaryExpr<LhsT, RhsT const &> const {
  2005. return {static_cast<bool>(m_lhs <= rhs), m_lhs, "<=", rhs};
  2006. }
  2007. template<typename RhsT>
  2008. auto operator&&(RhsT const &) -> BinaryExpr<LhsT, RhsT const &> const {
  2009. static_assert(always_false<RhsT>::value,
  2010. "operator&& is not supported inside assertions, "
  2011. "wrap the expression inside parentheses, or decompose it");
  2012. }
  2013. template<typename RhsT>
  2014. auto operator||(RhsT const &) -> BinaryExpr<LhsT, RhsT const &> const {
  2015. static_assert(always_false<RhsT>::value,
  2016. "operator|| is not supported inside assertions, "
  2017. "wrap the expression inside parentheses, or decompose it");
  2018. }
  2019. auto makeUnaryExpr() const -> UnaryExpr<LhsT> {
  2020. return UnaryExpr<LhsT>{m_lhs};
  2021. }
  2022. };
  2023. void handleExpression(ITransientExpression const &expr);
  2024. template<typename T>
  2025. void handleExpression(ExprLhs<T> const &expr) {
  2026. handleExpression(expr.makeUnaryExpr());
  2027. }
  2028. struct Decomposer {
  2029. template<typename T>
  2030. auto operator<=(T const &lhs) -> ExprLhs<T const &> {
  2031. return ExprLhs<T const &>{lhs};
  2032. }
  2033. auto operator<=(bool value) -> ExprLhs<bool> {
  2034. return ExprLhs<bool>{value};
  2035. }
  2036. };
  2037. } // end namespace Catch
  2038. #ifdef _MSC_VER
  2039. #pragma warning(pop)
  2040. #endif
  2041. // end catch_decomposer.h
  2042. // start catch_interfaces_capture.h
  2043. #include <string>
  2044. #include <chrono>
  2045. namespace Catch {
  2046. class AssertionResult;
  2047. struct AssertionInfo;
  2048. struct SectionInfo;
  2049. struct SectionEndInfo;
  2050. struct MessageInfo;
  2051. struct MessageBuilder;
  2052. struct Counts;
  2053. struct AssertionReaction;
  2054. struct SourceLineInfo;
  2055. struct ITransientExpression;
  2056. struct IGeneratorTracker;
  2057. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  2058. struct BenchmarkInfo;
  2059. template <typename Duration = std::chrono::duration<double, std::nano>>
  2060. struct BenchmarkStats;
  2061. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  2062. struct IResultCapture {
  2063. virtual ~IResultCapture();
  2064. virtual bool sectionStarted(SectionInfo const &sectionInfo,
  2065. Counts &assertions) = 0;
  2066. virtual void sectionEnded(SectionEndInfo const &endInfo) = 0;
  2067. virtual void sectionEndedEarly(SectionEndInfo const &endInfo) = 0;
  2068. virtual auto acquireGeneratorTracker(SourceLineInfo const &lineInfo) -> IGeneratorTracker & = 0;
  2069. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  2070. virtual void benchmarkPreparing( std::string const& name ) = 0;
  2071. virtual void benchmarkStarting( BenchmarkInfo const& info ) = 0;
  2072. virtual void benchmarkEnded( BenchmarkStats<> const& stats ) = 0;
  2073. virtual void benchmarkFailed( std::string const& error ) = 0;
  2074. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  2075. virtual void pushScopedMessage(MessageInfo const &message) = 0;
  2076. virtual void popScopedMessage(MessageInfo const &message) = 0;
  2077. virtual void emplaceUnscopedMessage(MessageBuilder const &builder) = 0;
  2078. virtual void handleFatalErrorCondition(StringRef message) = 0;
  2079. virtual void handleExpr
  2080. (AssertionInfo const &info,
  2081. ITransientExpression const &expr,
  2082. AssertionReaction &reaction) = 0;
  2083. virtual void handleMessage
  2084. (AssertionInfo const &info,
  2085. ResultWas::OfType resultType,
  2086. StringRef const &message,
  2087. AssertionReaction &reaction) = 0;
  2088. virtual void handleUnexpectedExceptionNotThrown
  2089. (AssertionInfo const &info,
  2090. AssertionReaction &reaction) = 0;
  2091. virtual void handleUnexpectedInflightException
  2092. (AssertionInfo const &info,
  2093. std::string const &message,
  2094. AssertionReaction &reaction) = 0;
  2095. virtual void handleIncomplete
  2096. (AssertionInfo const &info) = 0;
  2097. virtual void handleNonExpr
  2098. (AssertionInfo const &info,
  2099. ResultWas::OfType resultType,
  2100. AssertionReaction &reaction) = 0;
  2101. virtual bool lastAssertionPassed() = 0;
  2102. virtual void assertionPassed() = 0;
  2103. // Deprecated, do not use:
  2104. virtual std::string getCurrentTestName() const = 0;
  2105. virtual const AssertionResult *getLastResult() const = 0;
  2106. virtual void exceptionEarlyReported() = 0;
  2107. };
  2108. IResultCapture &getResultCapture();
  2109. }
  2110. // end catch_interfaces_capture.h
  2111. namespace Catch {
  2112. struct TestFailureException {};
  2113. struct AssertionResultData;
  2114. struct IResultCapture;
  2115. class RunContext;
  2116. class LazyExpression {
  2117. friend class AssertionHandler;
  2118. friend struct AssertionStats;
  2119. friend class RunContext;
  2120. ITransientExpression const *m_transientExpression = nullptr;
  2121. bool m_isNegated;
  2122. public:
  2123. LazyExpression(bool isNegated);
  2124. LazyExpression(LazyExpression const &other);
  2125. LazyExpression &operator=(LazyExpression const &) = delete;
  2126. explicit operator bool() const;
  2127. friend auto operator<<(std::ostream &os, LazyExpression const &lazyExpr) -> std::ostream &;
  2128. };
  2129. struct AssertionReaction {
  2130. bool shouldDebugBreak = false;
  2131. bool shouldThrow = false;
  2132. };
  2133. class AssertionHandler {
  2134. AssertionInfo m_assertionInfo;
  2135. AssertionReaction m_reaction;
  2136. bool m_completed = false;
  2137. IResultCapture &m_resultCapture;
  2138. public:
  2139. AssertionHandler
  2140. (StringRef const &macroName,
  2141. SourceLineInfo const &lineInfo,
  2142. StringRef capturedExpression,
  2143. ResultDisposition::Flags resultDisposition);
  2144. ~AssertionHandler() {
  2145. if (!m_completed) {
  2146. m_resultCapture.handleIncomplete(m_assertionInfo);
  2147. }
  2148. }
  2149. template<typename T>
  2150. void handleExpr(ExprLhs<T> const &expr) {
  2151. handleExpr(expr.makeUnaryExpr());
  2152. }
  2153. void handleExpr(ITransientExpression const &expr);
  2154. void handleMessage(ResultWas::OfType resultType, StringRef const &message);
  2155. void handleExceptionThrownAsExpected();
  2156. void handleUnexpectedExceptionNotThrown();
  2157. void handleExceptionNotThrownAsExpected();
  2158. void handleThrowingCallSkipped();
  2159. void handleUnexpectedInflightException();
  2160. void complete();
  2161. void setCompleted();
  2162. // query
  2163. auto allowThrows() const -> bool;
  2164. };
  2165. void handleExceptionMatchExpr(AssertionHandler &handler,
  2166. std::string const &str,
  2167. StringRef const &matcherString);
  2168. } // namespace Catch
  2169. // end catch_assertionhandler.h
  2170. // start catch_message.h
  2171. #include <string>
  2172. #include <vector>
  2173. namespace Catch {
  2174. struct MessageInfo {
  2175. MessageInfo(StringRef const &_macroName,
  2176. SourceLineInfo const &_lineInfo,
  2177. ResultWas::OfType _type);
  2178. StringRef macroName;
  2179. std::string message;
  2180. SourceLineInfo lineInfo;
  2181. ResultWas::OfType type;
  2182. unsigned int sequence;
  2183. bool operator==(MessageInfo const &other) const;
  2184. bool operator<(MessageInfo const &other) const;
  2185. private:
  2186. static unsigned int globalCount;
  2187. };
  2188. struct MessageStream {
  2189. template<typename T>
  2190. MessageStream &operator<<(T const &value) {
  2191. m_stream << value;
  2192. return *this;
  2193. }
  2194. ReusableStringStream m_stream;
  2195. };
  2196. struct MessageBuilder : MessageStream {
  2197. MessageBuilder(StringRef const &macroName,
  2198. SourceLineInfo const &lineInfo,
  2199. ResultWas::OfType type);
  2200. template<typename T>
  2201. MessageBuilder &operator<<(T const &value) {
  2202. m_stream << value;
  2203. return *this;
  2204. }
  2205. MessageInfo m_info;
  2206. };
  2207. class ScopedMessage {
  2208. public:
  2209. explicit ScopedMessage(MessageBuilder const &builder);
  2210. ScopedMessage(ScopedMessage &duplicate) = delete;
  2211. ScopedMessage(ScopedMessage &&old);
  2212. ~ScopedMessage();
  2213. MessageInfo m_info;
  2214. bool m_moved;
  2215. };
  2216. class Capturer {
  2217. std::vector<MessageInfo> m_messages;
  2218. IResultCapture &m_resultCapture = getResultCapture();
  2219. size_t m_captured = 0;
  2220. public:
  2221. Capturer(StringRef macroName,
  2222. SourceLineInfo const &lineInfo,
  2223. ResultWas::OfType resultType,
  2224. StringRef names);
  2225. ~Capturer();
  2226. void captureValue(size_t index, std::string const &value);
  2227. template<typename T>
  2228. void captureValues(size_t index, T const &value) {
  2229. captureValue(index, Catch::Detail::stringify(value));
  2230. }
  2231. template<typename T, typename... Ts>
  2232. void captureValues(size_t index, T const &value, Ts const &... values) {
  2233. captureValue(index, Catch::Detail::stringify(value));
  2234. captureValues(index + 1, values...);
  2235. }
  2236. };
  2237. } // end namespace Catch
  2238. // end catch_message.h
  2239. #if !defined(CATCH_CONFIG_DISABLE)
  2240. #if !defined(CATCH_CONFIG_DISABLE_STRINGIFICATION)
  2241. #define CATCH_INTERNAL_STRINGIFY(...) #__VA_ARGS__
  2242. #else
  2243. #define CATCH_INTERNAL_STRINGIFY(...) "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION"
  2244. #endif
  2245. #if defined(CATCH_CONFIG_FAST_COMPILE) || defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  2246. ///////////////////////////////////////////////////////////////////////////////
  2247. // Another way to speed-up compilation is to omit local try-catch for REQUIRE*
  2248. // macros.
  2249. #define INTERNAL_CATCH_TRY
  2250. #define INTERNAL_CATCH_CATCH( capturer )
  2251. #else // CATCH_CONFIG_FAST_COMPILE
  2252. #define INTERNAL_CATCH_TRY try
  2253. #define INTERNAL_CATCH_CATCH(handler) catch(...) { handler.handleUnexpectedInflightException(); }
  2254. #endif
  2255. #define INTERNAL_CATCH_REACT(handler) handler.complete();
  2256. ///////////////////////////////////////////////////////////////////////////////
  2257. #define INTERNAL_CATCH_TEST(macroName, resultDisposition, ...) \
  2258. do { \
  2259. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
  2260. INTERNAL_CATCH_TRY { \
  2261. CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
  2262. catchAssertionHandler.handleExpr( Catch::Decomposer() <= __VA_ARGS__ ); \
  2263. CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
  2264. } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
  2265. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2266. } 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
  2267. // The double negation silences MSVC's C4800 warning, the static_cast forces short-circuit evaluation if the type has overloaded &&.
  2268. ///////////////////////////////////////////////////////////////////////////////
  2269. #define INTERNAL_CATCH_IF(macroName, resultDisposition, ...) \
  2270. INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
  2271. if( Catch::getResultCapture().lastAssertionPassed() )
  2272. ///////////////////////////////////////////////////////////////////////////////
  2273. #define INTERNAL_CATCH_ELSE(macroName, resultDisposition, ...) \
  2274. INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
  2275. if( !Catch::getResultCapture().lastAssertionPassed() )
  2276. ///////////////////////////////////////////////////////////////////////////////
  2277. #define INTERNAL_CATCH_NO_THROW(macroName, resultDisposition, ...) \
  2278. do { \
  2279. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
  2280. try { \
  2281. static_cast<void>(__VA_ARGS__); \
  2282. catchAssertionHandler.handleExceptionNotThrownAsExpected(); \
  2283. } \
  2284. catch( ... ) { \
  2285. catchAssertionHandler.handleUnexpectedInflightException(); \
  2286. } \
  2287. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2288. } while( false )
  2289. ///////////////////////////////////////////////////////////////////////////////
  2290. #define INTERNAL_CATCH_THROWS(macroName, resultDisposition, ...) \
  2291. do { \
  2292. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition); \
  2293. if( catchAssertionHandler.allowThrows() ) \
  2294. try { \
  2295. static_cast<void>(__VA_ARGS__); \
  2296. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  2297. } \
  2298. catch( ... ) { \
  2299. catchAssertionHandler.handleExceptionThrownAsExpected(); \
  2300. } \
  2301. else \
  2302. catchAssertionHandler.handleThrowingCallSkipped(); \
  2303. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2304. } while( false )
  2305. ///////////////////////////////////////////////////////////////////////////////
  2306. #define INTERNAL_CATCH_THROWS_AS(macroName, exceptionType, resultDisposition, expr) \
  2307. do { \
  2308. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType), resultDisposition ); \
  2309. if( catchAssertionHandler.allowThrows() ) \
  2310. try { \
  2311. static_cast<void>(expr); \
  2312. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  2313. } \
  2314. catch( exceptionType const& ) { \
  2315. catchAssertionHandler.handleExceptionThrownAsExpected(); \
  2316. } \
  2317. catch( ... ) { \
  2318. catchAssertionHandler.handleUnexpectedInflightException(); \
  2319. } \
  2320. else \
  2321. catchAssertionHandler.handleThrowingCallSkipped(); \
  2322. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2323. } while( false )
  2324. ///////////////////////////////////////////////////////////////////////////////
  2325. #define INTERNAL_CATCH_MSG(macroName, messageType, resultDisposition, ...) \
  2326. do { \
  2327. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::StringRef(), resultDisposition ); \
  2328. catchAssertionHandler.handleMessage( messageType, ( Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop() ).m_stream.str() ); \
  2329. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2330. } while( false )
  2331. ///////////////////////////////////////////////////////////////////////////////
  2332. #define INTERNAL_CATCH_CAPTURE(varName, macroName, ...) \
  2333. auto varName = Catch::Capturer( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info, #__VA_ARGS__ ); \
  2334. varName.captureValues( 0, __VA_ARGS__ )
  2335. ///////////////////////////////////////////////////////////////////////////////
  2336. #define INTERNAL_CATCH_INFO(macroName, log) \
  2337. Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage )( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log );
  2338. ///////////////////////////////////////////////////////////////////////////////
  2339. #define INTERNAL_CATCH_UNSCOPED_INFO(macroName, log) \
  2340. Catch::getResultCapture().emplaceUnscopedMessage( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log )
  2341. ///////////////////////////////////////////////////////////////////////////////
  2342. // Although this is matcher-based, it can be used with just a string
  2343. #define INTERNAL_CATCH_THROWS_STR_MATCHES(macroName, resultDisposition, matcher, ...) \
  2344. do { \
  2345. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  2346. if( catchAssertionHandler.allowThrows() ) \
  2347. try { \
  2348. static_cast<void>(__VA_ARGS__); \
  2349. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  2350. } \
  2351. catch( ... ) { \
  2352. Catch::handleExceptionMatchExpr( catchAssertionHandler, matcher, #matcher##_catch_sr ); \
  2353. } \
  2354. else \
  2355. catchAssertionHandler.handleThrowingCallSkipped(); \
  2356. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2357. } while( false )
  2358. #endif // CATCH_CONFIG_DISABLE
  2359. // end catch_capture.hpp
  2360. // start catch_section.h
  2361. // start catch_section_info.h
  2362. // start catch_totals.h
  2363. #include <cstddef>
  2364. namespace Catch {
  2365. struct Counts {
  2366. Counts operator-(Counts const &other) const;
  2367. Counts &operator+=(Counts const &other);
  2368. std::size_t total() const;
  2369. bool allPassed() const;
  2370. bool allOk() const;
  2371. std::size_t passed = 0;
  2372. std::size_t failed = 0;
  2373. std::size_t failedButOk = 0;
  2374. };
  2375. struct Totals {
  2376. Totals operator-(Totals const &other) const;
  2377. Totals &operator+=(Totals const &other);
  2378. Totals delta(Totals const &prevTotals) const;
  2379. int error = 0;
  2380. Counts assertions;
  2381. Counts testCases;
  2382. };
  2383. }
  2384. // end catch_totals.h
  2385. #include <string>
  2386. namespace Catch {
  2387. struct SectionInfo {
  2388. SectionInfo
  2389. (SourceLineInfo const &_lineInfo,
  2390. std::string const &_name);
  2391. // Deprecated
  2392. SectionInfo
  2393. (SourceLineInfo const &_lineInfo,
  2394. std::string const &_name,
  2395. std::string const &) : SectionInfo(_lineInfo, _name) {}
  2396. std::string name;
  2397. std::string description; // !Deprecated: this will always be empty
  2398. SourceLineInfo lineInfo;
  2399. };
  2400. struct SectionEndInfo {
  2401. SectionInfo sectionInfo;
  2402. Counts prevAssertions;
  2403. double durationInSeconds;
  2404. };
  2405. } // end namespace Catch
  2406. // end catch_section_info.h
  2407. // start catch_timer.h
  2408. #include <cstdint>
  2409. namespace Catch {
  2410. auto getCurrentNanosecondsSinceEpoch() -> uint64_t;
  2411. auto getEstimatedClockResolution() -> uint64_t;
  2412. class Timer {
  2413. uint64_t m_nanoseconds = 0;
  2414. public:
  2415. void start();
  2416. auto getElapsedNanoseconds() const -> uint64_t;
  2417. auto getElapsedMicroseconds() const -> uint64_t;
  2418. auto getElapsedMilliseconds() const -> unsigned int;
  2419. auto getElapsedSeconds() const -> double;
  2420. };
  2421. } // namespace Catch
  2422. // end catch_timer.h
  2423. #include <string>
  2424. namespace Catch {
  2425. class Section : NonCopyable {
  2426. public:
  2427. Section(SectionInfo const &info);
  2428. ~Section();
  2429. // This indicates whether the section should be executed or not
  2430. explicit operator bool() const;
  2431. private:
  2432. SectionInfo m_info;
  2433. std::string m_name;
  2434. Counts m_assertions;
  2435. bool m_sectionIncluded;
  2436. Timer m_timer;
  2437. };
  2438. } // end namespace Catch
  2439. #define INTERNAL_CATCH_SECTION(...) \
  2440. CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
  2441. if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) ) \
  2442. CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS
  2443. #define INTERNAL_CATCH_DYNAMIC_SECTION(...) \
  2444. CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
  2445. if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, (Catch::ReusableStringStream() << __VA_ARGS__).str() ) ) \
  2446. CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS
  2447. // end catch_section.h
  2448. // start catch_interfaces_exception.h
  2449. // start catch_interfaces_registry_hub.h
  2450. #include <string>
  2451. #include <memory>
  2452. namespace Catch {
  2453. class TestCase;
  2454. struct ITestCaseRegistry;
  2455. struct IExceptionTranslatorRegistry;
  2456. struct IExceptionTranslator;
  2457. struct IReporterRegistry;
  2458. struct IReporterFactory;
  2459. struct ITagAliasRegistry;
  2460. struct IMutableEnumValuesRegistry;
  2461. class StartupExceptionRegistry;
  2462. using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
  2463. struct IRegistryHub {
  2464. virtual ~IRegistryHub();
  2465. virtual IReporterRegistry const &getReporterRegistry() const = 0;
  2466. virtual ITestCaseRegistry const &getTestCaseRegistry() const = 0;
  2467. virtual ITagAliasRegistry const &getTagAliasRegistry() const = 0;
  2468. virtual IExceptionTranslatorRegistry const &getExceptionTranslatorRegistry() const = 0;
  2469. virtual StartupExceptionRegistry const &getStartupExceptionRegistry() const = 0;
  2470. };
  2471. struct IMutableRegistryHub {
  2472. virtual ~IMutableRegistryHub();
  2473. virtual void registerReporter(std::string const &name, IReporterFactoryPtr const &factory) = 0;
  2474. virtual void registerListener(IReporterFactoryPtr const &factory) = 0;
  2475. virtual void registerTest(TestCase const &testInfo) = 0;
  2476. virtual void registerTranslator(const IExceptionTranslator *translator) = 0;
  2477. virtual void registerTagAlias(std::string const &alias,
  2478. std::string const &tag,
  2479. SourceLineInfo const &lineInfo) = 0;
  2480. virtual void registerStartupException() noexcept = 0;
  2481. virtual IMutableEnumValuesRegistry &getMutableEnumValuesRegistry() = 0;
  2482. };
  2483. IRegistryHub const &getRegistryHub();
  2484. IMutableRegistryHub &getMutableRegistryHub();
  2485. void cleanUp();
  2486. std::string translateActiveException();
  2487. }
  2488. // end catch_interfaces_registry_hub.h
  2489. #if defined(CATCH_CONFIG_DISABLE)
  2490. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( translatorName, signature) \
  2491. static std::string translatorName( signature )
  2492. #endif
  2493. #include <exception>
  2494. #include <string>
  2495. #include <vector>
  2496. namespace Catch {
  2497. using exceptionTranslateFunction = std::string(*)();
  2498. struct IExceptionTranslator;
  2499. using ExceptionTranslators = std::vector<std::unique_ptr<IExceptionTranslator const>>;
  2500. struct IExceptionTranslator {
  2501. virtual ~IExceptionTranslator();
  2502. virtual std::string translate(ExceptionTranslators::const_iterator it,
  2503. ExceptionTranslators::const_iterator itEnd) const = 0;
  2504. };
  2505. struct IExceptionTranslatorRegistry {
  2506. virtual ~IExceptionTranslatorRegistry();
  2507. virtual std::string translateActiveException() const = 0;
  2508. };
  2509. class ExceptionTranslatorRegistrar {
  2510. template<typename T>
  2511. class ExceptionTranslator : public IExceptionTranslator {
  2512. public:
  2513. ExceptionTranslator(std::string(*translateFunction)(T &))
  2514. : m_translateFunction(translateFunction) {}
  2515. std::string translate(ExceptionTranslators::const_iterator it,
  2516. ExceptionTranslators::const_iterator itEnd) const override {
  2517. try {
  2518. if (it == itEnd)
  2519. std::rethrow_exception(std::current_exception());
  2520. else
  2521. return (*it)->translate(it + 1, itEnd);
  2522. }
  2523. catch (T &ex) {
  2524. return m_translateFunction(ex);
  2525. }
  2526. }
  2527. protected:
  2528. std::string (*m_translateFunction)(T &);
  2529. };
  2530. public:
  2531. template<typename T>
  2532. ExceptionTranslatorRegistrar(std::string(*translateFunction)(T &)) {
  2533. getMutableRegistryHub().registerTranslator
  2534. (new ExceptionTranslator<T>(translateFunction));
  2535. }
  2536. };
  2537. }
  2538. ///////////////////////////////////////////////////////////////////////////////
  2539. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION2(translatorName, signature) \
  2540. static std::string translatorName( signature ); \
  2541. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  2542. namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &translatorName ); } \
  2543. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  2544. static std::string translatorName( signature )
  2545. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION(signature) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
  2546. // end catch_interfaces_exception.h
  2547. // start catch_approx.h
  2548. #include <type_traits>
  2549. namespace Catch {
  2550. namespace Detail {
  2551. class Approx {
  2552. private:
  2553. bool equalityComparisonImpl(double other) const;
  2554. // Validates the new margin (margin >= 0)
  2555. // out-of-line to avoid including stdexcept in the header
  2556. void setMargin(double margin);
  2557. // Validates the new epsilon (0 < epsilon < 1)
  2558. // out-of-line to avoid including stdexcept in the header
  2559. void setEpsilon(double epsilon);
  2560. public:
  2561. explicit Approx(double value);
  2562. static Approx custom();
  2563. Approx operator-() const;
  2564. template<typename T, typename = typename std::enable_if<std::is_constructible<double,
  2565. T>::value>::type>
  2566. Approx operator()(T const &value) {
  2567. Approx approx(static_cast<double>(value));
  2568. approx.m_epsilon = m_epsilon;
  2569. approx.m_margin = m_margin;
  2570. approx.m_scale = m_scale;
  2571. return approx;
  2572. }
  2573. template<typename T, typename = typename std::enable_if<std::is_constructible<double,
  2574. T>::value>::type>
  2575. explicit Approx(T const &value): Approx(static_cast<double>(value)) {}
  2576. template<typename T, typename = typename std::enable_if<std::is_constructible<double,
  2577. T>::value>::type>
  2578. friend bool operator==(const T &lhs, Approx const &rhs) {
  2579. auto lhs_v = static_cast<double>(lhs);
  2580. return rhs.equalityComparisonImpl(lhs_v);
  2581. }
  2582. template<typename T, typename = typename std::enable_if<std::is_constructible<double,
  2583. T>::value>::type>
  2584. friend bool operator==(Approx const &lhs, const T &rhs) {
  2585. return operator==(rhs, lhs);
  2586. }
  2587. template<typename T, typename = typename std::enable_if<std::is_constructible<double,
  2588. T>::value>::type>
  2589. friend bool operator!=(T const &lhs, Approx const &rhs) {
  2590. return !operator==(lhs, rhs);
  2591. }
  2592. template<typename T, typename = typename std::enable_if<std::is_constructible<double,
  2593. T>::value>::type>
  2594. friend bool operator!=(Approx const &lhs, T const &rhs) {
  2595. return !operator==(rhs, lhs);
  2596. }
  2597. template<typename T, typename = typename std::enable_if<std::is_constructible<double,
  2598. T>::value>::type>
  2599. friend bool operator<=(T const &lhs, Approx const &rhs) {
  2600. return static_cast<double>(lhs) < rhs.m_value || lhs == rhs;
  2601. }
  2602. template<typename T, typename = typename std::enable_if<std::is_constructible<double,
  2603. T>::value>::type>
  2604. friend bool operator<=(Approx const &lhs, T const &rhs) {
  2605. return lhs.m_value < static_cast<double>(rhs) || lhs == rhs;
  2606. }
  2607. template<typename T, typename = typename std::enable_if<std::is_constructible<double,
  2608. T>::value>::type>
  2609. friend bool operator>=(T const &lhs, Approx const &rhs) {
  2610. return static_cast<double>(lhs) > rhs.m_value || lhs == rhs;
  2611. }
  2612. template<typename T, typename = typename std::enable_if<std::is_constructible<double,
  2613. T>::value>::type>
  2614. friend bool operator>=(Approx const &lhs, T const &rhs) {
  2615. return lhs.m_value > static_cast<double>(rhs) || lhs == rhs;
  2616. }
  2617. template<typename T, typename = typename std::enable_if<std::is_constructible<double,
  2618. T>::value>::type>
  2619. Approx &epsilon(T const &newEpsilon) {
  2620. double epsilonAsDouble = static_cast<double>(newEpsilon);
  2621. setEpsilon(epsilonAsDouble);
  2622. return *this;
  2623. }
  2624. template<typename T, typename = typename std::enable_if<std::is_constructible<double,
  2625. T>::value>::type>
  2626. Approx &margin(T const &newMargin) {
  2627. double marginAsDouble = static_cast<double>(newMargin);
  2628. setMargin(marginAsDouble);
  2629. return *this;
  2630. }
  2631. template<typename T, typename = typename std::enable_if<std::is_constructible<double,
  2632. T>::value>::type>
  2633. Approx &scale(T const &newScale) {
  2634. m_scale = static_cast<double>(newScale);
  2635. return *this;
  2636. }
  2637. std::string toString() const;
  2638. private:
  2639. double m_epsilon;
  2640. double m_margin;
  2641. double m_scale;
  2642. double m_value;
  2643. };
  2644. } // end namespace Detail
  2645. namespace literals {
  2646. Detail::Approx operator "" _a(long double val);
  2647. Detail::Approx operator "" _a(unsigned long long val);
  2648. } // end namespace literals
  2649. template<>
  2650. struct StringMaker<Catch::Detail::Approx> {
  2651. static std::string convert(Catch::Detail::Approx const &value);
  2652. };
  2653. } // end namespace Catch
  2654. // end catch_approx.h
  2655. // start catch_string_manip.h
  2656. #include <string>
  2657. #include <iosfwd>
  2658. #include <vector>
  2659. namespace Catch {
  2660. bool startsWith(std::string const &s, std::string const &prefix);
  2661. bool startsWith(std::string const &s, char prefix);
  2662. bool endsWith(std::string const &s, std::string const &suffix);
  2663. bool endsWith(std::string const &s, char suffix);
  2664. bool contains(std::string const &s, std::string const &infix);
  2665. void toLowerInPlace(std::string &s);
  2666. std::string toLower(std::string const &s);
  2667. std::string trim(std::string const &str);
  2668. // !!! Be aware, returns refs into original string - make sure original string outlives them
  2669. std::vector<StringRef> splitStringRef(StringRef str, char delimiter);
  2670. bool replaceInPlace(std::string &str, std::string const &replaceThis, std::string const &withThis);
  2671. struct pluralise {
  2672. pluralise(std::size_t count, std::string const &label);
  2673. friend std::ostream &operator<<(std::ostream &os, pluralise const &pluraliser);
  2674. std::size_t m_count;
  2675. std::string m_label;
  2676. };
  2677. }
  2678. // end catch_string_manip.h
  2679. #ifndef CATCH_CONFIG_DISABLE_MATCHERS
  2680. // start catch_capture_matchers.h
  2681. // start catch_matchers.h
  2682. #include <string>
  2683. #include <vector>
  2684. namespace Catch {
  2685. namespace Matchers {
  2686. namespace Impl {
  2687. template<typename ArgT> struct MatchAllOf;
  2688. template<typename ArgT> struct MatchAnyOf;
  2689. template<typename ArgT> struct MatchNotOf;
  2690. class MatcherUntypedBase {
  2691. public:
  2692. MatcherUntypedBase() = default;
  2693. MatcherUntypedBase(MatcherUntypedBase const &) = default;
  2694. MatcherUntypedBase &operator=(MatcherUntypedBase const &) = delete;
  2695. std::string toString() const;
  2696. protected:
  2697. virtual ~MatcherUntypedBase();
  2698. virtual std::string describe() const = 0;
  2699. mutable std::string m_cachedToString;
  2700. };
  2701. #ifdef __clang__
  2702. # pragma clang diagnostic push
  2703. # pragma clang diagnostic ignored "-Wnon-virtual-dtor"
  2704. #endif
  2705. template<typename ObjectT>
  2706. struct MatcherMethod {
  2707. virtual bool match(ObjectT const &arg) const = 0;
  2708. };
  2709. #if defined(__OBJC__)
  2710. // Hack to fix Catch GH issue #1661. Could use id for generic Object support.
  2711. // use of const for Object pointers is very uncommon and under ARC it causes some kind of signature mismatch that breaks compilation
  2712. template<>
  2713. struct MatcherMethod<NSString*> {
  2714. virtual bool match( NSString* arg ) const = 0;
  2715. };
  2716. #endif
  2717. #ifdef __clang__
  2718. # pragma clang diagnostic pop
  2719. #endif
  2720. template<typename T>
  2721. struct MatcherBase : MatcherUntypedBase, MatcherMethod<T> {
  2722. MatchAllOf<T> operator&&(MatcherBase const &other) const;
  2723. MatchAnyOf<T> operator||(MatcherBase const &other) const;
  2724. MatchNotOf<T> operator!() const;
  2725. };
  2726. template<typename ArgT>
  2727. struct MatchAllOf : MatcherBase<ArgT> {
  2728. bool match(ArgT const &arg) const override {
  2729. for (auto matcher : m_matchers) {
  2730. if (!matcher->match(arg))
  2731. return false;
  2732. }
  2733. return true;
  2734. }
  2735. std::string describe() const override {
  2736. std::string description;
  2737. description.reserve(4 + m_matchers.size() * 32);
  2738. description += "( ";
  2739. bool first = true;
  2740. for (auto matcher : m_matchers) {
  2741. if (first)
  2742. first = false;
  2743. else
  2744. description += " and ";
  2745. description += matcher->toString();
  2746. }
  2747. description += " )";
  2748. return description;
  2749. }
  2750. MatchAllOf<ArgT> &operator&&(MatcherBase<ArgT> const &other) {
  2751. m_matchers.push_back(&other);
  2752. return *this;
  2753. }
  2754. std::vector<MatcherBase<ArgT> const *> m_matchers;
  2755. };
  2756. template<typename ArgT>
  2757. struct MatchAnyOf : MatcherBase<ArgT> {
  2758. bool match(ArgT const &arg) const override {
  2759. for (auto matcher : m_matchers) {
  2760. if (matcher->match(arg))
  2761. return true;
  2762. }
  2763. return false;
  2764. }
  2765. std::string describe() const override {
  2766. std::string description;
  2767. description.reserve(4 + m_matchers.size() * 32);
  2768. description += "( ";
  2769. bool first = true;
  2770. for (auto matcher : m_matchers) {
  2771. if (first)
  2772. first = false;
  2773. else
  2774. description += " or ";
  2775. description += matcher->toString();
  2776. }
  2777. description += " )";
  2778. return description;
  2779. }
  2780. MatchAnyOf<ArgT> &operator||(MatcherBase<ArgT> const &other) {
  2781. m_matchers.push_back(&other);
  2782. return *this;
  2783. }
  2784. std::vector<MatcherBase<ArgT> const *> m_matchers;
  2785. };
  2786. template<typename ArgT>
  2787. struct MatchNotOf : MatcherBase<ArgT> {
  2788. MatchNotOf(MatcherBase<ArgT> const &underlyingMatcher) : m_underlyingMatcher(underlyingMatcher) {}
  2789. bool match(ArgT const &arg) const override {
  2790. return !m_underlyingMatcher.match(arg);
  2791. }
  2792. std::string describe() const override {
  2793. return "not " + m_underlyingMatcher.toString();
  2794. }
  2795. MatcherBase<ArgT> const &m_underlyingMatcher;
  2796. };
  2797. template<typename T>
  2798. MatchAllOf<T> MatcherBase<T>::operator&&(MatcherBase const &other) const {
  2799. return MatchAllOf<T>() && *this && other;
  2800. }
  2801. template<typename T>
  2802. MatchAnyOf<T> MatcherBase<T>::operator||(MatcherBase const &other) const {
  2803. return MatchAnyOf<T>() || *this || other;
  2804. }
  2805. template<typename T>
  2806. MatchNotOf<T> MatcherBase<T>::operator!() const {
  2807. return MatchNotOf<T>(*this);
  2808. }
  2809. } // namespace Impl
  2810. } // namespace Matchers
  2811. using namespace Matchers;
  2812. using Matchers::Impl::MatcherBase;
  2813. } // namespace Catch
  2814. // end catch_matchers.h
  2815. // start catch_matchers_floating.h
  2816. #include <type_traits>
  2817. #include <cmath>
  2818. namespace Catch {
  2819. namespace Matchers {
  2820. namespace Floating {
  2821. enum class FloatingPointKind : uint8_t;
  2822. struct WithinAbsMatcher : MatcherBase<double> {
  2823. WithinAbsMatcher(double target, double margin);
  2824. bool match(double const &matchee) const override;
  2825. std::string describe() const override;
  2826. private:
  2827. double m_target;
  2828. double m_margin;
  2829. };
  2830. struct WithinUlpsMatcher : MatcherBase<double> {
  2831. WithinUlpsMatcher(double target, int ulps, FloatingPointKind baseType);
  2832. bool match(double const &matchee) const override;
  2833. std::string describe() const override;
  2834. private:
  2835. double m_target;
  2836. int m_ulps;
  2837. FloatingPointKind m_type;
  2838. };
  2839. } // namespace Floating
  2840. // The following functions create the actual matcher objects.
  2841. // This allows the types to be inferred
  2842. Floating::WithinUlpsMatcher WithinULP(double target, int maxUlpDiff);
  2843. Floating::WithinUlpsMatcher WithinULP(float target, int maxUlpDiff);
  2844. Floating::WithinAbsMatcher WithinAbs(double target, double margin);
  2845. } // namespace Matchers
  2846. } // namespace Catch
  2847. // end catch_matchers_floating.h
  2848. // start catch_matchers_generic.hpp
  2849. #include <functional>
  2850. #include <string>
  2851. namespace Catch {
  2852. namespace Matchers {
  2853. namespace Generic {
  2854. namespace Detail {
  2855. std::string finalizeDescription(const std::string &desc);
  2856. }
  2857. template<typename T>
  2858. class PredicateMatcher : public MatcherBase<T> {
  2859. std::function<bool(T const &)> m_predicate;
  2860. std::string m_description;
  2861. public:
  2862. PredicateMatcher(std::function<bool(T const &)> const &elem, std::string const &descr)
  2863. : m_predicate(std::move(elem)),
  2864. m_description(Detail::finalizeDescription(descr)) {}
  2865. bool match(T const &item) const override {
  2866. return m_predicate(item);
  2867. }
  2868. std::string describe() const override {
  2869. return m_description;
  2870. }
  2871. };
  2872. } // namespace Generic
  2873. // The following functions create the actual matcher objects.
  2874. // The user has to explicitly specify type to the function, because
  2875. // inferring std::function<bool(T const&)> is hard (but possible) and
  2876. // requires a lot of TMP.
  2877. template<typename T>
  2878. Generic::PredicateMatcher<T> Predicate(std::function<bool(T const &)> const &predicate,
  2879. std::string const &description = "") {
  2880. return Generic::PredicateMatcher<T>(predicate, description);
  2881. }
  2882. } // namespace Matchers
  2883. } // namespace Catch
  2884. // end catch_matchers_generic.hpp
  2885. // start catch_matchers_string.h
  2886. #include <string>
  2887. namespace Catch {
  2888. namespace Matchers {
  2889. namespace StdString {
  2890. struct CasedString {
  2891. CasedString(std::string const &str, CaseSensitive::Choice caseSensitivity);
  2892. std::string adjustString(std::string const &str) const;
  2893. std::string caseSensitivitySuffix() const;
  2894. CaseSensitive::Choice m_caseSensitivity;
  2895. std::string m_str;
  2896. };
  2897. struct StringMatcherBase : MatcherBase<std::string> {
  2898. StringMatcherBase(std::string const &operation, CasedString const &comparator);
  2899. std::string describe() const override;
  2900. CasedString m_comparator;
  2901. std::string m_operation;
  2902. };
  2903. struct EqualsMatcher : StringMatcherBase {
  2904. EqualsMatcher(CasedString const &comparator);
  2905. bool match(std::string const &source) const override;
  2906. };
  2907. struct ContainsMatcher : StringMatcherBase {
  2908. ContainsMatcher(CasedString const &comparator);
  2909. bool match(std::string const &source) const override;
  2910. };
  2911. struct StartsWithMatcher : StringMatcherBase {
  2912. StartsWithMatcher(CasedString const &comparator);
  2913. bool match(std::string const &source) const override;
  2914. };
  2915. struct EndsWithMatcher : StringMatcherBase {
  2916. EndsWithMatcher(CasedString const &comparator);
  2917. bool match(std::string const &source) const override;
  2918. };
  2919. struct RegexMatcher : MatcherBase<std::string> {
  2920. RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity);
  2921. bool match(std::string const &matchee) const override;
  2922. std::string describe() const override;
  2923. private:
  2924. std::string m_regex;
  2925. CaseSensitive::Choice m_caseSensitivity;
  2926. };
  2927. } // namespace StdString
  2928. // The following functions create the actual matcher objects.
  2929. // This allows the types to be inferred
  2930. StdString::EqualsMatcher Equals(std::string const &str,
  2931. CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes);
  2932. StdString::ContainsMatcher Contains(std::string const &str,
  2933. CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes);
  2934. StdString::EndsWithMatcher EndsWith(std::string const &str,
  2935. CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes);
  2936. StdString::StartsWithMatcher StartsWith(std::string const &str,
  2937. CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes);
  2938. StdString::RegexMatcher Matches(std::string const &regex,
  2939. CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes);
  2940. } // namespace Matchers
  2941. } // namespace Catch
  2942. // end catch_matchers_string.h
  2943. // start catch_matchers_vector.h
  2944. #include <algorithm>
  2945. namespace Catch {
  2946. namespace Matchers {
  2947. namespace Vector {
  2948. template<typename T>
  2949. struct ContainsElementMatcher : MatcherBase<std::vector<T>> {
  2950. ContainsElementMatcher(T const &comparator) : m_comparator(comparator) {}
  2951. bool match(std::vector<T> const &v) const override {
  2952. for (auto const &el : v) {
  2953. if (el == m_comparator) {
  2954. return true;
  2955. }
  2956. }
  2957. return false;
  2958. }
  2959. std::string describe() const override {
  2960. return "Contains: " + ::Catch::Detail::stringify(m_comparator);
  2961. }
  2962. T const &m_comparator;
  2963. };
  2964. template<typename T>
  2965. struct ContainsMatcher : MatcherBase<std::vector<T>> {
  2966. ContainsMatcher(std::vector<T> const &comparator) : m_comparator(comparator) {}
  2967. bool match(std::vector<T> const &v) const override {
  2968. // !TBD: see note in EqualsMatcher
  2969. if (m_comparator.size() > v.size())
  2970. return false;
  2971. for (auto const &comparator : m_comparator) {
  2972. auto present = false;
  2973. for (const auto &el : v) {
  2974. if (el == comparator) {
  2975. present = true;
  2976. break;
  2977. }
  2978. }
  2979. if (!present) {
  2980. return false;
  2981. }
  2982. }
  2983. return true;
  2984. }
  2985. std::string describe() const override {
  2986. return "Contains: " + ::Catch::Detail::stringify(m_comparator);
  2987. }
  2988. std::vector<T> const &m_comparator;
  2989. };
  2990. template<typename T>
  2991. struct EqualsMatcher : MatcherBase<std::vector<T>> {
  2992. EqualsMatcher(std::vector<T> const &comparator) : m_comparator(comparator) {}
  2993. bool match(std::vector<T> const &v) const override {
  2994. // !TBD: This currently works if all elements can be compared using !=
  2995. // - a more general approach would be via a compare template that defaults
  2996. // to using !=. but could be specialised for, e.g. std::vector<T> etc
  2997. // - then just call that directly
  2998. if (m_comparator.size() != v.size())
  2999. return false;
  3000. for (std::size_t i = 0; i < v.size(); ++i)
  3001. if (m_comparator[i] != v[i])
  3002. return false;
  3003. return true;
  3004. }
  3005. std::string describe() const override {
  3006. return "Equals: " + ::Catch::Detail::stringify(m_comparator);
  3007. }
  3008. std::vector<T> const &m_comparator;
  3009. };
  3010. template<typename T>
  3011. struct ApproxMatcher : MatcherBase<std::vector<T>> {
  3012. ApproxMatcher(std::vector<T> const &comparator) : m_comparator(comparator) {}
  3013. bool match(std::vector<T> const &v) const override {
  3014. if (m_comparator.size() != v.size())
  3015. return false;
  3016. for (std::size_t i = 0; i < v.size(); ++i)
  3017. if (m_comparator[i] != approx(v[i]))
  3018. return false;
  3019. return true;
  3020. }
  3021. std::string describe() const override {
  3022. return "is approx: " + ::Catch::Detail::stringify(m_comparator);
  3023. }
  3024. template<typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  3025. ApproxMatcher &epsilon(T const &newEpsilon) {
  3026. approx.epsilon(newEpsilon);
  3027. return *this;
  3028. }
  3029. template<typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  3030. ApproxMatcher &margin(T const &newMargin) {
  3031. approx.margin(newMargin);
  3032. return *this;
  3033. }
  3034. template<typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  3035. ApproxMatcher &scale(T const &newScale) {
  3036. approx.scale(newScale);
  3037. return *this;
  3038. }
  3039. std::vector<T> const &m_comparator;
  3040. mutable Catch::Detail::Approx approx = Catch::Detail::Approx::custom();
  3041. };
  3042. template<typename T>
  3043. struct UnorderedEqualsMatcher : MatcherBase<std::vector<T>> {
  3044. UnorderedEqualsMatcher(std::vector<T> const &target) : m_target(target) {}
  3045. bool match(std::vector<T> const &vec) const override {
  3046. // Note: This is a reimplementation of std::is_permutation,
  3047. // because I don't want to include <algorithm> inside the common path
  3048. if (m_target.size() != vec.size()) {
  3049. return false;
  3050. }
  3051. return std::is_permutation(m_target.begin(), m_target.end(), vec.begin());
  3052. }
  3053. std::string describe() const override {
  3054. return "UnorderedEquals: " + ::Catch::Detail::stringify(m_target);
  3055. }
  3056. private:
  3057. std::vector<T> const &m_target;
  3058. };
  3059. } // namespace Vector
  3060. // The following functions create the actual matcher objects.
  3061. // This allows the types to be inferred
  3062. template<typename T>
  3063. Vector::ContainsMatcher<T> Contains(std::vector<T> const &comparator) {
  3064. return Vector::ContainsMatcher<T>(comparator);
  3065. }
  3066. template<typename T>
  3067. Vector::ContainsElementMatcher<T> VectorContains(T const &comparator) {
  3068. return Vector::ContainsElementMatcher<T>(comparator);
  3069. }
  3070. template<typename T>
  3071. Vector::EqualsMatcher<T> Equals(std::vector<T> const &comparator) {
  3072. return Vector::EqualsMatcher<T>(comparator);
  3073. }
  3074. template<typename T>
  3075. Vector::ApproxMatcher<T> Approx(std::vector<T> const &comparator) {
  3076. return Vector::ApproxMatcher<T>(comparator);
  3077. }
  3078. template<typename T>
  3079. Vector::UnorderedEqualsMatcher<T> UnorderedEquals(std::vector<T> const &target) {
  3080. return Vector::UnorderedEqualsMatcher<T>(target);
  3081. }
  3082. } // namespace Matchers
  3083. } // namespace Catch
  3084. // end catch_matchers_vector.h
  3085. namespace Catch {
  3086. template<typename ArgT, typename MatcherT>
  3087. class MatchExpr : public ITransientExpression {
  3088. ArgT const &m_arg;
  3089. MatcherT m_matcher;
  3090. StringRef m_matcherString;
  3091. public:
  3092. MatchExpr(ArgT const &arg, MatcherT const &matcher, StringRef const &matcherString)
  3093. : ITransientExpression{true, matcher.match(arg)},
  3094. m_arg(arg),
  3095. m_matcher(matcher),
  3096. m_matcherString(matcherString) {}
  3097. void streamReconstructedExpression(std::ostream &os) const override {
  3098. auto matcherAsString = m_matcher.toString();
  3099. os << Catch::Detail::stringify(m_arg) << ' ';
  3100. if (matcherAsString == Detail::unprintableString)
  3101. os << m_matcherString;
  3102. else
  3103. os << matcherAsString;
  3104. }
  3105. };
  3106. using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
  3107. void handleExceptionMatchExpr(AssertionHandler &handler,
  3108. StringMatcher const &matcher,
  3109. StringRef const &matcherString);
  3110. template<typename ArgT, typename MatcherT>
  3111. auto makeMatchExpr(ArgT const &arg,
  3112. MatcherT const &matcher,
  3113. StringRef const &matcherString) -> MatchExpr<ArgT, MatcherT> {
  3114. return MatchExpr<ArgT, MatcherT>(arg, matcher, matcherString);
  3115. }
  3116. } // namespace Catch
  3117. ///////////////////////////////////////////////////////////////////////////////
  3118. #define INTERNAL_CHECK_THAT(macroName, matcher, resultDisposition, arg) \
  3119. do { \
  3120. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  3121. INTERNAL_CATCH_TRY { \
  3122. catchAssertionHandler.handleExpr( Catch::makeMatchExpr( arg, matcher, #matcher##_catch_sr ) ); \
  3123. } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
  3124. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  3125. } while( false )
  3126. ///////////////////////////////////////////////////////////////////////////////
  3127. #define INTERNAL_CATCH_THROWS_MATCHES(macroName, exceptionType, resultDisposition, matcher, ...) \
  3128. do { \
  3129. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(exceptionType) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  3130. if( catchAssertionHandler.allowThrows() ) \
  3131. try { \
  3132. static_cast<void>(__VA_ARGS__ ); \
  3133. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  3134. } \
  3135. catch( exceptionType const& ex ) { \
  3136. catchAssertionHandler.handleExpr( Catch::makeMatchExpr( ex, matcher, #matcher##_catch_sr ) ); \
  3137. } \
  3138. catch( ... ) { \
  3139. catchAssertionHandler.handleUnexpectedInflightException(); \
  3140. } \
  3141. else \
  3142. catchAssertionHandler.handleThrowingCallSkipped(); \
  3143. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  3144. } while( false )
  3145. // end catch_capture_matchers.h
  3146. #endif
  3147. // start catch_generators.hpp
  3148. // start catch_interfaces_generatortracker.h
  3149. #include <memory>
  3150. namespace Catch {
  3151. namespace Generators {
  3152. class GeneratorUntypedBase {
  3153. public:
  3154. GeneratorUntypedBase() = default;
  3155. virtual ~GeneratorUntypedBase();
  3156. // Attempts to move the generator to the next element
  3157. //
  3158. // Returns true iff the move succeeded (and a valid element
  3159. // can be retrieved).
  3160. virtual bool next() = 0;
  3161. };
  3162. using GeneratorBasePtr = std::unique_ptr<GeneratorUntypedBase>;
  3163. } // namespace Generators
  3164. struct IGeneratorTracker {
  3165. virtual ~IGeneratorTracker();
  3166. virtual auto hasGenerator() const -> bool = 0;
  3167. virtual auto getGenerator() const -> Generators::GeneratorBasePtr const & = 0;
  3168. virtual void setGenerator(Generators::GeneratorBasePtr &&generator) = 0;
  3169. };
  3170. } // namespace Catch
  3171. // end catch_interfaces_generatortracker.h
  3172. // start catch_enforce.h
  3173. #include <exception>
  3174. namespace Catch {
  3175. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  3176. template<typename Ex>
  3177. [[noreturn]]
  3178. void throw_exception(Ex const &e) {
  3179. throw e;
  3180. }
  3181. #else // ^^ Exceptions are enabled // Exceptions are disabled vv
  3182. [[noreturn]]
  3183. void throw_exception(std::exception const& e);
  3184. #endif
  3185. [[noreturn]]
  3186. void throw_logic_error(std::string const &msg);
  3187. [[noreturn]]
  3188. void throw_domain_error(std::string const &msg);
  3189. [[noreturn]]
  3190. void throw_runtime_error(std::string const &msg);
  3191. } // namespace Catch;
  3192. #define CATCH_MAKE_MSG(...) \
  3193. (Catch::ReusableStringStream() << __VA_ARGS__).str()
  3194. #define CATCH_INTERNAL_ERROR(...) \
  3195. Catch::throw_logic_error(CATCH_MAKE_MSG( CATCH_INTERNAL_LINEINFO << ": Internal Catch2 error: " << __VA_ARGS__));
  3196. #define CATCH_ERROR(...) \
  3197. Catch::throw_domain_error(CATCH_MAKE_MSG( __VA_ARGS__ ));
  3198. #define CATCH_RUNTIME_ERROR(...) \
  3199. Catch::throw_runtime_error(CATCH_MAKE_MSG( __VA_ARGS__ ));
  3200. #define CATCH_ENFORCE(condition, ...) \
  3201. do{ if( !(condition) ) CATCH_ERROR( __VA_ARGS__ ); } while(false)
  3202. // end catch_enforce.h
  3203. #include <memory>
  3204. #include <vector>
  3205. #include <cassert>
  3206. #include <utility>
  3207. #include <exception>
  3208. namespace Catch {
  3209. class GeneratorException : public std::exception {
  3210. const char *const m_msg = "";
  3211. public:
  3212. GeneratorException(const char *msg) :
  3213. m_msg(msg) {}
  3214. const char *what() const noexcept override final;
  3215. };
  3216. namespace Generators {
  3217. // !TBD move this into its own location?
  3218. namespace pf {
  3219. template<typename T, typename... Args>
  3220. std::unique_ptr<T> make_unique(Args &&... args) {
  3221. return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
  3222. }
  3223. }
  3224. template<typename T>
  3225. struct IGenerator : GeneratorUntypedBase {
  3226. virtual ~IGenerator() = default;
  3227. // Returns the current element of the generator
  3228. //
  3229. // \Precondition The generator is either freshly constructed,
  3230. // or the last call to `next()` returned true
  3231. virtual T const &get() const = 0;
  3232. using type = T;
  3233. };
  3234. template<typename T>
  3235. class SingleValueGenerator final : public IGenerator<T> {
  3236. T m_value;
  3237. public:
  3238. SingleValueGenerator(T const &value) : m_value(value) {}
  3239. SingleValueGenerator(T &&value) : m_value(std::move(value)) {}
  3240. T const &get() const override {
  3241. return m_value;
  3242. }
  3243. bool next() override {
  3244. return false;
  3245. }
  3246. };
  3247. template<typename T>
  3248. class FixedValuesGenerator final : public IGenerator<T> {
  3249. static_assert(!std::is_same<T, bool>::value,
  3250. "ValuesGenerator does not support bools because of std::vector<bool>"
  3251. "specialization, use SingleValue Generator instead.");
  3252. std::vector<T> m_values;
  3253. size_t m_idx = 0;
  3254. public:
  3255. FixedValuesGenerator(std::initializer_list<T> values) : m_values(values) {}
  3256. T const &get() const override {
  3257. return m_values[m_idx];
  3258. }
  3259. bool next() override {
  3260. ++m_idx;
  3261. return m_idx < m_values.size();
  3262. }
  3263. };
  3264. template<typename T>
  3265. class GeneratorWrapper final {
  3266. std::unique_ptr<IGenerator<T>> m_generator;
  3267. public:
  3268. GeneratorWrapper(std::unique_ptr<IGenerator<T>> generator) :
  3269. m_generator(std::move(generator)) {}
  3270. T const &get() const {
  3271. return m_generator->get();
  3272. }
  3273. bool next() {
  3274. return m_generator->next();
  3275. }
  3276. };
  3277. template<typename T>
  3278. GeneratorWrapper<T> value(T &&value) {
  3279. return GeneratorWrapper<T>(pf::make_unique<SingleValueGenerator<T>>(std::forward<T>(value)));
  3280. }
  3281. template<typename T>
  3282. GeneratorWrapper<T> values(std::initializer_list<T> values) {
  3283. return GeneratorWrapper<T>(pf::make_unique<FixedValuesGenerator<T>>(values));
  3284. }
  3285. template<typename T>
  3286. class Generators : public IGenerator<T> {
  3287. std::vector<GeneratorWrapper<T>> m_generators;
  3288. size_t m_current = 0;
  3289. void populate(GeneratorWrapper<T> &&generator) {
  3290. m_generators.emplace_back(std::move(generator));
  3291. }
  3292. void populate(T &&val) {
  3293. m_generators.emplace_back(value(std::move(val)));
  3294. }
  3295. template<typename U>
  3296. void populate(U &&val) {
  3297. populate(T(std::move(val)));
  3298. }
  3299. template<typename U, typename... Gs>
  3300. void populate(U &&valueOrGenerator, Gs... moreGenerators) {
  3301. populate(std::forward<U>(valueOrGenerator));
  3302. populate(std::forward<Gs>(moreGenerators)...);
  3303. }
  3304. public:
  3305. template<typename... Gs>
  3306. Generators(Gs... moreGenerators) {
  3307. m_generators.reserve(sizeof...(Gs));
  3308. populate(std::forward<Gs>(moreGenerators)...);
  3309. }
  3310. T const &get() const override {
  3311. return m_generators[m_current].get();
  3312. }
  3313. bool next() override {
  3314. if (m_current >= m_generators.size()) {
  3315. return false;
  3316. }
  3317. const bool current_status = m_generators[m_current].next();
  3318. if (!current_status) {
  3319. ++m_current;
  3320. }
  3321. return m_current < m_generators.size();
  3322. }
  3323. };
  3324. template<typename... Ts>
  3325. GeneratorWrapper<std::tuple<Ts...>> table(std::initializer_list<std::tuple<typename std::decay<Ts>::type...>> tuples) {
  3326. return values<std::tuple<Ts...>>(tuples);
  3327. }
  3328. // Tag type to signal that a generator sequence should convert arguments to a specific type
  3329. template<typename T>
  3330. struct as {};
  3331. template<typename T, typename... Gs>
  3332. auto makeGenerators(GeneratorWrapper<T> &&generator, Gs... moreGenerators) -> Generators<T> {
  3333. return Generators<T>(std::move(generator), std::forward<Gs>(moreGenerators)...);
  3334. }
  3335. template<typename T>
  3336. auto makeGenerators(GeneratorWrapper<T> &&generator) -> Generators<T> {
  3337. return Generators<T>(std::move(generator));
  3338. }
  3339. template<typename T, typename... Gs>
  3340. auto makeGenerators(T &&val, Gs... moreGenerators) -> Generators<T> {
  3341. return makeGenerators(value(std::forward<T>(val)), std::forward<Gs>(moreGenerators)...);
  3342. }
  3343. template<typename T, typename U, typename... Gs>
  3344. auto makeGenerators(as<T>, U &&val, Gs... moreGenerators) -> Generators<T> {
  3345. return makeGenerators(value(T(std::forward<U>(val))), std::forward<Gs>(moreGenerators)...);
  3346. }
  3347. auto acquireGeneratorTracker(SourceLineInfo const &lineInfo) -> IGeneratorTracker &;
  3348. template<typename L>
  3349. // Note: The type after -> is weird, because VS2015 cannot parse
  3350. // the expression used in the typedef inside, when it is in
  3351. // return type. Yeah.
  3352. auto generate(SourceLineInfo const &lineInfo,
  3353. L const &generatorExpression) -> decltype(std::declval<decltype(generatorExpression())>()
  3354. .get()) {
  3355. using UnderlyingType = typename decltype(generatorExpression())::type;
  3356. IGeneratorTracker &tracker = acquireGeneratorTracker(lineInfo);
  3357. if (!tracker.hasGenerator()) {
  3358. tracker.setGenerator(pf::make_unique<Generators<UnderlyingType>>(generatorExpression()));
  3359. }
  3360. auto const &generator = static_cast<IGenerator<UnderlyingType> const &>( *tracker.getGenerator());
  3361. return generator.get();
  3362. }
  3363. } // namespace Generators
  3364. } // namespace Catch
  3365. #define GENERATE(...) \
  3366. Catch::Generators::generate( CATCH_INTERNAL_LINEINFO, [ ]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } )
  3367. #define GENERATE_COPY(...) \
  3368. Catch::Generators::generate( CATCH_INTERNAL_LINEINFO, [=]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } )
  3369. #define GENERATE_REF(...) \
  3370. Catch::Generators::generate( CATCH_INTERNAL_LINEINFO, [&]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } )
  3371. // end catch_generators.hpp
  3372. // start catch_generators_generic.hpp
  3373. namespace Catch {
  3374. namespace Generators {
  3375. template<typename T>
  3376. class TakeGenerator : public IGenerator<T> {
  3377. GeneratorWrapper<T> m_generator;
  3378. size_t m_returned = 0;
  3379. size_t m_target;
  3380. public:
  3381. TakeGenerator(size_t target, GeneratorWrapper<T> &&generator) :
  3382. m_generator(std::move(generator)),
  3383. m_target(target) {
  3384. assert(target != 0 && "Empty generators are not allowed");
  3385. }
  3386. T const &get() const override {
  3387. return m_generator.get();
  3388. }
  3389. bool next() override {
  3390. ++m_returned;
  3391. if (m_returned >= m_target) {
  3392. return false;
  3393. }
  3394. const auto success = m_generator.next();
  3395. // If the underlying generator does not contain enough values
  3396. // then we cut short as well
  3397. if (!success) {
  3398. m_returned = m_target;
  3399. }
  3400. return success;
  3401. }
  3402. };
  3403. template<typename T>
  3404. GeneratorWrapper<T> take(size_t target, GeneratorWrapper<T> &&generator) {
  3405. return GeneratorWrapper<T>(pf::make_unique<TakeGenerator<T>>(target, std::move(generator)));
  3406. }
  3407. template<typename T, typename Predicate>
  3408. class FilterGenerator : public IGenerator<T> {
  3409. GeneratorWrapper<T> m_generator;
  3410. Predicate m_predicate;
  3411. public:
  3412. template<typename P = Predicate>
  3413. FilterGenerator(P &&pred, GeneratorWrapper<T> &&generator):
  3414. m_generator(std::move(generator)),
  3415. m_predicate(std::forward<P>(pred)) {
  3416. if (!m_predicate(m_generator.get())) {
  3417. // It might happen that there are no values that pass the
  3418. // filter. In that case we throw an exception.
  3419. auto has_initial_value = next();
  3420. if (!has_initial_value) {
  3421. Catch::throw_exception(GeneratorException("No valid value found in filtered generator"));
  3422. }
  3423. }
  3424. }
  3425. T const &get() const override {
  3426. return m_generator.get();
  3427. }
  3428. bool next() override {
  3429. bool success = m_generator.next();
  3430. if (!success) {
  3431. return false;
  3432. }
  3433. while (!m_predicate(m_generator.get()) && (success = m_generator.next()) == true);
  3434. return success;
  3435. }
  3436. };
  3437. template<typename T, typename Predicate>
  3438. GeneratorWrapper<T> filter(Predicate &&pred, GeneratorWrapper<T> &&generator) {
  3439. return GeneratorWrapper<T>(std::unique_ptr<IGenerator<T>>(pf::make_unique<FilterGenerator<T,
  3440. Predicate>>(
  3441. std::forward<Predicate>(pred),
  3442. std::move(generator))));
  3443. }
  3444. template<typename T>
  3445. class RepeatGenerator : public IGenerator<T> {
  3446. static_assert(!std::is_same<T, bool>::value,
  3447. "RepeatGenerator currently does not support bools"
  3448. "because of std::vector<bool> specialization");
  3449. GeneratorWrapper<T> m_generator;
  3450. mutable std::vector<T> m_returned;
  3451. size_t m_target_repeats;
  3452. size_t m_current_repeat = 0;
  3453. size_t m_repeat_index = 0;
  3454. public:
  3455. RepeatGenerator(size_t repeats, GeneratorWrapper<T> &&generator) :
  3456. m_generator(std::move(generator)),
  3457. m_target_repeats(repeats) {
  3458. assert(m_target_repeats > 0 && "Repeat generator must repeat at least once");
  3459. }
  3460. T const &get() const override {
  3461. if (m_current_repeat == 0) {
  3462. m_returned.push_back(m_generator.get());
  3463. return m_returned.back();
  3464. }
  3465. return m_returned[m_repeat_index];
  3466. }
  3467. bool next() override {
  3468. // There are 2 basic cases:
  3469. // 1) We are still reading the generator
  3470. // 2) We are reading our own cache
  3471. // In the first case, we need to poke the underlying generator.
  3472. // If it happily moves, we are left in that state, otherwise it is time to start reading from our cache
  3473. if (m_current_repeat == 0) {
  3474. const auto success = m_generator.next();
  3475. if (!success) {
  3476. ++m_current_repeat;
  3477. }
  3478. return m_current_repeat < m_target_repeats;
  3479. }
  3480. // In the second case, we need to move indices forward and check that we haven't run up against the end
  3481. ++m_repeat_index;
  3482. if (m_repeat_index == m_returned.size()) {
  3483. m_repeat_index = 0;
  3484. ++m_current_repeat;
  3485. }
  3486. return m_current_repeat < m_target_repeats;
  3487. }
  3488. };
  3489. template<typename T>
  3490. GeneratorWrapper<T> repeat(size_t repeats, GeneratorWrapper<T> &&generator) {
  3491. return GeneratorWrapper<T>(pf::make_unique<RepeatGenerator<T>>(repeats, std::move(generator)));
  3492. }
  3493. template<typename T, typename U, typename Func>
  3494. class MapGenerator : public IGenerator<T> {
  3495. // TBD: provide static assert for mapping function, for friendly error message
  3496. GeneratorWrapper<U> m_generator;
  3497. Func m_function;
  3498. // To avoid returning dangling reference, we have to save the values
  3499. T m_cache;
  3500. public:
  3501. template<typename F2 = Func>
  3502. MapGenerator(F2 &&function, GeneratorWrapper<U> &&generator) :
  3503. m_generator(std::move(generator)),
  3504. m_function(std::forward<F2>(function)),
  3505. m_cache(m_function(m_generator.get())) {}
  3506. T const &get() const override {
  3507. return m_cache;
  3508. }
  3509. bool next() override {
  3510. const auto success = m_generator.next();
  3511. if (success) {
  3512. m_cache = m_function(m_generator.get());
  3513. }
  3514. return success;
  3515. }
  3516. };
  3517. #if defined(__cpp_lib_is_invocable) && __cpp_lib_is_invocable >= 201703
  3518. // std::result_of is deprecated in C++17 and removed in C++20. Hence, it is
  3519. // replaced with std::invoke_result here. Also *_t format is preferred over
  3520. // typename *::type format.
  3521. template <typename Func, typename U>
  3522. using MapFunctionReturnType = std::remove_reference_t<std::remove_cv_t<std::invoke_result_t<Func, U>>>;
  3523. #else
  3524. template<typename Func, typename U>
  3525. using MapFunctionReturnType = typename std::remove_reference<typename std::remove_cv<typename std::result_of<
  3526. Func(U)>::type>::type>::type;
  3527. #endif
  3528. template<typename Func, typename U, typename T = MapFunctionReturnType<Func, U>>
  3529. GeneratorWrapper<T> map(Func &&function, GeneratorWrapper<U> &&generator) {
  3530. return GeneratorWrapper<T>(
  3531. pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(function), std::move(generator))
  3532. );
  3533. }
  3534. template<typename T, typename U, typename Func>
  3535. GeneratorWrapper<T> map(Func &&function, GeneratorWrapper<U> &&generator) {
  3536. return GeneratorWrapper<T>(
  3537. pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(function), std::move(generator))
  3538. );
  3539. }
  3540. template<typename T>
  3541. class ChunkGenerator final : public IGenerator<std::vector<T>> {
  3542. std::vector<T> m_chunk;
  3543. size_t m_chunk_size;
  3544. GeneratorWrapper<T> m_generator;
  3545. bool m_used_up = false;
  3546. public:
  3547. ChunkGenerator(size_t size, GeneratorWrapper<T> generator) :
  3548. m_chunk_size(size), m_generator(std::move(generator)) {
  3549. m_chunk.reserve(m_chunk_size);
  3550. if (m_chunk_size != 0) {
  3551. m_chunk.push_back(m_generator.get());
  3552. for (size_t i = 1; i < m_chunk_size; ++i) {
  3553. if (!m_generator.next()) {
  3554. Catch::throw_exception(GeneratorException(
  3555. "Not enough values to initialize the first chunk"));
  3556. }
  3557. m_chunk.push_back(m_generator.get());
  3558. }
  3559. }
  3560. }
  3561. std::vector<T> const &get() const override {
  3562. return m_chunk;
  3563. }
  3564. bool next() override {
  3565. m_chunk.clear();
  3566. for (size_t idx = 0; idx < m_chunk_size; ++idx) {
  3567. if (!m_generator.next()) {
  3568. return false;
  3569. }
  3570. m_chunk.push_back(m_generator.get());
  3571. }
  3572. return true;
  3573. }
  3574. };
  3575. template<typename T>
  3576. GeneratorWrapper<std::vector<T>> chunk(size_t size, GeneratorWrapper<T> &&generator) {
  3577. return GeneratorWrapper<std::vector<T>>(
  3578. pf::make_unique<ChunkGenerator<T>>(size, std::move(generator))
  3579. );
  3580. }
  3581. } // namespace Generators
  3582. } // namespace Catch
  3583. // end catch_generators_generic.hpp
  3584. // start catch_generators_specific.hpp
  3585. // start catch_context.h
  3586. #include <memory>
  3587. namespace Catch {
  3588. struct IResultCapture;
  3589. struct IRunner;
  3590. struct IConfig;
  3591. struct IMutableContext;
  3592. using IConfigPtr = std::shared_ptr<IConfig const>;
  3593. struct IContext {
  3594. virtual ~IContext();
  3595. virtual IResultCapture *getResultCapture() = 0;
  3596. virtual IRunner *getRunner() = 0;
  3597. virtual IConfigPtr const &getConfig() const = 0;
  3598. };
  3599. struct IMutableContext : IContext {
  3600. virtual ~IMutableContext();
  3601. virtual void setResultCapture(IResultCapture *resultCapture) = 0;
  3602. virtual void setRunner(IRunner *runner) = 0;
  3603. virtual void setConfig(IConfigPtr const &config) = 0;
  3604. private:
  3605. static IMutableContext *currentContext;
  3606. friend IMutableContext &getCurrentMutableContext();
  3607. friend void cleanUpContext();
  3608. static void createContext();
  3609. };
  3610. inline IMutableContext &getCurrentMutableContext() {
  3611. if (!IMutableContext::currentContext)
  3612. IMutableContext::createContext();
  3613. return *IMutableContext::currentContext;
  3614. }
  3615. inline IContext &getCurrentContext() {
  3616. return getCurrentMutableContext();
  3617. }
  3618. void cleanUpContext();
  3619. }
  3620. // end catch_context.h
  3621. // start catch_interfaces_config.h
  3622. // start catch_option.hpp
  3623. namespace Catch {
  3624. // An optional type
  3625. template<typename T>
  3626. class Option {
  3627. public:
  3628. Option() : nullableValue(nullptr) {}
  3629. Option(T const &_value)
  3630. : nullableValue(new(storage) T(_value)) {}
  3631. Option(Option const &_other)
  3632. : nullableValue(_other ? new(storage) T(*_other) : nullptr) {}
  3633. ~Option() {
  3634. reset();
  3635. }
  3636. Option &operator=(Option const &_other) {
  3637. if (&_other != this) {
  3638. reset();
  3639. if (_other)
  3640. nullableValue = new(storage) T(*_other);
  3641. }
  3642. return *this;
  3643. }
  3644. Option &operator=(T const &_value) {
  3645. reset();
  3646. nullableValue = new(storage) T(_value);
  3647. return *this;
  3648. }
  3649. void reset() {
  3650. if (nullableValue)
  3651. nullableValue->~T();
  3652. nullableValue = nullptr;
  3653. }
  3654. T &operator*() { return *nullableValue; }
  3655. T const &operator*() const { return *nullableValue; }
  3656. T *operator->() { return nullableValue; }
  3657. const T *operator->() const { return nullableValue; }
  3658. T valueOr(T const &defaultValue) const {
  3659. return nullableValue ? *nullableValue : defaultValue;
  3660. }
  3661. bool some() const { return nullableValue != nullptr; }
  3662. bool none() const { return nullableValue == nullptr; }
  3663. bool operator!() const { return nullableValue == nullptr; }
  3664. explicit operator bool() const {
  3665. return some();
  3666. }
  3667. private:
  3668. T *nullableValue;
  3669. alignas(alignof(T)) char storage[sizeof(T)];
  3670. };
  3671. } // end namespace Catch
  3672. // end catch_option.hpp
  3673. #include <iosfwd>
  3674. #include <string>
  3675. #include <vector>
  3676. #include <memory>
  3677. namespace Catch {
  3678. enum class Verbosity {
  3679. Quiet = 0,
  3680. Normal,
  3681. High
  3682. };
  3683. struct WarnAbout {
  3684. enum What {
  3685. Nothing = 0x00,
  3686. NoAssertions = 0x01,
  3687. NoTests = 0x02
  3688. };
  3689. };
  3690. struct ShowDurations {
  3691. enum OrNot {
  3692. DefaultForReporter,
  3693. Always,
  3694. Never
  3695. };
  3696. };
  3697. struct RunTests {
  3698. enum InWhatOrder {
  3699. InDeclarationOrder,
  3700. InLexicographicalOrder,
  3701. InRandomOrder
  3702. };
  3703. };
  3704. struct UseColour {
  3705. enum YesOrNo {
  3706. Auto,
  3707. Yes,
  3708. No
  3709. };
  3710. };
  3711. struct WaitForKeypress {
  3712. enum When {
  3713. Never,
  3714. BeforeStart = 1,
  3715. BeforeExit = 2,
  3716. BeforeStartAndExit = BeforeStart | BeforeExit
  3717. };
  3718. };
  3719. class TestSpec;
  3720. struct IConfig : NonCopyable {
  3721. virtual ~IConfig();
  3722. virtual bool allowThrows() const = 0;
  3723. virtual std::ostream &stream() const = 0;
  3724. virtual std::string name() const = 0;
  3725. virtual bool includeSuccessfulResults() const = 0;
  3726. virtual bool shouldDebugBreak() const = 0;
  3727. virtual bool warnAboutMissingAssertions() const = 0;
  3728. virtual bool warnAboutNoTests() const = 0;
  3729. virtual int abortAfter() const = 0;
  3730. virtual bool showInvisibles() const = 0;
  3731. virtual ShowDurations::OrNot showDurations() const = 0;
  3732. virtual TestSpec const &testSpec() const = 0;
  3733. virtual bool hasTestFilters() const = 0;
  3734. virtual std::vector<std::string> const &getTestsOrTags() const = 0;
  3735. virtual RunTests::InWhatOrder runOrder() const = 0;
  3736. virtual unsigned int rngSeed() const = 0;
  3737. virtual UseColour::YesOrNo useColour() const = 0;
  3738. virtual std::vector<std::string> const &getSectionsToRun() const = 0;
  3739. virtual Verbosity verbosity() const = 0;
  3740. virtual bool benchmarkNoAnalysis() const = 0;
  3741. virtual int benchmarkSamples() const = 0;
  3742. virtual double benchmarkConfidenceInterval() const = 0;
  3743. virtual unsigned int benchmarkResamples() const = 0;
  3744. };
  3745. using IConfigPtr = std::shared_ptr<IConfig const>;
  3746. }
  3747. // end catch_interfaces_config.h
  3748. #include <random>
  3749. namespace Catch {
  3750. namespace Generators {
  3751. template<typename Float>
  3752. class RandomFloatingGenerator final : public IGenerator<Float> {
  3753. // FIXME: What is the right seed?
  3754. std::minstd_rand m_rand;
  3755. std::uniform_real_distribution<Float> m_dist;
  3756. Float m_current_number;
  3757. public:
  3758. RandomFloatingGenerator(Float a, Float b) :
  3759. m_rand(getCurrentContext().getConfig()->rngSeed()),
  3760. m_dist(a, b) {
  3761. static_cast<void>(next());
  3762. }
  3763. Float const &get() const override {
  3764. return m_current_number;
  3765. }
  3766. bool next() override {
  3767. m_current_number = m_dist(m_rand);
  3768. return true;
  3769. }
  3770. };
  3771. template<typename Integer>
  3772. class RandomIntegerGenerator final : public IGenerator<Integer> {
  3773. std::minstd_rand m_rand;
  3774. std::uniform_int_distribution<Integer> m_dist;
  3775. Integer m_current_number;
  3776. public:
  3777. RandomIntegerGenerator(Integer a, Integer b) :
  3778. m_rand(getCurrentContext().getConfig()->rngSeed()),
  3779. m_dist(a, b) {
  3780. static_cast<void>(next());
  3781. }
  3782. Integer const &get() const override {
  3783. return m_current_number;
  3784. }
  3785. bool next() override {
  3786. m_current_number = m_dist(m_rand);
  3787. return true;
  3788. }
  3789. };
  3790. // TODO: Ideally this would be also constrained against the various char types,
  3791. // but I don't expect users to run into that in practice.
  3792. template<typename T>
  3793. typename std::enable_if<std::is_integral<T>::value && !std::is_same<T, bool>::value,
  3794. GeneratorWrapper<T>>::type
  3795. random(T a, T b) {
  3796. return GeneratorWrapper<T>(
  3797. pf::make_unique<RandomIntegerGenerator<T>>(a, b)
  3798. );
  3799. }
  3800. template<typename T>
  3801. typename std::enable_if<std::is_floating_point<T>::value,
  3802. GeneratorWrapper<T>>::type
  3803. random(T a, T b) {
  3804. return GeneratorWrapper<T>(
  3805. pf::make_unique<RandomFloatingGenerator<T>>(a, b)
  3806. );
  3807. }
  3808. template<typename T>
  3809. class RangeGenerator final : public IGenerator<T> {
  3810. T m_current;
  3811. T m_end;
  3812. T m_step;
  3813. bool m_positive;
  3814. public:
  3815. RangeGenerator(T const &start, T const &end, T const &step) :
  3816. m_current(start),
  3817. m_end(end),
  3818. m_step(step),
  3819. m_positive(m_step > T(0)) {
  3820. assert(m_current != m_end && "Range start and end cannot be equal");
  3821. assert(m_step != T(0) && "Step size cannot be zero");
  3822. assert(((m_positive && m_current <= m_end) || (!m_positive && m_current >= m_end))
  3823. && "Step moves away from end");
  3824. }
  3825. RangeGenerator(T const &start, T const &end) :
  3826. RangeGenerator(start, end, (start < end) ? T(1) : T(-1)) {}
  3827. T const &get() const override {
  3828. return m_current;
  3829. }
  3830. bool next() override {
  3831. m_current += m_step;
  3832. return (m_positive) ? (m_current < m_end) : (m_current > m_end);
  3833. }
  3834. };
  3835. template<typename T>
  3836. GeneratorWrapper<T> range(T const &start, T const &end, T const &step) {
  3837. static_assert(std::is_integral<T>::value && !std::is_same<T, bool>::value,
  3838. "Type must be an integer");
  3839. return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end, step));
  3840. }
  3841. template<typename T>
  3842. GeneratorWrapper<T> range(T const &start, T const &end) {
  3843. static_assert(std::is_integral<T>::value && !std::is_same<T, bool>::value,
  3844. "Type must be an integer");
  3845. return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end));
  3846. }
  3847. } // namespace Generators
  3848. } // namespace Catch
  3849. // end catch_generators_specific.hpp
  3850. // These files are included here so the single_include script doesn't put them
  3851. // in the conditionally compiled sections
  3852. // start catch_test_case_info.h
  3853. #include <string>
  3854. #include <vector>
  3855. #include <memory>
  3856. #ifdef __clang__
  3857. #pragma clang diagnostic push
  3858. #pragma clang diagnostic ignored "-Wpadded"
  3859. #endif
  3860. namespace Catch {
  3861. struct ITestInvoker;
  3862. struct TestCaseInfo {
  3863. enum SpecialProperties {
  3864. None = 0,
  3865. IsHidden = 1 << 1,
  3866. ShouldFail = 1 << 2,
  3867. MayFail = 1 << 3,
  3868. Throws = 1 << 4,
  3869. NonPortable = 1 << 5,
  3870. Benchmark = 1 << 6
  3871. };
  3872. TestCaseInfo(std::string const &_name,
  3873. std::string const &_className,
  3874. std::string const &_description,
  3875. std::vector<std::string> const &_tags,
  3876. SourceLineInfo const &_lineInfo);
  3877. friend void setTags(TestCaseInfo &testCaseInfo, std::vector<std::string> tags);
  3878. bool isHidden() const;
  3879. bool throws() const;
  3880. bool okToFail() const;
  3881. bool expectedToFail() const;
  3882. std::string tagsAsString() const;
  3883. std::string name;
  3884. std::string className;
  3885. std::string description;
  3886. std::vector<std::string> tags;
  3887. std::vector<std::string> lcaseTags;
  3888. SourceLineInfo lineInfo;
  3889. SpecialProperties properties;
  3890. };
  3891. class TestCase : public TestCaseInfo {
  3892. public:
  3893. TestCase(ITestInvoker *testCase, TestCaseInfo &&info);
  3894. TestCase withName(std::string const &_newName) const;
  3895. void invoke() const;
  3896. TestCaseInfo const &getTestCaseInfo() const;
  3897. bool operator==(TestCase const &other) const;
  3898. bool operator<(TestCase const &other) const;
  3899. private:
  3900. std::shared_ptr<ITestInvoker> test;
  3901. };
  3902. TestCase makeTestCase(ITestInvoker *testCase,
  3903. std::string const &className,
  3904. NameAndTags const &nameAndTags,
  3905. SourceLineInfo const &lineInfo);
  3906. }
  3907. #ifdef __clang__
  3908. #pragma clang diagnostic pop
  3909. #endif
  3910. // end catch_test_case_info.h
  3911. // start catch_interfaces_runner.h
  3912. namespace Catch {
  3913. struct IRunner {
  3914. virtual ~IRunner();
  3915. virtual bool aborting() const = 0;
  3916. };
  3917. }
  3918. // end catch_interfaces_runner.h
  3919. #ifdef __OBJC__
  3920. // start catch_objc.hpp
  3921. #import <objc/runtime.h>
  3922. #include <string>
  3923. // NB. Any general catch headers included here must be included
  3924. // in catch.hpp first to make sure they are included by the single
  3925. // header for non obj-usage
  3926. ///////////////////////////////////////////////////////////////////////////////
  3927. // This protocol is really only here for (self) documenting purposes, since
  3928. // all its methods are optional.
  3929. @protocol OcFixture
  3930. @optional
  3931. -(void) setUp;
  3932. -(void) tearDown;
  3933. @end
  3934. namespace Catch {
  3935. class OcMethod : public ITestInvoker {
  3936. public:
  3937. OcMethod( Class cls, SEL sel ) : m_cls( cls ), m_sel( sel ) {}
  3938. virtual void invoke() const {
  3939. id obj = [[m_cls alloc] init];
  3940. performOptionalSelector( obj, @selector(setUp) );
  3941. performOptionalSelector( obj, m_sel );
  3942. performOptionalSelector( obj, @selector(tearDown) );
  3943. arcSafeRelease( obj );
  3944. }
  3945. private:
  3946. virtual ~OcMethod() {}
  3947. Class m_cls;
  3948. SEL m_sel;
  3949. };
  3950. namespace Detail{
  3951. inline std::string getAnnotation( Class cls,
  3952. std::string const& annotationName,
  3953. std::string const& testCaseName ) {
  3954. NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()];
  3955. SEL sel = NSSelectorFromString( selStr );
  3956. arcSafeRelease( selStr );
  3957. id value = performOptionalSelector( cls, sel );
  3958. if( value )
  3959. return [(NSString*)value UTF8String];
  3960. return "";
  3961. }
  3962. }
  3963. inline std::size_t registerTestMethods() {
  3964. std::size_t noTestMethods = 0;
  3965. int noClasses = objc_getClassList( nullptr, 0 );
  3966. Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc( sizeof(Class) * noClasses);
  3967. objc_getClassList( classes, noClasses );
  3968. for( int c = 0; c < noClasses; c++ ) {
  3969. Class cls = classes[c];
  3970. {
  3971. u_int count;
  3972. Method* methods = class_copyMethodList( cls, &count );
  3973. for( u_int m = 0; m < count ; m++ ) {
  3974. SEL selector = method_getName(methods[m]);
  3975. std::string methodName = sel_getName(selector);
  3976. if( startsWith( methodName, "Catch_TestCase_" ) ) {
  3977. std::string testCaseName = methodName.substr( 15 );
  3978. std::string name = Detail::getAnnotation( cls, "Name", testCaseName );
  3979. std::string desc = Detail::getAnnotation( cls, "Description", testCaseName );
  3980. const char* className = class_getName( cls );
  3981. getMutableRegistryHub().registerTest( makeTestCase( new OcMethod( cls, selector ), className, NameAndTags( name.c_str(), desc.c_str() ), SourceLineInfo("",0) ) );
  3982. noTestMethods++;
  3983. }
  3984. }
  3985. free(methods);
  3986. }
  3987. }
  3988. return noTestMethods;
  3989. }
  3990. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  3991. namespace Matchers {
  3992. namespace Impl {
  3993. namespace NSStringMatchers {
  3994. struct StringHolder : MatcherBase<NSString*>{
  3995. StringHolder( NSString* substr ) : m_substr( [substr copy] ){}
  3996. StringHolder( StringHolder const& other ) : m_substr( [other.m_substr copy] ){}
  3997. StringHolder() {
  3998. arcSafeRelease( m_substr );
  3999. }
  4000. bool match( NSString* str ) const override {
  4001. return false;
  4002. }
  4003. NSString* CATCH_ARC_STRONG m_substr;
  4004. };
  4005. struct Equals : StringHolder {
  4006. Equals( NSString* substr ) : StringHolder( substr ){}
  4007. bool match( NSString* str ) const override {
  4008. return (str != nil || m_substr == nil ) &&
  4009. [str isEqualToString:m_substr];
  4010. }
  4011. std::string describe() const override {
  4012. return "equals string: " + Catch::Detail::stringify( m_substr );
  4013. }
  4014. };
  4015. struct Contains : StringHolder {
  4016. Contains( NSString* substr ) : StringHolder( substr ){}
  4017. bool match( NSString* str ) const override {
  4018. return (str != nil || m_substr == nil ) &&
  4019. [str rangeOfString:m_substr].location != NSNotFound;
  4020. }
  4021. std::string describe() const override {
  4022. return "contains string: " + Catch::Detail::stringify( m_substr );
  4023. }
  4024. };
  4025. struct StartsWith : StringHolder {
  4026. StartsWith( NSString* substr ) : StringHolder( substr ){}
  4027. bool match( NSString* str ) const override {
  4028. return (str != nil || m_substr == nil ) &&
  4029. [str rangeOfString:m_substr].location == 0;
  4030. }
  4031. std::string describe() const override {
  4032. return "starts with: " + Catch::Detail::stringify( m_substr );
  4033. }
  4034. };
  4035. struct EndsWith : StringHolder {
  4036. EndsWith( NSString* substr ) : StringHolder( substr ){}
  4037. bool match( NSString* str ) const override {
  4038. return (str != nil || m_substr == nil ) &&
  4039. [str rangeOfString:m_substr].location == [str length] - [m_substr length];
  4040. }
  4041. std::string describe() const override {
  4042. return "ends with: " + Catch::Detail::stringify( m_substr );
  4043. }
  4044. };
  4045. } // namespace NSStringMatchers
  4046. } // namespace Impl
  4047. inline Impl::NSStringMatchers::Equals
  4048. Equals( NSString* substr ){ return Impl::NSStringMatchers::Equals( substr ); }
  4049. inline Impl::NSStringMatchers::Contains
  4050. Contains( NSString* substr ){ return Impl::NSStringMatchers::Contains( substr ); }
  4051. inline Impl::NSStringMatchers::StartsWith
  4052. StartsWith( NSString* substr ){ return Impl::NSStringMatchers::StartsWith( substr ); }
  4053. inline Impl::NSStringMatchers::EndsWith
  4054. EndsWith( NSString* substr ){ return Impl::NSStringMatchers::EndsWith( substr ); }
  4055. } // namespace Matchers
  4056. using namespace Matchers;
  4057. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  4058. } // namespace Catch
  4059. ///////////////////////////////////////////////////////////////////////////////
  4060. #define OC_MAKE_UNIQUE_NAME( root, uniqueSuffix ) root##uniqueSuffix
  4061. #define OC_TEST_CASE2( name, desc, uniqueSuffix ) \
  4062. +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Name_test_, uniqueSuffix ) \
  4063. { \
  4064. return @ name; \
  4065. } \
  4066. +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Description_test_, uniqueSuffix ) \
  4067. { \
  4068. return @ desc; \
  4069. } \
  4070. -(void) OC_MAKE_UNIQUE_NAME( Catch_TestCase_test_, uniqueSuffix )
  4071. #define OC_TEST_CASE( name, desc ) OC_TEST_CASE2( name, desc, __LINE__ )
  4072. // end catch_objc.hpp
  4073. #endif
  4074. // Benchmarking needs the externally-facing parts of reporters to work
  4075. #if defined(CATCH_CONFIG_EXTERNAL_INTERFACES) || defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  4076. // start catch_external_interfaces.h
  4077. // start catch_reporter_bases.hpp
  4078. // start catch_interfaces_reporter.h
  4079. // start catch_config.hpp
  4080. // start catch_test_spec_parser.h
  4081. #ifdef __clang__
  4082. #pragma clang diagnostic push
  4083. #pragma clang diagnostic ignored "-Wpadded"
  4084. #endif
  4085. // start catch_test_spec.h
  4086. #ifdef __clang__
  4087. #pragma clang diagnostic push
  4088. #pragma clang diagnostic ignored "-Wpadded"
  4089. #endif
  4090. // start catch_wildcard_pattern.h
  4091. namespace Catch
  4092. {
  4093. class WildcardPattern {
  4094. enum WildcardPosition {
  4095. NoWildcard = 0,
  4096. WildcardAtStart = 1,
  4097. WildcardAtEnd = 2,
  4098. WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd
  4099. };
  4100. public:
  4101. WildcardPattern( std::string const& pattern, CaseSensitive::Choice caseSensitivity );
  4102. virtual ~WildcardPattern() = default;
  4103. virtual bool matches( std::string const& str ) const;
  4104. private:
  4105. std::string adjustCase( std::string const& str ) const;
  4106. CaseSensitive::Choice m_caseSensitivity;
  4107. WildcardPosition m_wildcard = NoWildcard;
  4108. std::string m_pattern;
  4109. };
  4110. }
  4111. // end catch_wildcard_pattern.h
  4112. #include <string>
  4113. #include <vector>
  4114. #include <memory>
  4115. namespace Catch {
  4116. struct IConfig;
  4117. class TestSpec {
  4118. class Pattern {
  4119. public:
  4120. explicit Pattern( std::string const& name );
  4121. virtual ~Pattern();
  4122. virtual bool matches( TestCaseInfo const& testCase ) const = 0;
  4123. std::string const& name() const;
  4124. private:
  4125. std::string const m_name;
  4126. };
  4127. using PatternPtr = std::shared_ptr<Pattern>;
  4128. class NamePattern : public Pattern {
  4129. public:
  4130. explicit NamePattern( std::string const& name, std::string const& filterString );
  4131. bool matches( TestCaseInfo const& testCase ) const override;
  4132. private:
  4133. WildcardPattern m_wildcardPattern;
  4134. };
  4135. class TagPattern : public Pattern {
  4136. public:
  4137. explicit TagPattern( std::string const& tag, std::string const& filterString );
  4138. bool matches( TestCaseInfo const& testCase ) const override;
  4139. private:
  4140. std::string m_tag;
  4141. };
  4142. class ExcludedPattern : public Pattern {
  4143. public:
  4144. explicit ExcludedPattern( PatternPtr const& underlyingPattern );
  4145. bool matches( TestCaseInfo const& testCase ) const override;
  4146. private:
  4147. PatternPtr m_underlyingPattern;
  4148. };
  4149. struct Filter {
  4150. std::vector<PatternPtr> m_patterns;
  4151. bool matches( TestCaseInfo const& testCase ) const;
  4152. std::string name() const;
  4153. };
  4154. public:
  4155. struct FilterMatch {
  4156. std::string name;
  4157. std::vector<TestCase const*> tests;
  4158. };
  4159. using Matches = std::vector<FilterMatch>;
  4160. bool hasFilters() const;
  4161. bool matches( TestCaseInfo const& testCase ) const;
  4162. Matches matchesByFilter( std::vector<TestCase> const& testCases, IConfig const& config ) const;
  4163. private:
  4164. std::vector<Filter> m_filters;
  4165. friend class TestSpecParser;
  4166. };
  4167. }
  4168. #ifdef __clang__
  4169. #pragma clang diagnostic pop
  4170. #endif
  4171. // end catch_test_spec.h
  4172. // start catch_interfaces_tag_alias_registry.h
  4173. #include <string>
  4174. namespace Catch {
  4175. struct TagAlias;
  4176. struct ITagAliasRegistry {
  4177. virtual ~ITagAliasRegistry();
  4178. // Nullptr if not present
  4179. virtual TagAlias const* find( std::string const& alias ) const = 0;
  4180. virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const = 0;
  4181. static ITagAliasRegistry const& get();
  4182. };
  4183. } // end namespace Catch
  4184. // end catch_interfaces_tag_alias_registry.h
  4185. namespace Catch {
  4186. class TestSpecParser {
  4187. enum Mode{ None, Name, QuotedName, Tag, EscapedName };
  4188. Mode m_mode = None;
  4189. bool m_exclusion = false;
  4190. std::size_t m_pos = 0;
  4191. std::string m_arg;
  4192. std::string m_substring;
  4193. std::string m_patternName;
  4194. std::vector<std::size_t> m_escapeChars;
  4195. TestSpec::Filter m_currentFilter;
  4196. TestSpec m_testSpec;
  4197. ITagAliasRegistry const* m_tagAliases = nullptr;
  4198. public:
  4199. TestSpecParser( ITagAliasRegistry const& tagAliases );
  4200. TestSpecParser& parse( std::string const& arg );
  4201. TestSpec testSpec();
  4202. private:
  4203. void visitChar( char c );
  4204. void startNewMode( Mode mode );
  4205. bool processNoneChar( char c );
  4206. void processNameChar( char c );
  4207. bool processOtherChar( char c );
  4208. void endMode();
  4209. void escape();
  4210. bool isControlChar( char c ) const;
  4211. template<typename T>
  4212. void addPattern() {
  4213. std::string token = m_patternName;
  4214. for( std::size_t i = 0; i < m_escapeChars.size(); ++i )
  4215. token = token.substr( 0, m_escapeChars[i] - i ) + token.substr( m_escapeChars[i] -i +1 );
  4216. m_escapeChars.clear();
  4217. if( startsWith( token, "exclude:" ) ) {
  4218. m_exclusion = true;
  4219. token = token.substr( 8 );
  4220. }
  4221. if( !token.empty() ) {
  4222. TestSpec::PatternPtr pattern = std::make_shared<T>( token, m_substring );
  4223. if( m_exclusion )
  4224. pattern = std::make_shared<TestSpec::ExcludedPattern>( pattern );
  4225. m_currentFilter.m_patterns.push_back( pattern );
  4226. }
  4227. m_substring.clear();
  4228. m_patternName.clear();
  4229. m_exclusion = false;
  4230. m_mode = None;
  4231. }
  4232. void addFilter();
  4233. };
  4234. TestSpec parseTestSpec( std::string const& arg );
  4235. } // namespace Catch
  4236. #ifdef __clang__
  4237. #pragma clang diagnostic pop
  4238. #endif
  4239. // end catch_test_spec_parser.h
  4240. // Libstdc++ doesn't like incomplete classes for unique_ptr
  4241. #include <memory>
  4242. #include <vector>
  4243. #include <string>
  4244. #ifndef CATCH_CONFIG_CONSOLE_WIDTH
  4245. #define CATCH_CONFIG_CONSOLE_WIDTH 80
  4246. #endif
  4247. namespace Catch {
  4248. struct IStream;
  4249. struct ConfigData {
  4250. bool listTests = false;
  4251. bool listTags = false;
  4252. bool listReporters = false;
  4253. bool listTestNamesOnly = false;
  4254. bool showSuccessfulTests = false;
  4255. bool shouldDebugBreak = false;
  4256. bool noThrow = false;
  4257. bool showHelp = false;
  4258. bool showInvisibles = false;
  4259. bool filenamesAsTags = false;
  4260. bool libIdentify = false;
  4261. int abortAfter = -1;
  4262. unsigned int rngSeed = 0;
  4263. bool benchmarkNoAnalysis = false;
  4264. unsigned int benchmarkSamples = 100;
  4265. double benchmarkConfidenceInterval = 0.95;
  4266. unsigned int benchmarkResamples = 100000;
  4267. Verbosity verbosity = Verbosity::Normal;
  4268. WarnAbout::What warnings = WarnAbout::Nothing;
  4269. ShowDurations::OrNot showDurations = ShowDurations::DefaultForReporter;
  4270. RunTests::InWhatOrder runOrder = RunTests::InDeclarationOrder;
  4271. UseColour::YesOrNo useColour = UseColour::Auto;
  4272. WaitForKeypress::When waitForKeypress = WaitForKeypress::Never;
  4273. std::string outputFilename;
  4274. std::string name;
  4275. std::string processName;
  4276. #ifndef CATCH_CONFIG_DEFAULT_REPORTER
  4277. #define CATCH_CONFIG_DEFAULT_REPORTER "console"
  4278. #endif
  4279. std::string reporterName = CATCH_CONFIG_DEFAULT_REPORTER;
  4280. #undef CATCH_CONFIG_DEFAULT_REPORTER
  4281. std::vector<std::string> testsOrTags;
  4282. std::vector<std::string> sectionsToRun;
  4283. };
  4284. class Config : public IConfig {
  4285. public:
  4286. Config() = default;
  4287. Config( ConfigData const& data );
  4288. virtual ~Config() = default;
  4289. std::string const& getFilename() const;
  4290. bool listTests() const;
  4291. bool listTestNamesOnly() const;
  4292. bool listTags() const;
  4293. bool listReporters() const;
  4294. std::string getProcessName() const;
  4295. std::string const& getReporterName() const;
  4296. std::vector<std::string> const& getTestsOrTags() const override;
  4297. std::vector<std::string> const& getSectionsToRun() const override;
  4298. TestSpec const& testSpec() const override;
  4299. bool hasTestFilters() const override;
  4300. bool showHelp() const;
  4301. // IConfig interface
  4302. bool allowThrows() const override;
  4303. std::ostream& stream() const override;
  4304. std::string name() const override;
  4305. bool includeSuccessfulResults() const override;
  4306. bool warnAboutMissingAssertions() const override;
  4307. bool warnAboutNoTests() const override;
  4308. ShowDurations::OrNot showDurations() const override;
  4309. RunTests::InWhatOrder runOrder() const override;
  4310. unsigned int rngSeed() const override;
  4311. UseColour::YesOrNo useColour() const override;
  4312. bool shouldDebugBreak() const override;
  4313. int abortAfter() const override;
  4314. bool showInvisibles() const override;
  4315. Verbosity verbosity() const override;
  4316. bool benchmarkNoAnalysis() const override;
  4317. int benchmarkSamples() const override;
  4318. double benchmarkConfidenceInterval() const override;
  4319. unsigned int benchmarkResamples() const override;
  4320. private:
  4321. IStream const* openStream();
  4322. ConfigData m_data;
  4323. std::unique_ptr<IStream const> m_stream;
  4324. TestSpec m_testSpec;
  4325. bool m_hasTestFilters = false;
  4326. };
  4327. } // end namespace Catch
  4328. // end catch_config.hpp
  4329. // start catch_assertionresult.h
  4330. #include <string>
  4331. namespace Catch {
  4332. struct AssertionResultData
  4333. {
  4334. AssertionResultData() = delete;
  4335. AssertionResultData( ResultWas::OfType _resultType, LazyExpression const& _lazyExpression );
  4336. std::string message;
  4337. mutable std::string reconstructedExpression;
  4338. LazyExpression lazyExpression;
  4339. ResultWas::OfType resultType;
  4340. std::string reconstructExpression() const;
  4341. };
  4342. class AssertionResult {
  4343. public:
  4344. AssertionResult() = delete;
  4345. AssertionResult( AssertionInfo const& info, AssertionResultData const& data );
  4346. bool isOk() const;
  4347. bool succeeded() const;
  4348. ResultWas::OfType getResultType() const;
  4349. bool hasExpression() const;
  4350. bool hasMessage() const;
  4351. std::string getExpression() const;
  4352. std::string getExpressionInMacro() const;
  4353. bool hasExpandedExpression() const;
  4354. std::string getExpandedExpression() const;
  4355. std::string getMessage() const;
  4356. SourceLineInfo getSourceInfo() const;
  4357. StringRef getTestMacroName() const;
  4358. //protected:
  4359. AssertionInfo m_info;
  4360. AssertionResultData m_resultData;
  4361. };
  4362. } // end namespace Catch
  4363. // end catch_assertionresult.h
  4364. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  4365. // start catch_estimate.hpp
  4366. // Statistics estimates
  4367. namespace Catch {
  4368. namespace Benchmark {
  4369. template <typename Duration>
  4370. struct Estimate {
  4371. Duration point;
  4372. Duration lower_bound;
  4373. Duration upper_bound;
  4374. double confidence_interval;
  4375. template <typename Duration2>
  4376. operator Estimate<Duration2>() const {
  4377. return { point, lower_bound, upper_bound, confidence_interval };
  4378. }
  4379. };
  4380. } // namespace Benchmark
  4381. } // namespace Catch
  4382. // end catch_estimate.hpp
  4383. // start catch_outlier_classification.hpp
  4384. // Outlier information
  4385. namespace Catch {
  4386. namespace Benchmark {
  4387. struct OutlierClassification {
  4388. int samples_seen = 0;
  4389. int low_severe = 0; // more than 3 times IQR below Q1
  4390. int low_mild = 0; // 1.5 to 3 times IQR below Q1
  4391. int high_mild = 0; // 1.5 to 3 times IQR above Q3
  4392. int high_severe = 0; // more than 3 times IQR above Q3
  4393. int total() const {
  4394. return low_severe + low_mild + high_mild + high_severe;
  4395. }
  4396. };
  4397. } // namespace Benchmark
  4398. } // namespace Catch
  4399. // end catch_outlier_classification.hpp
  4400. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  4401. #include <string>
  4402. #include <iosfwd>
  4403. #include <map>
  4404. #include <set>
  4405. #include <memory>
  4406. #include <algorithm>
  4407. namespace Catch {
  4408. struct ReporterConfig {
  4409. explicit ReporterConfig( IConfigPtr const& _fullConfig );
  4410. ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream );
  4411. std::ostream& stream() const;
  4412. IConfigPtr fullConfig() const;
  4413. private:
  4414. std::ostream* m_stream;
  4415. IConfigPtr m_fullConfig;
  4416. };
  4417. struct ReporterPreferences {
  4418. bool shouldRedirectStdOut = false;
  4419. bool shouldReportAllAssertions = false;
  4420. };
  4421. template<typename T>
  4422. struct LazyStat : Option<T> {
  4423. LazyStat& operator=( T const& _value ) {
  4424. Option<T>::operator=( _value );
  4425. used = false;
  4426. return *this;
  4427. }
  4428. void reset() {
  4429. Option<T>::reset();
  4430. used = false;
  4431. }
  4432. bool used = false;
  4433. };
  4434. struct TestRunInfo {
  4435. TestRunInfo( std::string const& _name );
  4436. std::string name;
  4437. };
  4438. struct GroupInfo {
  4439. GroupInfo( std::string const& _name,
  4440. std::size_t _groupIndex,
  4441. std::size_t _groupsCount );
  4442. std::string name;
  4443. std::size_t groupIndex;
  4444. std::size_t groupsCounts;
  4445. };
  4446. struct AssertionStats {
  4447. AssertionStats( AssertionResult const& _assertionResult,
  4448. std::vector<MessageInfo> const& _infoMessages,
  4449. Totals const& _totals );
  4450. AssertionStats( AssertionStats const& ) = default;
  4451. AssertionStats( AssertionStats && ) = default;
  4452. AssertionStats& operator = ( AssertionStats const& ) = delete;
  4453. AssertionStats& operator = ( AssertionStats && ) = delete;
  4454. virtual ~AssertionStats();
  4455. AssertionResult assertionResult;
  4456. std::vector<MessageInfo> infoMessages;
  4457. Totals totals;
  4458. };
  4459. struct SectionStats {
  4460. SectionStats( SectionInfo const& _sectionInfo,
  4461. Counts const& _assertions,
  4462. double _durationInSeconds,
  4463. bool _missingAssertions );
  4464. SectionStats( SectionStats const& ) = default;
  4465. SectionStats( SectionStats && ) = default;
  4466. SectionStats& operator = ( SectionStats const& ) = default;
  4467. SectionStats& operator = ( SectionStats && ) = default;
  4468. virtual ~SectionStats();
  4469. SectionInfo sectionInfo;
  4470. Counts assertions;
  4471. double durationInSeconds;
  4472. bool missingAssertions;
  4473. };
  4474. struct TestCaseStats {
  4475. TestCaseStats( TestCaseInfo const& _testInfo,
  4476. Totals const& _totals,
  4477. std::string const& _stdOut,
  4478. std::string const& _stdErr,
  4479. bool _aborting );
  4480. TestCaseStats( TestCaseStats const& ) = default;
  4481. TestCaseStats( TestCaseStats && ) = default;
  4482. TestCaseStats& operator = ( TestCaseStats const& ) = default;
  4483. TestCaseStats& operator = ( TestCaseStats && ) = default;
  4484. virtual ~TestCaseStats();
  4485. TestCaseInfo testInfo;
  4486. Totals totals;
  4487. std::string stdOut;
  4488. std::string stdErr;
  4489. bool aborting;
  4490. };
  4491. struct TestGroupStats {
  4492. TestGroupStats( GroupInfo const& _groupInfo,
  4493. Totals const& _totals,
  4494. bool _aborting );
  4495. TestGroupStats( GroupInfo const& _groupInfo );
  4496. TestGroupStats( TestGroupStats const& ) = default;
  4497. TestGroupStats( TestGroupStats && ) = default;
  4498. TestGroupStats& operator = ( TestGroupStats const& ) = default;
  4499. TestGroupStats& operator = ( TestGroupStats && ) = default;
  4500. virtual ~TestGroupStats();
  4501. GroupInfo groupInfo;
  4502. Totals totals;
  4503. bool aborting;
  4504. };
  4505. struct TestRunStats {
  4506. TestRunStats( TestRunInfo const& _runInfo,
  4507. Totals const& _totals,
  4508. bool _aborting );
  4509. TestRunStats( TestRunStats const& ) = default;
  4510. TestRunStats( TestRunStats && ) = default;
  4511. TestRunStats& operator = ( TestRunStats const& ) = default;
  4512. TestRunStats& operator = ( TestRunStats && ) = default;
  4513. virtual ~TestRunStats();
  4514. TestRunInfo runInfo;
  4515. Totals totals;
  4516. bool aborting;
  4517. };
  4518. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  4519. struct BenchmarkInfo {
  4520. std::string name;
  4521. double estimatedDuration;
  4522. int iterations;
  4523. int samples;
  4524. unsigned int resamples;
  4525. double clockResolution;
  4526. double clockCost;
  4527. };
  4528. template <class Duration>
  4529. struct BenchmarkStats {
  4530. BenchmarkInfo info;
  4531. std::vector<Duration> samples;
  4532. Benchmark::Estimate<Duration> mean;
  4533. Benchmark::Estimate<Duration> standardDeviation;
  4534. Benchmark::OutlierClassification outliers;
  4535. double outlierVariance;
  4536. template <typename Duration2>
  4537. operator BenchmarkStats<Duration2>() const {
  4538. std::vector<Duration2> samples2;
  4539. samples2.reserve(samples.size());
  4540. std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration d) { return Duration2(d); });
  4541. return {
  4542. info,
  4543. std::move(samples2),
  4544. mean,
  4545. standardDeviation,
  4546. outliers,
  4547. outlierVariance,
  4548. };
  4549. }
  4550. };
  4551. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  4552. struct IStreamingReporter {
  4553. virtual ~IStreamingReporter() = default;
  4554. // Implementing class must also provide the following static methods:
  4555. // static std::string getDescription();
  4556. // static std::set<Verbosity> getSupportedVerbosities()
  4557. virtual ReporterPreferences getPreferences() const = 0;
  4558. virtual void noMatchingTestCases( std::string const& spec ) = 0;
  4559. virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0;
  4560. virtual void testGroupStarting( GroupInfo const& groupInfo ) = 0;
  4561. virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0;
  4562. virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0;
  4563. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  4564. virtual void benchmarkPreparing( std::string const& ) {}
  4565. virtual void benchmarkStarting( BenchmarkInfo const& ) {}
  4566. virtual void benchmarkEnded( BenchmarkStats<> const& ) {}
  4567. virtual void benchmarkFailed( std::string const& ) {}
  4568. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  4569. virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0;
  4570. // The return value indicates if the messages buffer should be cleared:
  4571. virtual bool assertionEnded( AssertionStats const& assertionStats ) = 0;
  4572. virtual void sectionEnded( SectionStats const& sectionStats ) = 0;
  4573. virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0;
  4574. virtual void testGroupEnded( TestGroupStats const& testGroupStats ) = 0;
  4575. virtual void testRunEnded( TestRunStats const& testRunStats ) = 0;
  4576. virtual void skipTest( TestCaseInfo const& testInfo ) = 0;
  4577. // Default empty implementation provided
  4578. virtual void fatalErrorEncountered( StringRef name );
  4579. virtual bool isMulti() const;
  4580. };
  4581. using IStreamingReporterPtr = std::unique_ptr<IStreamingReporter>;
  4582. struct IReporterFactory {
  4583. virtual ~IReporterFactory();
  4584. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const = 0;
  4585. virtual std::string getDescription() const = 0;
  4586. };
  4587. using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
  4588. struct IReporterRegistry {
  4589. using FactoryMap = std::map<std::string, IReporterFactoryPtr>;
  4590. using Listeners = std::vector<IReporterFactoryPtr>;
  4591. virtual ~IReporterRegistry();
  4592. virtual IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const = 0;
  4593. virtual FactoryMap const& getFactories() const = 0;
  4594. virtual Listeners const& getListeners() const = 0;
  4595. };
  4596. } // end namespace Catch
  4597. // end catch_interfaces_reporter.h
  4598. #include <algorithm>
  4599. #include <cstring>
  4600. #include <cfloat>
  4601. #include <cstdio>
  4602. #include <cassert>
  4603. #include <memory>
  4604. #include <ostream>
  4605. namespace Catch {
  4606. void prepareExpandedExpression(AssertionResult& result);
  4607. // Returns double formatted as %.3f (format expected on output)
  4608. std::string getFormattedDuration( double duration );
  4609. std::string serializeFilters( std::vector<std::string> const& container );
  4610. template<typename DerivedT>
  4611. struct StreamingReporterBase : IStreamingReporter {
  4612. StreamingReporterBase( ReporterConfig const& _config )
  4613. : m_config( _config.fullConfig() ),
  4614. stream( _config.stream() )
  4615. {
  4616. m_reporterPrefs.shouldRedirectStdOut = false;
  4617. if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
  4618. CATCH_ERROR( "Verbosity level not supported by this reporter" );
  4619. }
  4620. ReporterPreferences getPreferences() const override {
  4621. return m_reporterPrefs;
  4622. }
  4623. static std::set<Verbosity> getSupportedVerbosities() {
  4624. return { Verbosity::Normal };
  4625. }
  4626. ~StreamingReporterBase() override = default;
  4627. void noMatchingTestCases(std::string const&) override {}
  4628. void testRunStarting(TestRunInfo const& _testRunInfo) override {
  4629. currentTestRunInfo = _testRunInfo;
  4630. }
  4631. void testGroupStarting(GroupInfo const& _groupInfo) override {
  4632. currentGroupInfo = _groupInfo;
  4633. }
  4634. void testCaseStarting(TestCaseInfo const& _testInfo) override {
  4635. currentTestCaseInfo = _testInfo;
  4636. }
  4637. void sectionStarting(SectionInfo const& _sectionInfo) override {
  4638. m_sectionStack.push_back(_sectionInfo);
  4639. }
  4640. void sectionEnded(SectionStats const& /* _sectionStats */) override {
  4641. m_sectionStack.pop_back();
  4642. }
  4643. void testCaseEnded(TestCaseStats const& /* _testCaseStats */) override {
  4644. currentTestCaseInfo.reset();
  4645. }
  4646. void testGroupEnded(TestGroupStats const& /* _testGroupStats */) override {
  4647. currentGroupInfo.reset();
  4648. }
  4649. void testRunEnded(TestRunStats const& /* _testRunStats */) override {
  4650. currentTestCaseInfo.reset();
  4651. currentGroupInfo.reset();
  4652. currentTestRunInfo.reset();
  4653. }
  4654. void skipTest(TestCaseInfo const&) override {
  4655. // Don't do anything with this by default.
  4656. // It can optionally be overridden in the derived class.
  4657. }
  4658. IConfigPtr m_config;
  4659. std::ostream& stream;
  4660. LazyStat<TestRunInfo> currentTestRunInfo;
  4661. LazyStat<GroupInfo> currentGroupInfo;
  4662. LazyStat<TestCaseInfo> currentTestCaseInfo;
  4663. std::vector<SectionInfo> m_sectionStack;
  4664. ReporterPreferences m_reporterPrefs;
  4665. };
  4666. template<typename DerivedT>
  4667. struct CumulativeReporterBase : IStreamingReporter {
  4668. template<typename T, typename ChildNodeT>
  4669. struct Node {
  4670. explicit Node( T const& _value ) : value( _value ) {}
  4671. virtual ~Node() {}
  4672. using ChildNodes = std::vector<std::shared_ptr<ChildNodeT>>;
  4673. T value;
  4674. ChildNodes children;
  4675. };
  4676. struct SectionNode {
  4677. explicit SectionNode(SectionStats const& _stats) : stats(_stats) {}
  4678. virtual ~SectionNode() = default;
  4679. bool operator == (SectionNode const& other) const {
  4680. return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;
  4681. }
  4682. bool operator == (std::shared_ptr<SectionNode> const& other) const {
  4683. return operator==(*other);
  4684. }
  4685. SectionStats stats;
  4686. using ChildSections = std::vector<std::shared_ptr<SectionNode>>;
  4687. using Assertions = std::vector<AssertionStats>;
  4688. ChildSections childSections;
  4689. Assertions assertions;
  4690. std::string stdOut;
  4691. std::string stdErr;
  4692. };
  4693. struct BySectionInfo {
  4694. BySectionInfo( SectionInfo const& other ) : m_other( other ) {}
  4695. BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {}
  4696. bool operator() (std::shared_ptr<SectionNode> const& node) const {
  4697. return ((node->stats.sectionInfo.name == m_other.name) &&
  4698. (node->stats.sectionInfo.lineInfo == m_other.lineInfo));
  4699. }
  4700. void operator=(BySectionInfo const&) = delete;
  4701. private:
  4702. SectionInfo const& m_other;
  4703. };
  4704. using TestCaseNode = Node<TestCaseStats, SectionNode>;
  4705. using TestGroupNode = Node<TestGroupStats, TestCaseNode>;
  4706. using TestRunNode = Node<TestRunStats, TestGroupNode>;
  4707. CumulativeReporterBase( ReporterConfig const& _config )
  4708. : m_config( _config.fullConfig() ),
  4709. stream( _config.stream() )
  4710. {
  4711. m_reporterPrefs.shouldRedirectStdOut = false;
  4712. if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
  4713. CATCH_ERROR( "Verbosity level not supported by this reporter" );
  4714. }
  4715. ~CumulativeReporterBase() override = default;
  4716. ReporterPreferences getPreferences() const override {
  4717. return m_reporterPrefs;
  4718. }
  4719. static std::set<Verbosity> getSupportedVerbosities() {
  4720. return { Verbosity::Normal };
  4721. }
  4722. void testRunStarting( TestRunInfo const& ) override {}
  4723. void testGroupStarting( GroupInfo const& ) override {}
  4724. void testCaseStarting( TestCaseInfo const& ) override {}
  4725. void sectionStarting( SectionInfo const& sectionInfo ) override {
  4726. SectionStats incompleteStats( sectionInfo, Counts(), 0, false );
  4727. std::shared_ptr<SectionNode> node;
  4728. if( m_sectionStack.empty() ) {
  4729. if( !m_rootSection )
  4730. m_rootSection = std::make_shared<SectionNode>( incompleteStats );
  4731. node = m_rootSection;
  4732. }
  4733. else {
  4734. SectionNode& parentNode = *m_sectionStack.back();
  4735. auto it =
  4736. std::find_if( parentNode.childSections.begin(),
  4737. parentNode.childSections.end(),
  4738. BySectionInfo( sectionInfo ) );
  4739. if( it == parentNode.childSections.end() ) {
  4740. node = std::make_shared<SectionNode>( incompleteStats );
  4741. parentNode.childSections.push_back( node );
  4742. }
  4743. else
  4744. node = *it;
  4745. }
  4746. m_sectionStack.push_back( node );
  4747. m_deepestSection = std::move(node);
  4748. }
  4749. void assertionStarting(AssertionInfo const&) override {}
  4750. bool assertionEnded(AssertionStats const& assertionStats) override {
  4751. assert(!m_sectionStack.empty());
  4752. // AssertionResult holds a pointer to a temporary DecomposedExpression,
  4753. // which getExpandedExpression() calls to build the expression string.
  4754. // Our section stack copy of the assertionResult will likely outlive the
  4755. // temporary, so it must be expanded or discarded now to avoid calling
  4756. // a destroyed object later.
  4757. prepareExpandedExpression(const_cast<AssertionResult&>( assertionStats.assertionResult ) );
  4758. SectionNode& sectionNode = *m_sectionStack.back();
  4759. sectionNode.assertions.push_back(assertionStats);
  4760. return true;
  4761. }
  4762. void sectionEnded(SectionStats const& sectionStats) override {
  4763. assert(!m_sectionStack.empty());
  4764. SectionNode& node = *m_sectionStack.back();
  4765. node.stats = sectionStats;
  4766. m_sectionStack.pop_back();
  4767. }
  4768. void testCaseEnded(TestCaseStats const& testCaseStats) override {
  4769. auto node = std::make_shared<TestCaseNode>(testCaseStats);
  4770. assert(m_sectionStack.size() == 0);
  4771. node->children.push_back(m_rootSection);
  4772. m_testCases.push_back(node);
  4773. m_rootSection.reset();
  4774. assert(m_deepestSection);
  4775. m_deepestSection->stdOut = testCaseStats.stdOut;
  4776. m_deepestSection->stdErr = testCaseStats.stdErr;
  4777. }
  4778. void testGroupEnded(TestGroupStats const& testGroupStats) override {
  4779. auto node = std::make_shared<TestGroupNode>(testGroupStats);
  4780. node->children.swap(m_testCases);
  4781. m_testGroups.push_back(node);
  4782. }
  4783. void testRunEnded(TestRunStats const& testRunStats) override {
  4784. auto node = std::make_shared<TestRunNode>(testRunStats);
  4785. node->children.swap(m_testGroups);
  4786. m_testRuns.push_back(node);
  4787. testRunEndedCumulative();
  4788. }
  4789. virtual void testRunEndedCumulative() = 0;
  4790. void skipTest(TestCaseInfo const&) override {}
  4791. IConfigPtr m_config;
  4792. std::ostream& stream;
  4793. std::vector<AssertionStats> m_assertions;
  4794. std::vector<std::vector<std::shared_ptr<SectionNode>>> m_sections;
  4795. std::vector<std::shared_ptr<TestCaseNode>> m_testCases;
  4796. std::vector<std::shared_ptr<TestGroupNode>> m_testGroups;
  4797. std::vector<std::shared_ptr<TestRunNode>> m_testRuns;
  4798. std::shared_ptr<SectionNode> m_rootSection;
  4799. std::shared_ptr<SectionNode> m_deepestSection;
  4800. std::vector<std::shared_ptr<SectionNode>> m_sectionStack;
  4801. ReporterPreferences m_reporterPrefs;
  4802. };
  4803. template<char C>
  4804. char const* getLineOfChars() {
  4805. static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
  4806. if( !*line ) {
  4807. std::memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 );
  4808. line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0;
  4809. }
  4810. return line;
  4811. }
  4812. struct TestEventListenerBase : StreamingReporterBase<TestEventListenerBase> {
  4813. TestEventListenerBase( ReporterConfig const& _config );
  4814. static std::set<Verbosity> getSupportedVerbosities();
  4815. void assertionStarting(AssertionInfo const&) override;
  4816. bool assertionEnded(AssertionStats const&) override;
  4817. };
  4818. } // end namespace Catch
  4819. // end catch_reporter_bases.hpp
  4820. // start catch_console_colour.h
  4821. namespace Catch {
  4822. struct Colour {
  4823. enum Code {
  4824. None = 0,
  4825. White,
  4826. Red,
  4827. Green,
  4828. Blue,
  4829. Cyan,
  4830. Yellow,
  4831. Grey,
  4832. Bright = 0x10,
  4833. BrightRed = Bright | Red,
  4834. BrightGreen = Bright | Green,
  4835. LightGrey = Bright | Grey,
  4836. BrightWhite = Bright | White,
  4837. BrightYellow = Bright | Yellow,
  4838. // By intention
  4839. FileName = LightGrey,
  4840. Warning = BrightYellow,
  4841. ResultError = BrightRed,
  4842. ResultSuccess = BrightGreen,
  4843. ResultExpectedFailure = Warning,
  4844. Error = BrightRed,
  4845. Success = Green,
  4846. OriginalExpression = Cyan,
  4847. ReconstructedExpression = BrightYellow,
  4848. SecondaryText = LightGrey,
  4849. Headers = White
  4850. };
  4851. // Use constructed object for RAII guard
  4852. Colour( Code _colourCode );
  4853. Colour( Colour&& other ) noexcept;
  4854. Colour& operator=( Colour&& other ) noexcept;
  4855. ~Colour();
  4856. // Use static method for one-shot changes
  4857. static void use( Code _colourCode );
  4858. private:
  4859. bool m_moved = false;
  4860. };
  4861. std::ostream& operator << ( std::ostream& os, Colour const& );
  4862. } // end namespace Catch
  4863. // end catch_console_colour.h
  4864. // start catch_reporter_registrars.hpp
  4865. namespace Catch {
  4866. template<typename T>
  4867. class ReporterRegistrar {
  4868. class ReporterFactory : public IReporterFactory {
  4869. IStreamingReporterPtr create( ReporterConfig const& config ) const override {
  4870. return std::unique_ptr<T>( new T( config ) );
  4871. }
  4872. std::string getDescription() const override {
  4873. return T::getDescription();
  4874. }
  4875. };
  4876. public:
  4877. explicit ReporterRegistrar( std::string const& name ) {
  4878. getMutableRegistryHub().registerReporter( name, std::make_shared<ReporterFactory>() );
  4879. }
  4880. };
  4881. template<typename T>
  4882. class ListenerRegistrar {
  4883. class ListenerFactory : public IReporterFactory {
  4884. IStreamingReporterPtr create( ReporterConfig const& config ) const override {
  4885. return std::unique_ptr<T>( new T( config ) );
  4886. }
  4887. std::string getDescription() const override {
  4888. return std::string();
  4889. }
  4890. };
  4891. public:
  4892. ListenerRegistrar() {
  4893. getMutableRegistryHub().registerListener( std::make_shared<ListenerFactory>() );
  4894. }
  4895. };
  4896. }
  4897. #if !defined(CATCH_CONFIG_DISABLE)
  4898. #define CATCH_REGISTER_REPORTER( name, reporterType ) \
  4899. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  4900. namespace{ Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); } \
  4901. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  4902. #define CATCH_REGISTER_LISTENER( listenerType ) \
  4903. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  4904. namespace{ Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; } \
  4905. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  4906. #else // CATCH_CONFIG_DISABLE
  4907. #define CATCH_REGISTER_REPORTER(name, reporterType)
  4908. #define CATCH_REGISTER_LISTENER(listenerType)
  4909. #endif // CATCH_CONFIG_DISABLE
  4910. // end catch_reporter_registrars.hpp
  4911. // Allow users to base their work off existing reporters
  4912. // start catch_reporter_compact.h
  4913. namespace Catch {
  4914. struct CompactReporter : StreamingReporterBase<CompactReporter> {
  4915. using StreamingReporterBase::StreamingReporterBase;
  4916. ~CompactReporter() override;
  4917. static std::string getDescription();
  4918. ReporterPreferences getPreferences() const override;
  4919. void noMatchingTestCases(std::string const& spec) override;
  4920. void assertionStarting(AssertionInfo const&) override;
  4921. bool assertionEnded(AssertionStats const& _assertionStats) override;
  4922. void sectionEnded(SectionStats const& _sectionStats) override;
  4923. void testRunEnded(TestRunStats const& _testRunStats) override;
  4924. };
  4925. } // end namespace Catch
  4926. // end catch_reporter_compact.h
  4927. // start catch_reporter_console.h
  4928. #if defined(_MSC_VER)
  4929. #pragma warning(push)
  4930. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  4931. // Note that 4062 (not all labels are handled
  4932. // and default is missing) is enabled
  4933. #endif
  4934. namespace Catch {
  4935. // Fwd decls
  4936. struct SummaryColumn;
  4937. class TablePrinter;
  4938. struct ConsoleReporter : StreamingReporterBase<ConsoleReporter> {
  4939. std::unique_ptr<TablePrinter> m_tablePrinter;
  4940. ConsoleReporter(ReporterConfig const& config);
  4941. ~ConsoleReporter() override;
  4942. static std::string getDescription();
  4943. void noMatchingTestCases(std::string const& spec) override;
  4944. void assertionStarting(AssertionInfo const&) override;
  4945. bool assertionEnded(AssertionStats const& _assertionStats) override;
  4946. void sectionStarting(SectionInfo const& _sectionInfo) override;
  4947. void sectionEnded(SectionStats const& _sectionStats) override;
  4948. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  4949. void benchmarkPreparing(std::string const& name) override;
  4950. void benchmarkStarting(BenchmarkInfo const& info) override;
  4951. void benchmarkEnded(BenchmarkStats<> const& stats) override;
  4952. void benchmarkFailed(std::string const& error) override;
  4953. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  4954. void testCaseEnded(TestCaseStats const& _testCaseStats) override;
  4955. void testGroupEnded(TestGroupStats const& _testGroupStats) override;
  4956. void testRunEnded(TestRunStats const& _testRunStats) override;
  4957. void testRunStarting(TestRunInfo const& _testRunInfo) override;
  4958. private:
  4959. void lazyPrint();
  4960. void lazyPrintWithoutClosingBenchmarkTable();
  4961. void lazyPrintRunInfo();
  4962. void lazyPrintGroupInfo();
  4963. void printTestCaseAndSectionHeader();
  4964. void printClosedHeader(std::string const& _name);
  4965. void printOpenHeader(std::string const& _name);
  4966. // if string has a : in first line will set indent to follow it on
  4967. // subsequent lines
  4968. void printHeaderString(std::string const& _string, std::size_t indent = 0);
  4969. void printTotals(Totals const& totals);
  4970. void printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row);
  4971. void printTotalsDivider(Totals const& totals);
  4972. void printSummaryDivider();
  4973. void printTestFilters();
  4974. private:
  4975. bool m_headerPrinted = false;
  4976. };
  4977. } // end namespace Catch
  4978. #if defined(_MSC_VER)
  4979. #pragma warning(pop)
  4980. #endif
  4981. // end catch_reporter_console.h
  4982. // start catch_reporter_junit.h
  4983. // start catch_xmlwriter.h
  4984. #include <vector>
  4985. namespace Catch {
  4986. class XmlEncode {
  4987. public:
  4988. enum ForWhat { ForTextNodes, ForAttributes };
  4989. XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes );
  4990. void encodeTo( std::ostream& os ) const;
  4991. friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode );
  4992. private:
  4993. std::string m_str;
  4994. ForWhat m_forWhat;
  4995. };
  4996. class XmlWriter {
  4997. public:
  4998. class ScopedElement {
  4999. public:
  5000. ScopedElement( XmlWriter* writer );
  5001. ScopedElement( ScopedElement&& other ) noexcept;
  5002. ScopedElement& operator=( ScopedElement&& other ) noexcept;
  5003. ~ScopedElement();
  5004. ScopedElement& writeText( std::string const& text, bool indent = true );
  5005. template<typename T>
  5006. ScopedElement& writeAttribute( std::string const& name, T const& attribute ) {
  5007. m_writer->writeAttribute( name, attribute );
  5008. return *this;
  5009. }
  5010. private:
  5011. mutable XmlWriter* m_writer = nullptr;
  5012. };
  5013. XmlWriter( std::ostream& os = Catch::cout() );
  5014. ~XmlWriter();
  5015. XmlWriter( XmlWriter const& ) = delete;
  5016. XmlWriter& operator=( XmlWriter const& ) = delete;
  5017. XmlWriter& startElement( std::string const& name );
  5018. ScopedElement scopedElement( std::string const& name );
  5019. XmlWriter& endElement();
  5020. XmlWriter& writeAttribute( std::string const& name, std::string const& attribute );
  5021. XmlWriter& writeAttribute( std::string const& name, bool attribute );
  5022. template<typename T>
  5023. XmlWriter& writeAttribute( std::string const& name, T const& attribute ) {
  5024. ReusableStringStream rss;
  5025. rss << attribute;
  5026. return writeAttribute( name, rss.str() );
  5027. }
  5028. XmlWriter& writeText( std::string const& text, bool indent = true );
  5029. XmlWriter& writeComment( std::string const& text );
  5030. void writeStylesheetRef( std::string const& url );
  5031. XmlWriter& writeBlankLine();
  5032. void ensureTagClosed();
  5033. private:
  5034. void writeDeclaration();
  5035. void newlineIfNecessary();
  5036. bool m_tagIsOpen = false;
  5037. bool m_needsNewline = false;
  5038. std::vector<std::string> m_tags;
  5039. std::string m_indent;
  5040. std::ostream& m_os;
  5041. };
  5042. }
  5043. // end catch_xmlwriter.h
  5044. namespace Catch {
  5045. class JunitReporter : public CumulativeReporterBase<JunitReporter> {
  5046. public:
  5047. JunitReporter(ReporterConfig const& _config);
  5048. ~JunitReporter() override;
  5049. static std::string getDescription();
  5050. void noMatchingTestCases(std::string const& /*spec*/) override;
  5051. void testRunStarting(TestRunInfo const& runInfo) override;
  5052. void testGroupStarting(GroupInfo const& groupInfo) override;
  5053. void testCaseStarting(TestCaseInfo const& testCaseInfo) override;
  5054. bool assertionEnded(AssertionStats const& assertionStats) override;
  5055. void testCaseEnded(TestCaseStats const& testCaseStats) override;
  5056. void testGroupEnded(TestGroupStats const& testGroupStats) override;
  5057. void testRunEndedCumulative() override;
  5058. void writeGroup(TestGroupNode const& groupNode, double suiteTime);
  5059. void writeTestCase(TestCaseNode const& testCaseNode);
  5060. void writeSection(std::string const& className,
  5061. std::string const& rootName,
  5062. SectionNode const& sectionNode);
  5063. void writeAssertions(SectionNode const& sectionNode);
  5064. void writeAssertion(AssertionStats const& stats);
  5065. XmlWriter xml;
  5066. Timer suiteTimer;
  5067. std::string stdOutForSuite;
  5068. std::string stdErrForSuite;
  5069. unsigned int unexpectedExceptions = 0;
  5070. bool m_okToFail = false;
  5071. };
  5072. } // end namespace Catch
  5073. // end catch_reporter_junit.h
  5074. // start catch_reporter_xml.h
  5075. namespace Catch {
  5076. class XmlReporter : public StreamingReporterBase<XmlReporter> {
  5077. public:
  5078. XmlReporter(ReporterConfig const& _config);
  5079. ~XmlReporter() override;
  5080. static std::string getDescription();
  5081. virtual std::string getStylesheetRef() const;
  5082. void writeSourceInfo(SourceLineInfo const& sourceInfo);
  5083. public: // StreamingReporterBase
  5084. void noMatchingTestCases(std::string const& s) override;
  5085. void testRunStarting(TestRunInfo const& testInfo) override;
  5086. void testGroupStarting(GroupInfo const& groupInfo) override;
  5087. void testCaseStarting(TestCaseInfo const& testInfo) override;
  5088. void sectionStarting(SectionInfo const& sectionInfo) override;
  5089. void assertionStarting(AssertionInfo const&) override;
  5090. bool assertionEnded(AssertionStats const& assertionStats) override;
  5091. void sectionEnded(SectionStats const& sectionStats) override;
  5092. void testCaseEnded(TestCaseStats const& testCaseStats) override;
  5093. void testGroupEnded(TestGroupStats const& testGroupStats) override;
  5094. void testRunEnded(TestRunStats const& testRunStats) override;
  5095. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  5096. void benchmarkPreparing(std::string const& name) override;
  5097. void benchmarkStarting(BenchmarkInfo const&) override;
  5098. void benchmarkEnded(BenchmarkStats<> const&) override;
  5099. void benchmarkFailed(std::string const&) override;
  5100. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  5101. private:
  5102. Timer m_testCaseTimer;
  5103. XmlWriter m_xml;
  5104. int m_sectionDepth = 0;
  5105. };
  5106. } // end namespace Catch
  5107. // end catch_reporter_xml.h
  5108. // end catch_external_interfaces.h
  5109. #endif
  5110. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  5111. // start catch_benchmark.hpp
  5112. // Benchmark
  5113. // start catch_chronometer.hpp
  5114. // User-facing chronometer
  5115. // start catch_clock.hpp
  5116. // Clocks
  5117. #include <chrono>
  5118. #include <ratio>
  5119. namespace Catch {
  5120. namespace Benchmark {
  5121. template <typename Clock>
  5122. using ClockDuration = typename Clock::duration;
  5123. template <typename Clock>
  5124. using FloatDuration = std::chrono::duration<double, typename Clock::period>;
  5125. template <typename Clock>
  5126. using TimePoint = typename Clock::time_point;
  5127. using default_clock = std::chrono::steady_clock;
  5128. template <typename Clock>
  5129. struct now {
  5130. TimePoint<Clock> operator()() const {
  5131. return Clock::now();
  5132. }
  5133. };
  5134. using fp_seconds = std::chrono::duration<double, std::ratio<1>>;
  5135. } // namespace Benchmark
  5136. } // namespace Catch
  5137. // end catch_clock.hpp
  5138. // start catch_optimizer.hpp
  5139. // Hinting the optimizer
  5140. #if defined(_MSC_VER)
  5141. # include <atomic> // atomic_thread_fence
  5142. #endif
  5143. namespace Catch {
  5144. namespace Benchmark {
  5145. #if defined(__GNUC__) || defined(__clang__)
  5146. template <typename T>
  5147. inline void keep_memory(T* p) {
  5148. asm volatile("" : : "g"(p) : "memory");
  5149. }
  5150. inline void keep_memory() {
  5151. asm volatile("" : : : "memory");
  5152. }
  5153. namespace Detail {
  5154. inline void optimizer_barrier() { keep_memory(); }
  5155. } // namespace Detail
  5156. #elif defined(_MSC_VER)
  5157. #pragma optimize("", off)
  5158. template <typename T>
  5159. inline void keep_memory(T* p) {
  5160. // thanks @milleniumbug
  5161. *reinterpret_cast<char volatile*>(p) = *reinterpret_cast<char const volatile*>(p);
  5162. }
  5163. // TODO equivalent keep_memory()
  5164. #pragma optimize("", on)
  5165. namespace Detail {
  5166. inline void optimizer_barrier() {
  5167. std::atomic_thread_fence(std::memory_order_seq_cst);
  5168. }
  5169. } // namespace Detail
  5170. #endif
  5171. template <typename T>
  5172. inline void deoptimize_value(T&& x) {
  5173. keep_memory(&x);
  5174. }
  5175. template <typename Fn, typename... Args>
  5176. inline auto invoke_deoptimized(Fn&& fn, Args&&... args) -> typename std::enable_if<!std::is_same<void, decltype(fn(args...))>::value>::type {
  5177. deoptimize_value(std::forward<Fn>(fn) (std::forward<Args...>(args...)));
  5178. }
  5179. template <typename Fn, typename... Args>
  5180. inline auto invoke_deoptimized(Fn&& fn, Args&&... args) -> typename std::enable_if<std::is_same<void, decltype(fn(args...))>::value>::type {
  5181. std::forward<Fn>(fn) (std::forward<Args...>(args...));
  5182. }
  5183. } // namespace Benchmark
  5184. } // namespace Catch
  5185. // end catch_optimizer.hpp
  5186. // start catch_complete_invoke.hpp
  5187. // Invoke with a special case for void
  5188. #include <type_traits>
  5189. #include <utility>
  5190. namespace Catch {
  5191. namespace Benchmark {
  5192. namespace Detail {
  5193. template <typename T>
  5194. struct CompleteType { using type = T; };
  5195. template <>
  5196. struct CompleteType<void> { struct type {}; };
  5197. template <typename T>
  5198. using CompleteType_t = typename CompleteType<T>::type;
  5199. template <typename Result>
  5200. struct CompleteInvoker {
  5201. template <typename Fun, typename... Args>
  5202. static Result invoke(Fun&& fun, Args&&... args) {
  5203. return std::forward<Fun>(fun)(std::forward<Args>(args)...);
  5204. }
  5205. };
  5206. template <>
  5207. struct CompleteInvoker<void> {
  5208. template <typename Fun, typename... Args>
  5209. static CompleteType_t<void> invoke(Fun&& fun, Args&&... args) {
  5210. std::forward<Fun>(fun)(std::forward<Args>(args)...);
  5211. return {};
  5212. }
  5213. };
  5214. template <typename Sig>
  5215. using ResultOf_t = typename std::result_of<Sig>::type;
  5216. // invoke and not return void :(
  5217. template <typename Fun, typename... Args>
  5218. CompleteType_t<ResultOf_t<Fun(Args...)>> complete_invoke(Fun&& fun, Args&&... args) {
  5219. return CompleteInvoker<ResultOf_t<Fun(Args...)>>::invoke(std::forward<Fun>(fun), std::forward<Args>(args)...);
  5220. }
  5221. const std::string benchmarkErrorMsg = "a benchmark failed to run successfully";
  5222. } // namespace Detail
  5223. template <typename Fun>
  5224. Detail::CompleteType_t<Detail::ResultOf_t<Fun()>> user_code(Fun&& fun) {
  5225. CATCH_TRY{
  5226. return Detail::complete_invoke(std::forward<Fun>(fun));
  5227. } CATCH_CATCH_ALL{
  5228. getResultCapture().benchmarkFailed(translateActiveException());
  5229. CATCH_RUNTIME_ERROR(Detail::benchmarkErrorMsg);
  5230. }
  5231. }
  5232. } // namespace Benchmark
  5233. } // namespace Catch
  5234. // end catch_complete_invoke.hpp
  5235. namespace Catch {
  5236. namespace Benchmark {
  5237. namespace Detail {
  5238. struct ChronometerConcept {
  5239. virtual void start() = 0;
  5240. virtual void finish() = 0;
  5241. virtual ~ChronometerConcept() = default;
  5242. };
  5243. template <typename Clock>
  5244. struct ChronometerModel final : public ChronometerConcept {
  5245. void start() override { started = Clock::now(); }
  5246. void finish() override { finished = Clock::now(); }
  5247. ClockDuration<Clock> elapsed() const { return finished - started; }
  5248. TimePoint<Clock> started;
  5249. TimePoint<Clock> finished;
  5250. };
  5251. } // namespace Detail
  5252. struct Chronometer {
  5253. public:
  5254. template <typename Fun>
  5255. void measure(Fun&& fun) { measure(std::forward<Fun>(fun), is_callable<Fun(int)>()); }
  5256. int runs() const { return k; }
  5257. Chronometer(Detail::ChronometerConcept& meter, int k)
  5258. : impl(&meter)
  5259. , k(k) {}
  5260. private:
  5261. template <typename Fun>
  5262. void measure(Fun&& fun, std::false_type) {
  5263. measure([&fun](int) { return fun(); }, std::true_type());
  5264. }
  5265. template <typename Fun>
  5266. void measure(Fun&& fun, std::true_type) {
  5267. Detail::optimizer_barrier();
  5268. impl->start();
  5269. for (int i = 0; i < k; ++i) invoke_deoptimized(fun, i);
  5270. impl->finish();
  5271. Detail::optimizer_barrier();
  5272. }
  5273. Detail::ChronometerConcept* impl;
  5274. int k;
  5275. };
  5276. } // namespace Benchmark
  5277. } // namespace Catch
  5278. // end catch_chronometer.hpp
  5279. // start catch_environment.hpp
  5280. // Environment information
  5281. namespace Catch {
  5282. namespace Benchmark {
  5283. template <typename Duration>
  5284. struct EnvironmentEstimate {
  5285. Duration mean;
  5286. OutlierClassification outliers;
  5287. template <typename Duration2>
  5288. operator EnvironmentEstimate<Duration2>() const {
  5289. return { mean, outliers };
  5290. }
  5291. };
  5292. template <typename Clock>
  5293. struct Environment {
  5294. using clock_type = Clock;
  5295. EnvironmentEstimate<FloatDuration<Clock>> clock_resolution;
  5296. EnvironmentEstimate<FloatDuration<Clock>> clock_cost;
  5297. };
  5298. } // namespace Benchmark
  5299. } // namespace Catch
  5300. // end catch_environment.hpp
  5301. // start catch_execution_plan.hpp
  5302. // Execution plan
  5303. // start catch_benchmark_function.hpp
  5304. // Dumb std::function implementation for consistent call overhead
  5305. #include <cassert>
  5306. #include <type_traits>
  5307. #include <utility>
  5308. #include <memory>
  5309. namespace Catch {
  5310. namespace Benchmark {
  5311. namespace Detail {
  5312. template <typename T>
  5313. using Decay = typename std::decay<T>::type;
  5314. template <typename T, typename U>
  5315. struct is_related
  5316. : std::is_same<Decay<T>, Decay<U>> {};
  5317. /// We need to reinvent std::function because every piece of code that might add overhead
  5318. /// in a measurement context needs to have consistent performance characteristics so that we
  5319. /// can account for it in the measurement.
  5320. /// Implementations of std::function with optimizations that aren't always applicable, like
  5321. /// small buffer optimizations, are not uncommon.
  5322. /// This is effectively an implementation of std::function without any such optimizations;
  5323. /// it may be slow, but it is consistently slow.
  5324. struct BenchmarkFunction {
  5325. private:
  5326. struct callable {
  5327. virtual void call(Chronometer meter) const = 0;
  5328. virtual callable* clone() const = 0;
  5329. virtual ~callable() = default;
  5330. };
  5331. template <typename Fun>
  5332. struct model : public callable {
  5333. model(Fun&& fun) : fun(std::move(fun)) {}
  5334. model(Fun const& fun) : fun(fun) {}
  5335. model<Fun>* clone() const override { return new model<Fun>(*this); }
  5336. void call(Chronometer meter) const override {
  5337. call(meter, is_callable<Fun(Chronometer)>());
  5338. }
  5339. void call(Chronometer meter, std::true_type) const {
  5340. fun(meter);
  5341. }
  5342. void call(Chronometer meter, std::false_type) const {
  5343. meter.measure(fun);
  5344. }
  5345. Fun fun;
  5346. };
  5347. struct do_nothing { void operator()() const {} };
  5348. template <typename T>
  5349. BenchmarkFunction(model<T>* c) : f(c) {}
  5350. public:
  5351. BenchmarkFunction()
  5352. : f(new model<do_nothing>{ {} }) {}
  5353. template <typename Fun,
  5354. typename std::enable_if<!is_related<Fun, BenchmarkFunction>::value, int>::type = 0>
  5355. BenchmarkFunction(Fun&& fun)
  5356. : f(new model<typename std::decay<Fun>::type>(std::forward<Fun>(fun))) {}
  5357. BenchmarkFunction(BenchmarkFunction&& that)
  5358. : f(std::move(that.f)) {}
  5359. BenchmarkFunction(BenchmarkFunction const& that)
  5360. : f(that.f->clone()) {}
  5361. BenchmarkFunction& operator=(BenchmarkFunction&& that) {
  5362. f = std::move(that.f);
  5363. return *this;
  5364. }
  5365. BenchmarkFunction& operator=(BenchmarkFunction const& that) {
  5366. f.reset(that.f->clone());
  5367. return *this;
  5368. }
  5369. void operator()(Chronometer meter) const { f->call(meter); }
  5370. private:
  5371. std::unique_ptr<callable> f;
  5372. };
  5373. } // namespace Detail
  5374. } // namespace Benchmark
  5375. } // namespace Catch
  5376. // end catch_benchmark_function.hpp
  5377. // start catch_repeat.hpp
  5378. // repeat algorithm
  5379. #include <type_traits>
  5380. #include <utility>
  5381. namespace Catch {
  5382. namespace Benchmark {
  5383. namespace Detail {
  5384. template <typename Fun>
  5385. struct repeater {
  5386. void operator()(int k) const {
  5387. for (int i = 0; i < k; ++i) {
  5388. fun();
  5389. }
  5390. }
  5391. Fun fun;
  5392. };
  5393. template <typename Fun>
  5394. repeater<typename std::decay<Fun>::type> repeat(Fun&& fun) {
  5395. return { std::forward<Fun>(fun) };
  5396. }
  5397. } // namespace Detail
  5398. } // namespace Benchmark
  5399. } // namespace Catch
  5400. // end catch_repeat.hpp
  5401. // start catch_run_for_at_least.hpp
  5402. // Run a function for a minimum amount of time
  5403. // start catch_measure.hpp
  5404. // Measure
  5405. // start catch_timing.hpp
  5406. // Timing
  5407. #include <tuple>
  5408. #include <type_traits>
  5409. namespace Catch {
  5410. namespace Benchmark {
  5411. template <typename Duration, typename Result>
  5412. struct Timing {
  5413. Duration elapsed;
  5414. Result result;
  5415. int iterations;
  5416. };
  5417. template <typename Clock, typename Sig>
  5418. using TimingOf = Timing<ClockDuration<Clock>, Detail::CompleteType_t<Detail::ResultOf_t<Sig>>>;
  5419. } // namespace Benchmark
  5420. } // namespace Catch
  5421. // end catch_timing.hpp
  5422. #include <utility>
  5423. namespace Catch {
  5424. namespace Benchmark {
  5425. namespace Detail {
  5426. template <typename Clock, typename Fun, typename... Args>
  5427. TimingOf<Clock, Fun(Args...)> measure(Fun&& fun, Args&&... args) {
  5428. auto start = Clock::now();
  5429. auto&& r = Detail::complete_invoke(fun, std::forward<Args>(args)...);
  5430. auto end = Clock::now();
  5431. auto delta = end - start;
  5432. return { delta, std::forward<decltype(r)>(r), 1 };
  5433. }
  5434. } // namespace Detail
  5435. } // namespace Benchmark
  5436. } // namespace Catch
  5437. // end catch_measure.hpp
  5438. #include <utility>
  5439. #include <type_traits>
  5440. namespace Catch {
  5441. namespace Benchmark {
  5442. namespace Detail {
  5443. template <typename Clock, typename Fun>
  5444. TimingOf<Clock, Fun(int)> measure_one(Fun&& fun, int iters, std::false_type) {
  5445. return Detail::measure<Clock>(fun, iters);
  5446. }
  5447. template <typename Clock, typename Fun>
  5448. TimingOf<Clock, Fun(Chronometer)> measure_one(Fun&& fun, int iters, std::true_type) {
  5449. Detail::ChronometerModel<Clock> meter;
  5450. auto&& result = Detail::complete_invoke(fun, Chronometer(meter, iters));
  5451. return { meter.elapsed(), std::move(result), iters };
  5452. }
  5453. template <typename Clock, typename Fun>
  5454. using run_for_at_least_argument_t = typename std::conditional<is_callable<Fun(Chronometer)>::value, Chronometer, int>::type;
  5455. struct optimized_away_error : std::exception {
  5456. const char* what() const noexcept override {
  5457. return "could not measure benchmark, maybe it was optimized away";
  5458. }
  5459. };
  5460. template <typename Clock, typename Fun>
  5461. TimingOf<Clock, Fun(run_for_at_least_argument_t<Clock, Fun>)> run_for_at_least(ClockDuration<Clock> how_long, int seed, Fun&& fun) {
  5462. auto iters = seed;
  5463. while (iters < (1 << 30)) {
  5464. auto&& Timing = measure_one<Clock>(fun, iters, is_callable<Fun(Chronometer)>());
  5465. if (Timing.elapsed >= how_long) {
  5466. return { Timing.elapsed, std::move(Timing.result), iters };
  5467. }
  5468. iters *= 2;
  5469. }
  5470. throw optimized_away_error{};
  5471. }
  5472. } // namespace Detail
  5473. } // namespace Benchmark
  5474. } // namespace Catch
  5475. // end catch_run_for_at_least.hpp
  5476. #include <algorithm>
  5477. namespace Catch {
  5478. namespace Benchmark {
  5479. template <typename Duration>
  5480. struct ExecutionPlan {
  5481. int iterations_per_sample;
  5482. Duration estimated_duration;
  5483. Detail::BenchmarkFunction benchmark;
  5484. Duration warmup_time;
  5485. int warmup_iterations;
  5486. template <typename Duration2>
  5487. operator ExecutionPlan<Duration2>() const {
  5488. return { iterations_per_sample, estimated_duration, benchmark, warmup_time, warmup_iterations };
  5489. }
  5490. template <typename Clock>
  5491. std::vector<FloatDuration<Clock>> run(const IConfig &cfg, Environment<FloatDuration<Clock>> env) const {
  5492. // warmup a bit
  5493. Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_iterations, Detail::repeat(now<Clock>{}));
  5494. std::vector<FloatDuration<Clock>> times;
  5495. times.reserve(cfg.benchmarkSamples());
  5496. std::generate_n(std::back_inserter(times), cfg.benchmarkSamples(), [this, env] {
  5497. Detail::ChronometerModel<Clock> model;
  5498. this->benchmark(Chronometer(model, iterations_per_sample));
  5499. auto sample_time = model.elapsed() - env.clock_cost.mean;
  5500. if (sample_time < FloatDuration<Clock>::zero()) sample_time = FloatDuration<Clock>::zero();
  5501. return sample_time / iterations_per_sample;
  5502. });
  5503. return times;
  5504. }
  5505. };
  5506. } // namespace Benchmark
  5507. } // namespace Catch
  5508. // end catch_execution_plan.hpp
  5509. // start catch_estimate_clock.hpp
  5510. // Environment measurement
  5511. // start catch_stats.hpp
  5512. // Statistical analysis tools
  5513. #include <algorithm>
  5514. #include <functional>
  5515. #include <vector>
  5516. #include <numeric>
  5517. #include <tuple>
  5518. #include <cmath>
  5519. #include <utility>
  5520. #include <cstddef>
  5521. namespace Catch {
  5522. namespace Benchmark {
  5523. namespace Detail {
  5524. using sample = std::vector<double>;
  5525. double weighted_average_quantile(int k, int q, std::vector<double>::iterator first, std::vector<double>::iterator last);
  5526. template <typename Iterator>
  5527. OutlierClassification classify_outliers(Iterator first, Iterator last) {
  5528. std::vector<double> copy(first, last);
  5529. auto q1 = weighted_average_quantile(1, 4, copy.begin(), copy.end());
  5530. auto q3 = weighted_average_quantile(3, 4, copy.begin(), copy.end());
  5531. auto iqr = q3 - q1;
  5532. auto los = q1 - (iqr * 3.);
  5533. auto lom = q1 - (iqr * 1.5);
  5534. auto him = q3 + (iqr * 1.5);
  5535. auto his = q3 + (iqr * 3.);
  5536. OutlierClassification o;
  5537. for (; first != last; ++first) {
  5538. auto&& t = *first;
  5539. if (t < los) ++o.low_severe;
  5540. else if (t < lom) ++o.low_mild;
  5541. else if (t > his) ++o.high_severe;
  5542. else if (t > him) ++o.high_mild;
  5543. ++o.samples_seen;
  5544. }
  5545. return o;
  5546. }
  5547. template <typename Iterator>
  5548. double mean(Iterator first, Iterator last) {
  5549. auto count = last - first;
  5550. double sum = std::accumulate(first, last, 0.);
  5551. return sum / count;
  5552. }
  5553. template <typename URng, typename Iterator, typename Estimator>
  5554. sample resample(URng& rng, int resamples, Iterator first, Iterator last, Estimator& estimator) {
  5555. auto n = last - first;
  5556. std::uniform_int_distribution<decltype(n)> dist(0, n - 1);
  5557. sample out;
  5558. out.reserve(resamples);
  5559. std::generate_n(std::back_inserter(out), resamples, [n, first, &estimator, &dist, &rng] {
  5560. std::vector<double> resampled;
  5561. resampled.reserve(n);
  5562. std::generate_n(std::back_inserter(resampled), n, [first, &dist, &rng] { return first[dist(rng)]; });
  5563. return estimator(resampled.begin(), resampled.end());
  5564. });
  5565. std::sort(out.begin(), out.end());
  5566. return out;
  5567. }
  5568. template <typename Estimator, typename Iterator>
  5569. sample jackknife(Estimator&& estimator, Iterator first, Iterator last) {
  5570. auto n = last - first;
  5571. auto second = std::next(first);
  5572. sample results;
  5573. results.reserve(n);
  5574. for (auto it = first; it != last; ++it) {
  5575. std::iter_swap(it, first);
  5576. results.push_back(estimator(second, last));
  5577. }
  5578. return results;
  5579. }
  5580. inline double normal_cdf(double x) {
  5581. return std::erfc(-x / std::sqrt(2.0)) / 2.0;
  5582. }
  5583. double erfc_inv(double x);
  5584. double normal_quantile(double p);
  5585. template <typename Iterator, typename Estimator>
  5586. Estimate<double> bootstrap(double confidence_level, Iterator first, Iterator last, sample const& resample, Estimator&& estimator) {
  5587. auto n_samples = last - first;
  5588. double point = estimator(first, last);
  5589. // Degenerate case with a single sample
  5590. if (n_samples == 1) return { point, point, point, confidence_level };
  5591. sample jack = jackknife(estimator, first, last);
  5592. double jack_mean = mean(jack.begin(), jack.end());
  5593. double sum_squares, sum_cubes;
  5594. 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> {
  5595. auto d = jack_mean - x;
  5596. auto d2 = d * d;
  5597. auto d3 = d2 * d;
  5598. return { sqcb.first + d2, sqcb.second + d3 };
  5599. });
  5600. double accel = sum_cubes / (6 * std::pow(sum_squares, 1.5));
  5601. int n = static_cast<int>(resample.size());
  5602. double prob_n = std::count_if(resample.begin(), resample.end(), [point](double x) { return x < point; }) / (double)n;
  5603. // degenerate case with uniform samples
  5604. if (prob_n == 0) return { point, point, point, confidence_level };
  5605. double bias = normal_quantile(prob_n);
  5606. double z1 = normal_quantile((1. - confidence_level) / 2.);
  5607. auto cumn = [n](double x) -> int {
  5608. return std::lround(normal_cdf(x) * n); };
  5609. auto a = [bias, accel](double b) { return bias + b / (1. - accel * b); };
  5610. double b1 = bias + z1;
  5611. double b2 = bias - z1;
  5612. double a1 = a(b1);
  5613. double a2 = a(b2);
  5614. auto lo = std::max(cumn(a1), 0);
  5615. auto hi = std::min(cumn(a2), n - 1);
  5616. return { point, resample[lo], resample[hi], confidence_level };
  5617. }
  5618. double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n);
  5619. struct bootstrap_analysis {
  5620. Estimate<double> mean;
  5621. Estimate<double> standard_deviation;
  5622. double outlier_variance;
  5623. };
  5624. bootstrap_analysis analyse_samples(double confidence_level, int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last);
  5625. } // namespace Detail
  5626. } // namespace Benchmark
  5627. } // namespace Catch
  5628. // end catch_stats.hpp
  5629. #include <algorithm>
  5630. #include <iterator>
  5631. #include <tuple>
  5632. #include <vector>
  5633. #include <cmath>
  5634. namespace Catch {
  5635. namespace Benchmark {
  5636. namespace Detail {
  5637. template <typename Clock>
  5638. std::vector<double> resolution(int k) {
  5639. std::vector<TimePoint<Clock>> times;
  5640. times.reserve(k + 1);
  5641. std::generate_n(std::back_inserter(times), k + 1, now<Clock>{});
  5642. std::vector<double> deltas;
  5643. deltas.reserve(k);
  5644. std::transform(std::next(times.begin()), times.end(), times.begin(),
  5645. std::back_inserter(deltas),
  5646. [](TimePoint<Clock> a, TimePoint<Clock> b) { return static_cast<double>((a - b).count()); });
  5647. return deltas;
  5648. }
  5649. const auto warmup_iterations = 10000;
  5650. const auto warmup_time = std::chrono::milliseconds(100);
  5651. const auto minimum_ticks = 1000;
  5652. const auto warmup_seed = 10000;
  5653. const auto clock_resolution_estimation_time = std::chrono::milliseconds(500);
  5654. const auto clock_cost_estimation_time_limit = std::chrono::seconds(1);
  5655. const auto clock_cost_estimation_tick_limit = 100000;
  5656. const auto clock_cost_estimation_time = std::chrono::milliseconds(10);
  5657. const auto clock_cost_estimation_iterations = 10000;
  5658. template <typename Clock>
  5659. int warmup() {
  5660. return run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_seed, &resolution<Clock>)
  5661. .iterations;
  5662. }
  5663. template <typename Clock>
  5664. EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_resolution(int iterations) {
  5665. auto r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_resolution_estimation_time), iterations, &resolution<Clock>)
  5666. .result;
  5667. return {
  5668. FloatDuration<Clock>(mean(r.begin(), r.end())),
  5669. classify_outliers(r.begin(), r.end()),
  5670. };
  5671. }
  5672. template <typename Clock>
  5673. EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_cost(FloatDuration<Clock> resolution) {
  5674. auto time_limit = std::min(resolution * clock_cost_estimation_tick_limit, FloatDuration<Clock>(clock_cost_estimation_time_limit));
  5675. auto time_clock = [](int k) {
  5676. return Detail::measure<Clock>([k] {
  5677. for (int i = 0; i < k; ++i) {
  5678. volatile auto ignored = Clock::now();
  5679. (void)ignored;
  5680. }
  5681. }).elapsed;
  5682. };
  5683. time_clock(1);
  5684. int iters = clock_cost_estimation_iterations;
  5685. auto&& r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_cost_estimation_time), iters, time_clock);
  5686. std::vector<double> times;
  5687. int nsamples = static_cast<int>(std::ceil(time_limit / r.elapsed));
  5688. times.reserve(nsamples);
  5689. std::generate_n(std::back_inserter(times), nsamples, [time_clock, &r] {
  5690. return static_cast<double>((time_clock(r.iterations) / r.iterations).count());
  5691. });
  5692. return {
  5693. FloatDuration<Clock>(mean(times.begin(), times.end())),
  5694. classify_outliers(times.begin(), times.end()),
  5695. };
  5696. }
  5697. template <typename Clock>
  5698. Environment<FloatDuration<Clock>> measure_environment() {
  5699. static Environment<FloatDuration<Clock>>* env = nullptr;
  5700. if (env) {
  5701. return *env;
  5702. }
  5703. auto iters = Detail::warmup<Clock>();
  5704. auto resolution = Detail::estimate_clock_resolution<Clock>(iters);
  5705. auto cost = Detail::estimate_clock_cost<Clock>(resolution.mean);
  5706. env = new Environment<FloatDuration<Clock>>{ resolution, cost };
  5707. return *env;
  5708. }
  5709. } // namespace Detail
  5710. } // namespace Benchmark
  5711. } // namespace Catch
  5712. // end catch_estimate_clock.hpp
  5713. // start catch_analyse.hpp
  5714. // Run and analyse one benchmark
  5715. // start catch_sample_analysis.hpp
  5716. // Benchmark results
  5717. #include <algorithm>
  5718. #include <vector>
  5719. #include <string>
  5720. #include <iterator>
  5721. namespace Catch {
  5722. namespace Benchmark {
  5723. template <typename Duration>
  5724. struct SampleAnalysis {
  5725. std::vector<Duration> samples;
  5726. Estimate<Duration> mean;
  5727. Estimate<Duration> standard_deviation;
  5728. OutlierClassification outliers;
  5729. double outlier_variance;
  5730. template <typename Duration2>
  5731. operator SampleAnalysis<Duration2>() const {
  5732. std::vector<Duration2> samples2;
  5733. samples2.reserve(samples.size());
  5734. std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration d) { return Duration2(d); });
  5735. return {
  5736. std::move(samples2),
  5737. mean,
  5738. standard_deviation,
  5739. outliers,
  5740. outlier_variance,
  5741. };
  5742. }
  5743. };
  5744. } // namespace Benchmark
  5745. } // namespace Catch
  5746. // end catch_sample_analysis.hpp
  5747. #include <algorithm>
  5748. #include <iterator>
  5749. #include <vector>
  5750. namespace Catch {
  5751. namespace Benchmark {
  5752. namespace Detail {
  5753. template <typename Duration, typename Iterator>
  5754. SampleAnalysis<Duration> analyse(const IConfig &cfg, Environment<Duration>, Iterator first, Iterator last) {
  5755. if (!cfg.benchmarkNoAnalysis()) {
  5756. std::vector<double> samples;
  5757. samples.reserve(last - first);
  5758. std::transform(first, last, std::back_inserter(samples), [](Duration d) { return d.count(); });
  5759. auto analysis = Catch::Benchmark::Detail::analyse_samples(cfg.benchmarkConfidenceInterval(), cfg.benchmarkResamples(), samples.begin(), samples.end());
  5760. auto outliers = Catch::Benchmark::Detail::classify_outliers(samples.begin(), samples.end());
  5761. auto wrap_estimate = [](Estimate<double> e) {
  5762. return Estimate<Duration> {
  5763. Duration(e.point),
  5764. Duration(e.lower_bound),
  5765. Duration(e.upper_bound),
  5766. e.confidence_interval,
  5767. };
  5768. };
  5769. std::vector<Duration> samples2;
  5770. samples2.reserve(samples.size());
  5771. std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](double d) { return Duration(d); });
  5772. return {
  5773. std::move(samples2),
  5774. wrap_estimate(analysis.mean),
  5775. wrap_estimate(analysis.standard_deviation),
  5776. outliers,
  5777. analysis.outlier_variance,
  5778. };
  5779. } else {
  5780. std::vector<Duration> samples;
  5781. samples.reserve(last - first);
  5782. Duration mean = Duration(0);
  5783. int i = 0;
  5784. for (auto it = first; it < last; ++it, ++i) {
  5785. samples.push_back(Duration(*it));
  5786. mean += Duration(*it);
  5787. }
  5788. mean /= i;
  5789. return {
  5790. std::move(samples),
  5791. Estimate<Duration>{mean, mean, mean, 0.0},
  5792. Estimate<Duration>{Duration(0), Duration(0), Duration(0), 0.0},
  5793. OutlierClassification{},
  5794. 0.0
  5795. };
  5796. }
  5797. }
  5798. } // namespace Detail
  5799. } // namespace Benchmark
  5800. } // namespace Catch
  5801. // end catch_analyse.hpp
  5802. #include <algorithm>
  5803. #include <functional>
  5804. #include <string>
  5805. #include <vector>
  5806. #include <cmath>
  5807. namespace Catch {
  5808. namespace Benchmark {
  5809. struct Benchmark {
  5810. Benchmark(std::string &&name)
  5811. : name(std::move(name)) {}
  5812. template <class FUN>
  5813. Benchmark(std::string &&name, FUN &&func)
  5814. : fun(std::move(func)), name(std::move(name)) {}
  5815. template <typename Clock>
  5816. ExecutionPlan<FloatDuration<Clock>> prepare(const IConfig &cfg, Environment<FloatDuration<Clock>> env) const {
  5817. auto min_time = env.clock_resolution.mean * Detail::minimum_ticks;
  5818. auto run_time = std::max(min_time, std::chrono::duration_cast<decltype(min_time)>(Detail::warmup_time));
  5819. auto&& test = Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(run_time), 1, fun);
  5820. int new_iters = static_cast<int>(std::ceil(min_time * test.iterations / test.elapsed));
  5821. return { new_iters, test.elapsed / test.iterations * new_iters * cfg.benchmarkSamples(), fun, std::chrono::duration_cast<FloatDuration<Clock>>(Detail::warmup_time), Detail::warmup_iterations };
  5822. }
  5823. template <typename Clock = default_clock>
  5824. void run() {
  5825. IConfigPtr cfg = getCurrentContext().getConfig();
  5826. auto env = Detail::measure_environment<Clock>();
  5827. getResultCapture().benchmarkPreparing(name);
  5828. CATCH_TRY{
  5829. auto plan = user_code([&] {
  5830. return prepare<Clock>(*cfg, env);
  5831. });
  5832. BenchmarkInfo info {
  5833. name,
  5834. plan.estimated_duration.count(),
  5835. plan.iterations_per_sample,
  5836. cfg->benchmarkSamples(),
  5837. cfg->benchmarkResamples(),
  5838. env.clock_resolution.mean.count(),
  5839. env.clock_cost.mean.count()
  5840. };
  5841. getResultCapture().benchmarkStarting(info);
  5842. auto samples = user_code([&] {
  5843. return plan.template run<Clock>(*cfg, env);
  5844. });
  5845. auto analysis = Detail::analyse(*cfg, env, samples.begin(), samples.end());
  5846. BenchmarkStats<std::chrono::duration<double, std::nano>> stats{ info, analysis.samples, analysis.mean, analysis.standard_deviation, analysis.outliers, analysis.outlier_variance };
  5847. getResultCapture().benchmarkEnded(stats);
  5848. } CATCH_CATCH_ALL{
  5849. if (translateActiveException() != Detail::benchmarkErrorMsg) // benchmark errors have been reported, otherwise rethrow.
  5850. std::rethrow_exception(std::current_exception());
  5851. }
  5852. }
  5853. // sets lambda to be used in fun *and* executes benchmark!
  5854. template <typename Fun,
  5855. typename std::enable_if<!Detail::is_related<Fun, Benchmark>::value, int>::type = 0>
  5856. Benchmark & operator=(Fun func) {
  5857. fun = Detail::BenchmarkFunction(func);
  5858. run();
  5859. return *this;
  5860. }
  5861. explicit operator bool() {
  5862. return true;
  5863. }
  5864. private:
  5865. Detail::BenchmarkFunction fun;
  5866. std::string name;
  5867. };
  5868. }
  5869. } // namespace Catch
  5870. #define INTERNAL_CATCH_GET_1_ARG(arg1, arg2, ...) arg1
  5871. #define INTERNAL_CATCH_GET_2_ARG(arg1, arg2, ...) arg2
  5872. #define INTERNAL_CATCH_BENCHMARK(BenchmarkName, name, benchmarkIndex)\
  5873. if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \
  5874. BenchmarkName = [&](int benchmarkIndex)
  5875. #define INTERNAL_CATCH_BENCHMARK_ADVANCED(BenchmarkName, name)\
  5876. if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \
  5877. BenchmarkName = [&]
  5878. // end catch_benchmark.hpp
  5879. #endif
  5880. #endif // ! CATCH_CONFIG_IMPL_ONLY
  5881. #ifdef CATCH_IMPL
  5882. // start catch_impl.hpp
  5883. #ifdef __clang__
  5884. #pragma clang diagnostic push
  5885. #pragma clang diagnostic ignored "-Wweak-vtables"
  5886. #endif
  5887. // Keep these here for external reporters
  5888. // start catch_test_case_tracker.h
  5889. #include <string>
  5890. #include <vector>
  5891. #include <memory>
  5892. namespace Catch {
  5893. namespace TestCaseTracking {
  5894. struct NameAndLocation {
  5895. std::string name;
  5896. SourceLineInfo location;
  5897. NameAndLocation( std::string const& _name, SourceLineInfo const& _location );
  5898. };
  5899. struct ITracker;
  5900. using ITrackerPtr = std::shared_ptr<ITracker>;
  5901. struct ITracker {
  5902. virtual ~ITracker();
  5903. // static queries
  5904. virtual NameAndLocation const& nameAndLocation() const = 0;
  5905. // dynamic queries
  5906. virtual bool isComplete() const = 0; // Successfully completed or failed
  5907. virtual bool isSuccessfullyCompleted() const = 0;
  5908. virtual bool isOpen() const = 0; // Started but not complete
  5909. virtual bool hasChildren() const = 0;
  5910. virtual ITracker& parent() = 0;
  5911. // actions
  5912. virtual void close() = 0; // Successfully complete
  5913. virtual void fail() = 0;
  5914. virtual void markAsNeedingAnotherRun() = 0;
  5915. virtual void addChild( ITrackerPtr const& child ) = 0;
  5916. virtual ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) = 0;
  5917. virtual void openChild() = 0;
  5918. // Debug/ checking
  5919. virtual bool isSectionTracker() const = 0;
  5920. virtual bool isGeneratorTracker() const = 0;
  5921. };
  5922. class TrackerContext {
  5923. enum RunState {
  5924. NotStarted,
  5925. Executing,
  5926. CompletedCycle
  5927. };
  5928. ITrackerPtr m_rootTracker;
  5929. ITracker* m_currentTracker = nullptr;
  5930. RunState m_runState = NotStarted;
  5931. public:
  5932. ITracker& startRun();
  5933. void endRun();
  5934. void startCycle();
  5935. void completeCycle();
  5936. bool completedCycle() const;
  5937. ITracker& currentTracker();
  5938. void setCurrentTracker( ITracker* tracker );
  5939. };
  5940. class TrackerBase : public ITracker {
  5941. protected:
  5942. enum CycleState {
  5943. NotStarted,
  5944. Executing,
  5945. ExecutingChildren,
  5946. NeedsAnotherRun,
  5947. CompletedSuccessfully,
  5948. Failed
  5949. };
  5950. using Children = std::vector<ITrackerPtr>;
  5951. NameAndLocation m_nameAndLocation;
  5952. TrackerContext& m_ctx;
  5953. ITracker* m_parent;
  5954. Children m_children;
  5955. CycleState m_runState = NotStarted;
  5956. public:
  5957. TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  5958. NameAndLocation const& nameAndLocation() const override;
  5959. bool isComplete() const override;
  5960. bool isSuccessfullyCompleted() const override;
  5961. bool isOpen() const override;
  5962. bool hasChildren() const override;
  5963. void addChild( ITrackerPtr const& child ) override;
  5964. ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) override;
  5965. ITracker& parent() override;
  5966. void openChild() override;
  5967. bool isSectionTracker() const override;
  5968. bool isGeneratorTracker() const override;
  5969. void open();
  5970. void close() override;
  5971. void fail() override;
  5972. void markAsNeedingAnotherRun() override;
  5973. private:
  5974. void moveToParent();
  5975. void moveToThis();
  5976. };
  5977. class SectionTracker : public TrackerBase {
  5978. std::vector<std::string> m_filters;
  5979. public:
  5980. SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  5981. bool isSectionTracker() const override;
  5982. bool isComplete() const override;
  5983. static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation );
  5984. void tryOpen();
  5985. void addInitialFilters( std::vector<std::string> const& filters );
  5986. void addNextFilters( std::vector<std::string> const& filters );
  5987. };
  5988. } // namespace TestCaseTracking
  5989. using TestCaseTracking::ITracker;
  5990. using TestCaseTracking::TrackerContext;
  5991. using TestCaseTracking::SectionTracker;
  5992. } // namespace Catch
  5993. // end catch_test_case_tracker.h
  5994. // start catch_leak_detector.h
  5995. namespace Catch {
  5996. struct LeakDetector {
  5997. LeakDetector();
  5998. ~LeakDetector();
  5999. };
  6000. }
  6001. // end catch_leak_detector.h
  6002. // Cpp files will be included in the single-header file here
  6003. // start catch_stats.cpp
  6004. // Statistical analysis tools
  6005. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  6006. #include <cassert>
  6007. #include <random>
  6008. #if defined(CATCH_CONFIG_USE_ASYNC)
  6009. #include <future>
  6010. #endif
  6011. namespace {
  6012. double erf_inv(double x) {
  6013. // Code accompanying the article "Approximating the erfinv function" in GPU Computing Gems, Volume 2
  6014. double w, p;
  6015. w = -log((1.0 - x) * (1.0 + x));
  6016. if (w < 6.250000) {
  6017. w = w - 3.125000;
  6018. p = -3.6444120640178196996e-21;
  6019. p = -1.685059138182016589e-19 + p * w;
  6020. p = 1.2858480715256400167e-18 + p * w;
  6021. p = 1.115787767802518096e-17 + p * w;
  6022. p = -1.333171662854620906e-16 + p * w;
  6023. p = 2.0972767875968561637e-17 + p * w;
  6024. p = 6.6376381343583238325e-15 + p * w;
  6025. p = -4.0545662729752068639e-14 + p * w;
  6026. p = -8.1519341976054721522e-14 + p * w;
  6027. p = 2.6335093153082322977e-12 + p * w;
  6028. p = -1.2975133253453532498e-11 + p * w;
  6029. p = -5.4154120542946279317e-11 + p * w;
  6030. p = 1.051212273321532285e-09 + p * w;
  6031. p = -4.1126339803469836976e-09 + p * w;
  6032. p = -2.9070369957882005086e-08 + p * w;
  6033. p = 4.2347877827932403518e-07 + p * w;
  6034. p = -1.3654692000834678645e-06 + p * w;
  6035. p = -1.3882523362786468719e-05 + p * w;
  6036. p = 0.0001867342080340571352 + p * w;
  6037. p = -0.00074070253416626697512 + p * w;
  6038. p = -0.0060336708714301490533 + p * w;
  6039. p = 0.24015818242558961693 + p * w;
  6040. p = 1.6536545626831027356 + p * w;
  6041. } else if (w < 16.000000) {
  6042. w = sqrt(w) - 3.250000;
  6043. p = 2.2137376921775787049e-09;
  6044. p = 9.0756561938885390979e-08 + p * w;
  6045. p = -2.7517406297064545428e-07 + p * w;
  6046. p = 1.8239629214389227755e-08 + p * w;
  6047. p = 1.5027403968909827627e-06 + p * w;
  6048. p = -4.013867526981545969e-06 + p * w;
  6049. p = 2.9234449089955446044e-06 + p * w;
  6050. p = 1.2475304481671778723e-05 + p * w;
  6051. p = -4.7318229009055733981e-05 + p * w;
  6052. p = 6.8284851459573175448e-05 + p * w;
  6053. p = 2.4031110387097893999e-05 + p * w;
  6054. p = -0.0003550375203628474796 + p * w;
  6055. p = 0.00095328937973738049703 + p * w;
  6056. p = -0.0016882755560235047313 + p * w;
  6057. p = 0.0024914420961078508066 + p * w;
  6058. p = -0.0037512085075692412107 + p * w;
  6059. p = 0.005370914553590063617 + p * w;
  6060. p = 1.0052589676941592334 + p * w;
  6061. p = 3.0838856104922207635 + p * w;
  6062. } else {
  6063. w = sqrt(w) - 5.000000;
  6064. p = -2.7109920616438573243e-11;
  6065. p = -2.5556418169965252055e-10 + p * w;
  6066. p = 1.5076572693500548083e-09 + p * w;
  6067. p = -3.7894654401267369937e-09 + p * w;
  6068. p = 7.6157012080783393804e-09 + p * w;
  6069. p = -1.4960026627149240478e-08 + p * w;
  6070. p = 2.9147953450901080826e-08 + p * w;
  6071. p = -6.7711997758452339498e-08 + p * w;
  6072. p = 2.2900482228026654717e-07 + p * w;
  6073. p = -9.9298272942317002539e-07 + p * w;
  6074. p = 4.5260625972231537039e-06 + p * w;
  6075. p = -1.9681778105531670567e-05 + p * w;
  6076. p = 7.5995277030017761139e-05 + p * w;
  6077. p = -0.00021503011930044477347 + p * w;
  6078. p = -0.00013871931833623122026 + p * w;
  6079. p = 1.0103004648645343977 + p * w;
  6080. p = 4.8499064014085844221 + p * w;
  6081. }
  6082. return p * x;
  6083. }
  6084. double standard_deviation(std::vector<double>::iterator first, std::vector<double>::iterator last) {
  6085. auto m = Catch::Benchmark::Detail::mean(first, last);
  6086. double variance = std::accumulate(first, last, 0., [m](double a, double b) {
  6087. double diff = b - m;
  6088. return a + diff * diff;
  6089. }) / (last - first);
  6090. return std::sqrt(variance);
  6091. }
  6092. }
  6093. namespace Catch {
  6094. namespace Benchmark {
  6095. namespace Detail {
  6096. double weighted_average_quantile(int k, int q, std::vector<double>::iterator first, std::vector<double>::iterator last) {
  6097. auto count = last - first;
  6098. double idx = (count - 1) * k / static_cast<double>(q);
  6099. int j = static_cast<int>(idx);
  6100. double g = idx - j;
  6101. std::nth_element(first, first + j, last);
  6102. auto xj = first[j];
  6103. if (g == 0) return xj;
  6104. auto xj1 = *std::min_element(first + (j + 1), last);
  6105. return xj + g * (xj1 - xj);
  6106. }
  6107. double erfc_inv(double x) {
  6108. return erf_inv(1.0 - x);
  6109. }
  6110. double normal_quantile(double p) {
  6111. static const double ROOT_TWO = std::sqrt(2.0);
  6112. double result = 0.0;
  6113. assert(p >= 0 && p <= 1);
  6114. if (p < 0 || p > 1) {
  6115. return result;
  6116. }
  6117. result = -erfc_inv(2.0 * p);
  6118. // result *= normal distribution standard deviation (1.0) * sqrt(2)
  6119. result *= /*sd * */ ROOT_TWO;
  6120. // result += normal disttribution mean (0)
  6121. return result;
  6122. }
  6123. double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n) {
  6124. double sb = stddev.point;
  6125. double mn = mean.point / n;
  6126. double mg_min = mn / 2.;
  6127. double sg = std::min(mg_min / 4., sb / std::sqrt(n));
  6128. double sg2 = sg * sg;
  6129. double sb2 = sb * sb;
  6130. auto c_max = [n, mn, sb2, sg2](double x) -> double {
  6131. double k = mn - x;
  6132. double d = k * k;
  6133. double nd = n * d;
  6134. double k0 = -n * nd;
  6135. double k1 = sb2 - n * sg2 + nd;
  6136. double det = k1 * k1 - 4 * sg2 * k0;
  6137. return (int)(-2. * k0 / (k1 + std::sqrt(det)));
  6138. };
  6139. auto var_out = [n, sb2, sg2](double c) {
  6140. double nc = n - c;
  6141. return (nc / n) * (sb2 - nc * sg2);
  6142. };
  6143. return std::min(var_out(1), var_out(std::min(c_max(0.), c_max(mg_min)))) / sb2;
  6144. }
  6145. bootstrap_analysis analyse_samples(double confidence_level, int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last) {
  6146. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  6147. static std::random_device entropy;
  6148. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  6149. auto n = static_cast<int>(last - first); // seriously, one can't use integral types without hell in C++
  6150. auto mean = &Detail::mean<std::vector<double>::iterator>;
  6151. auto stddev = &standard_deviation;
  6152. #if defined(CATCH_CONFIG_USE_ASYNC)
  6153. auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
  6154. auto seed = entropy();
  6155. return std::async(std::launch::async, [=] {
  6156. std::mt19937 rng(seed);
  6157. auto resampled = resample(rng, n_resamples, first, last, f);
  6158. return bootstrap(confidence_level, first, last, resampled, f);
  6159. });
  6160. };
  6161. auto mean_future = Estimate(mean);
  6162. auto stddev_future = Estimate(stddev);
  6163. auto mean_estimate = mean_future.get();
  6164. auto stddev_estimate = stddev_future.get();
  6165. #else
  6166. auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
  6167. auto seed = entropy();
  6168. std::mt19937 rng(seed);
  6169. auto resampled = resample(rng, n_resamples, first, last, f);
  6170. return bootstrap(confidence_level, first, last, resampled, f);
  6171. };
  6172. auto mean_estimate = Estimate(mean);
  6173. auto stddev_estimate = Estimate(stddev);
  6174. #endif // CATCH_USE_ASYNC
  6175. double outlier_variance = Detail::outlier_variance(mean_estimate, stddev_estimate, n);
  6176. return { mean_estimate, stddev_estimate, outlier_variance };
  6177. }
  6178. } // namespace Detail
  6179. } // namespace Benchmark
  6180. } // namespace Catch
  6181. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  6182. // end catch_stats.cpp
  6183. // start catch_approx.cpp
  6184. #include <cmath>
  6185. #include <limits>
  6186. namespace {
  6187. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  6188. // But without the subtraction to allow for INFINITY in comparison
  6189. bool marginComparison(double lhs, double rhs, double margin) {
  6190. return (lhs + margin >= rhs) && (rhs + margin >= lhs);
  6191. }
  6192. }
  6193. namespace Catch {
  6194. namespace Detail {
  6195. Approx::Approx ( double value )
  6196. : m_epsilon( std::numeric_limits<float>::epsilon()*100 ),
  6197. m_margin( 0.0 ),
  6198. m_scale( 0.0 ),
  6199. m_value( value )
  6200. {}
  6201. Approx Approx::custom() {
  6202. return Approx( 0 );
  6203. }
  6204. Approx Approx::operator-() const {
  6205. auto temp(*this);
  6206. temp.m_value = -temp.m_value;
  6207. return temp;
  6208. }
  6209. std::string Approx::toString() const {
  6210. ReusableStringStream rss;
  6211. rss << "Approx( " << ::Catch::Detail::stringify( m_value ) << " )";
  6212. return rss.str();
  6213. }
  6214. bool Approx::equalityComparisonImpl(const double other) const {
  6215. // First try with fixed margin, then compute margin based on epsilon, scale and Approx's value
  6216. // Thanks to Richard Harris for his help refining the scaled margin value
  6217. return marginComparison(m_value, other, m_margin) || marginComparison(m_value, other, m_epsilon * (m_scale + std::fabs(m_value)));
  6218. }
  6219. void Approx::setMargin(double newMargin) {
  6220. CATCH_ENFORCE(newMargin >= 0,
  6221. "Invalid Approx::margin: " << newMargin << '.'
  6222. << " Approx::Margin has to be non-negative.");
  6223. m_margin = newMargin;
  6224. }
  6225. void Approx::setEpsilon(double newEpsilon) {
  6226. CATCH_ENFORCE(newEpsilon >= 0 && newEpsilon <= 1.0,
  6227. "Invalid Approx::epsilon: " << newEpsilon << '.'
  6228. << " Approx::epsilon has to be in [0, 1]");
  6229. m_epsilon = newEpsilon;
  6230. }
  6231. } // end namespace Detail
  6232. namespace literals {
  6233. Detail::Approx operator "" _a(long double val) {
  6234. return Detail::Approx(val);
  6235. }
  6236. Detail::Approx operator "" _a(unsigned long long val) {
  6237. return Detail::Approx(val);
  6238. }
  6239. } // end namespace literals
  6240. std::string StringMaker<Catch::Detail::Approx>::convert(Catch::Detail::Approx const& value) {
  6241. return value.toString();
  6242. }
  6243. } // end namespace Catch
  6244. // end catch_approx.cpp
  6245. // start catch_assertionhandler.cpp
  6246. // start catch_debugger.h
  6247. namespace Catch {
  6248. bool isDebuggerActive();
  6249. }
  6250. #ifdef CATCH_PLATFORM_MAC
  6251. #define CATCH_TRAP() __asm__("int $3\n" : : ) /* NOLINT */
  6252. #elif defined(CATCH_PLATFORM_LINUX)
  6253. // If we can use inline assembler, do it because this allows us to break
  6254. // directly at the location of the failing check instead of breaking inside
  6255. // raise() called from it, i.e. one stack frame below.
  6256. #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64))
  6257. #define CATCH_TRAP() asm volatile ("int $3") /* NOLINT */
  6258. #else // Fall back to the generic way.
  6259. #include <signal.h>
  6260. #define CATCH_TRAP() raise(SIGTRAP)
  6261. #endif
  6262. #elif defined(_MSC_VER)
  6263. #define CATCH_TRAP() __debugbreak()
  6264. #elif defined(__MINGW32__)
  6265. extern "C" __declspec(dllimport) void __stdcall DebugBreak();
  6266. #define CATCH_TRAP() DebugBreak()
  6267. #endif
  6268. #ifdef CATCH_TRAP
  6269. #define CATCH_BREAK_INTO_DEBUGGER() []{ if( Catch::isDebuggerActive() ) { CATCH_TRAP(); } }()
  6270. #else
  6271. #define CATCH_BREAK_INTO_DEBUGGER() []{}()
  6272. #endif
  6273. // end catch_debugger.h
  6274. // start catch_run_context.h
  6275. // start catch_fatal_condition.h
  6276. // start catch_windows_h_proxy.h
  6277. #if defined(CATCH_PLATFORM_WINDOWS)
  6278. #if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX)
  6279. # define CATCH_DEFINED_NOMINMAX
  6280. # define NOMINMAX
  6281. #endif
  6282. #if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN)
  6283. # define CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  6284. # define WIN32_LEAN_AND_MEAN
  6285. #endif
  6286. #ifdef __AFXDLL
  6287. #include <AfxWin.h>
  6288. #else
  6289. #include <windows.h>
  6290. #endif
  6291. #ifdef CATCH_DEFINED_NOMINMAX
  6292. # undef NOMINMAX
  6293. #endif
  6294. #ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  6295. # undef WIN32_LEAN_AND_MEAN
  6296. #endif
  6297. #endif // defined(CATCH_PLATFORM_WINDOWS)
  6298. // end catch_windows_h_proxy.h
  6299. #if defined( CATCH_CONFIG_WINDOWS_SEH )
  6300. namespace Catch {
  6301. struct FatalConditionHandler {
  6302. static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo);
  6303. FatalConditionHandler();
  6304. static void reset();
  6305. ~FatalConditionHandler();
  6306. private:
  6307. static bool isSet;
  6308. static ULONG guaranteeSize;
  6309. static PVOID exceptionHandlerHandle;
  6310. };
  6311. } // namespace Catch
  6312. #elif defined ( CATCH_CONFIG_POSIX_SIGNALS )
  6313. #include <signal.h>
  6314. namespace Catch {
  6315. struct FatalConditionHandler {
  6316. static bool isSet;
  6317. static struct sigaction oldSigActions[];
  6318. static stack_t oldSigStack;
  6319. static char altStackMem[];
  6320. static void handleSignal( int sig );
  6321. FatalConditionHandler();
  6322. ~FatalConditionHandler();
  6323. static void reset();
  6324. };
  6325. } // namespace Catch
  6326. #else
  6327. namespace Catch {
  6328. struct FatalConditionHandler {
  6329. void reset();
  6330. };
  6331. }
  6332. #endif
  6333. // end catch_fatal_condition.h
  6334. #include <string>
  6335. namespace Catch {
  6336. struct IMutableContext;
  6337. ///////////////////////////////////////////////////////////////////////////
  6338. class RunContext : public IResultCapture, public IRunner {
  6339. public:
  6340. RunContext( RunContext const& ) = delete;
  6341. RunContext& operator =( RunContext const& ) = delete;
  6342. explicit RunContext( IConfigPtr const& _config, IStreamingReporterPtr&& reporter );
  6343. ~RunContext() override;
  6344. void testGroupStarting( std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount );
  6345. void testGroupEnded( std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount );
  6346. Totals runTest(TestCase const& testCase);
  6347. IConfigPtr config() const;
  6348. IStreamingReporter& reporter() const;
  6349. public: // IResultCapture
  6350. // Assertion handlers
  6351. void handleExpr
  6352. ( AssertionInfo const& info,
  6353. ITransientExpression const& expr,
  6354. AssertionReaction& reaction ) override;
  6355. void handleMessage
  6356. ( AssertionInfo const& info,
  6357. ResultWas::OfType resultType,
  6358. StringRef const& message,
  6359. AssertionReaction& reaction ) override;
  6360. void handleUnexpectedExceptionNotThrown
  6361. ( AssertionInfo const& info,
  6362. AssertionReaction& reaction ) override;
  6363. void handleUnexpectedInflightException
  6364. ( AssertionInfo const& info,
  6365. std::string const& message,
  6366. AssertionReaction& reaction ) override;
  6367. void handleIncomplete
  6368. ( AssertionInfo const& info ) override;
  6369. void handleNonExpr
  6370. ( AssertionInfo const &info,
  6371. ResultWas::OfType resultType,
  6372. AssertionReaction &reaction ) override;
  6373. bool sectionStarted( SectionInfo const& sectionInfo, Counts& assertions ) override;
  6374. void sectionEnded( SectionEndInfo const& endInfo ) override;
  6375. void sectionEndedEarly( SectionEndInfo const& endInfo ) override;
  6376. auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& override;
  6377. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  6378. void benchmarkPreparing( std::string const& name ) override;
  6379. void benchmarkStarting( BenchmarkInfo const& info ) override;
  6380. void benchmarkEnded( BenchmarkStats<> const& stats ) override;
  6381. void benchmarkFailed( std::string const& error ) override;
  6382. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  6383. void pushScopedMessage( MessageInfo const& message ) override;
  6384. void popScopedMessage( MessageInfo const& message ) override;
  6385. void emplaceUnscopedMessage( MessageBuilder const& builder ) override;
  6386. std::string getCurrentTestName() const override;
  6387. const AssertionResult* getLastResult() const override;
  6388. void exceptionEarlyReported() override;
  6389. void handleFatalErrorCondition( StringRef message ) override;
  6390. bool lastAssertionPassed() override;
  6391. void assertionPassed() override;
  6392. public:
  6393. // !TBD We need to do this another way!
  6394. bool aborting() const final;
  6395. private:
  6396. void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr );
  6397. void invokeActiveTestCase();
  6398. void resetAssertionInfo();
  6399. bool testForMissingAssertions( Counts& assertions );
  6400. void assertionEnded( AssertionResult const& result );
  6401. void reportExpr
  6402. ( AssertionInfo const &info,
  6403. ResultWas::OfType resultType,
  6404. ITransientExpression const *expr,
  6405. bool negated );
  6406. void populateReaction( AssertionReaction& reaction );
  6407. private:
  6408. void handleUnfinishedSections();
  6409. TestRunInfo m_runInfo;
  6410. IMutableContext& m_context;
  6411. TestCase const* m_activeTestCase = nullptr;
  6412. ITracker* m_testCaseTracker = nullptr;
  6413. Option<AssertionResult> m_lastResult;
  6414. IConfigPtr m_config;
  6415. Totals m_totals;
  6416. IStreamingReporterPtr m_reporter;
  6417. std::vector<MessageInfo> m_messages;
  6418. std::vector<ScopedMessage> m_messageScopes; /* Keeps owners of so-called unscoped messages. */
  6419. AssertionInfo m_lastAssertionInfo;
  6420. std::vector<SectionEndInfo> m_unfinishedSections;
  6421. std::vector<ITracker*> m_activeSections;
  6422. TrackerContext m_trackerContext;
  6423. bool m_lastAssertionPassed = false;
  6424. bool m_shouldReportUnexpected = true;
  6425. bool m_includeSuccessfulResults;
  6426. };
  6427. } // end namespace Catch
  6428. // end catch_run_context.h
  6429. namespace Catch {
  6430. namespace {
  6431. auto operator <<( std::ostream& os, ITransientExpression const& expr ) -> std::ostream& {
  6432. expr.streamReconstructedExpression( os );
  6433. return os;
  6434. }
  6435. }
  6436. LazyExpression::LazyExpression( bool isNegated )
  6437. : m_isNegated( isNegated )
  6438. {}
  6439. LazyExpression::LazyExpression( LazyExpression const& other ) : m_isNegated( other.m_isNegated ) {}
  6440. LazyExpression::operator bool() const {
  6441. return m_transientExpression != nullptr;
  6442. }
  6443. auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream& {
  6444. if( lazyExpr.m_isNegated )
  6445. os << "!";
  6446. if( lazyExpr ) {
  6447. if( lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression() )
  6448. os << "(" << *lazyExpr.m_transientExpression << ")";
  6449. else
  6450. os << *lazyExpr.m_transientExpression;
  6451. }
  6452. else {
  6453. os << "{** error - unchecked empty expression requested **}";
  6454. }
  6455. return os;
  6456. }
  6457. AssertionHandler::AssertionHandler
  6458. ( StringRef const& macroName,
  6459. SourceLineInfo const& lineInfo,
  6460. StringRef capturedExpression,
  6461. ResultDisposition::Flags resultDisposition )
  6462. : m_assertionInfo{ macroName, lineInfo, capturedExpression, resultDisposition },
  6463. m_resultCapture( getResultCapture() )
  6464. {}
  6465. void AssertionHandler::handleExpr( ITransientExpression const& expr ) {
  6466. m_resultCapture.handleExpr( m_assertionInfo, expr, m_reaction );
  6467. }
  6468. void AssertionHandler::handleMessage(ResultWas::OfType resultType, StringRef const& message) {
  6469. m_resultCapture.handleMessage( m_assertionInfo, resultType, message, m_reaction );
  6470. }
  6471. auto AssertionHandler::allowThrows() const -> bool {
  6472. return getCurrentContext().getConfig()->allowThrows();
  6473. }
  6474. void AssertionHandler::complete() {
  6475. setCompleted();
  6476. if( m_reaction.shouldDebugBreak ) {
  6477. // If you find your debugger stopping you here then go one level up on the
  6478. // call-stack for the code that caused it (typically a failed assertion)
  6479. // (To go back to the test and change execution, jump over the throw, next)
  6480. CATCH_BREAK_INTO_DEBUGGER();
  6481. }
  6482. if (m_reaction.shouldThrow) {
  6483. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  6484. throw Catch::TestFailureException();
  6485. #else
  6486. CATCH_ERROR( "Test failure requires aborting test!" );
  6487. #endif
  6488. }
  6489. }
  6490. void AssertionHandler::setCompleted() {
  6491. m_completed = true;
  6492. }
  6493. void AssertionHandler::handleUnexpectedInflightException() {
  6494. m_resultCapture.handleUnexpectedInflightException( m_assertionInfo, Catch::translateActiveException(), m_reaction );
  6495. }
  6496. void AssertionHandler::handleExceptionThrownAsExpected() {
  6497. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  6498. }
  6499. void AssertionHandler::handleExceptionNotThrownAsExpected() {
  6500. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  6501. }
  6502. void AssertionHandler::handleUnexpectedExceptionNotThrown() {
  6503. m_resultCapture.handleUnexpectedExceptionNotThrown( m_assertionInfo, m_reaction );
  6504. }
  6505. void AssertionHandler::handleThrowingCallSkipped() {
  6506. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  6507. }
  6508. // This is the overload that takes a string and infers the Equals matcher from it
  6509. // The more general overload, that takes any string matcher, is in catch_capture_matchers.cpp
  6510. void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString ) {
  6511. handleExceptionMatchExpr( handler, Matchers::Equals( str ), matcherString );
  6512. }
  6513. } // namespace Catch
  6514. // end catch_assertionhandler.cpp
  6515. // start catch_assertionresult.cpp
  6516. namespace Catch {
  6517. AssertionResultData::AssertionResultData(ResultWas::OfType _resultType, LazyExpression const & _lazyExpression):
  6518. lazyExpression(_lazyExpression),
  6519. resultType(_resultType) {}
  6520. std::string AssertionResultData::reconstructExpression() const {
  6521. if( reconstructedExpression.empty() ) {
  6522. if( lazyExpression ) {
  6523. ReusableStringStream rss;
  6524. rss << lazyExpression;
  6525. reconstructedExpression = rss.str();
  6526. }
  6527. }
  6528. return reconstructedExpression;
  6529. }
  6530. AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data )
  6531. : m_info( info ),
  6532. m_resultData( data )
  6533. {}
  6534. // Result was a success
  6535. bool AssertionResult::succeeded() const {
  6536. return Catch::isOk( m_resultData.resultType );
  6537. }
  6538. // Result was a success, or failure is suppressed
  6539. bool AssertionResult::isOk() const {
  6540. return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition );
  6541. }
  6542. ResultWas::OfType AssertionResult::getResultType() const {
  6543. return m_resultData.resultType;
  6544. }
  6545. bool AssertionResult::hasExpression() const {
  6546. return m_info.capturedExpression[0] != 0;
  6547. }
  6548. bool AssertionResult::hasMessage() const {
  6549. return !m_resultData.message.empty();
  6550. }
  6551. std::string AssertionResult::getExpression() const {
  6552. if( isFalseTest( m_info.resultDisposition ) )
  6553. return "!(" + m_info.capturedExpression + ")";
  6554. else
  6555. return m_info.capturedExpression;
  6556. }
  6557. std::string AssertionResult::getExpressionInMacro() const {
  6558. std::string expr;
  6559. if( m_info.macroName[0] == 0 )
  6560. expr = m_info.capturedExpression;
  6561. else {
  6562. expr.reserve( m_info.macroName.size() + m_info.capturedExpression.size() + 4 );
  6563. expr += m_info.macroName;
  6564. expr += "( ";
  6565. expr += m_info.capturedExpression;
  6566. expr += " )";
  6567. }
  6568. return expr;
  6569. }
  6570. bool AssertionResult::hasExpandedExpression() const {
  6571. return hasExpression() && getExpandedExpression() != getExpression();
  6572. }
  6573. std::string AssertionResult::getExpandedExpression() const {
  6574. std::string expr = m_resultData.reconstructExpression();
  6575. return expr.empty()
  6576. ? getExpression()
  6577. : expr;
  6578. }
  6579. std::string AssertionResult::getMessage() const {
  6580. return m_resultData.message;
  6581. }
  6582. SourceLineInfo AssertionResult::getSourceInfo() const {
  6583. return m_info.lineInfo;
  6584. }
  6585. StringRef AssertionResult::getTestMacroName() const {
  6586. return m_info.macroName;
  6587. }
  6588. } // end namespace Catch
  6589. // end catch_assertionresult.cpp
  6590. // start catch_capture_matchers.cpp
  6591. namespace Catch {
  6592. using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
  6593. // This is the general overload that takes a any string matcher
  6594. // There is another overload, in catch_assertionhandler.h/.cpp, that only takes a string and infers
  6595. // the Equals matcher (so the header does not mention matchers)
  6596. void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString ) {
  6597. std::string exceptionMessage = Catch::translateActiveException();
  6598. MatchExpr<std::string, StringMatcher const&> expr( exceptionMessage, matcher, matcherString );
  6599. handler.handleExpr( expr );
  6600. }
  6601. } // namespace Catch
  6602. // end catch_capture_matchers.cpp
  6603. // start catch_commandline.cpp
  6604. // start catch_commandline.h
  6605. // start catch_clara.h
  6606. // Use Catch's value for console width (store Clara's off to the side, if present)
  6607. #ifdef CLARA_CONFIG_CONSOLE_WIDTH
  6608. #define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  6609. #undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  6610. #endif
  6611. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH-1
  6612. #ifdef __clang__
  6613. #pragma clang diagnostic push
  6614. #pragma clang diagnostic ignored "-Wweak-vtables"
  6615. #pragma clang diagnostic ignored "-Wexit-time-destructors"
  6616. #pragma clang diagnostic ignored "-Wshadow"
  6617. #endif
  6618. // start clara.hpp
  6619. // Copyright 2017 Two Blue Cubes Ltd. All rights reserved.
  6620. //
  6621. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  6622. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6623. //
  6624. // See https://github.com/philsquared/Clara for more details
  6625. // Clara v1.1.5
  6626. #ifndef CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  6627. #define CATCH_CLARA_CONFIG_CONSOLE_WIDTH 80
  6628. #endif
  6629. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  6630. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  6631. #endif
  6632. #ifndef CLARA_CONFIG_OPTIONAL_TYPE
  6633. #ifdef __has_include
  6634. #if __has_include(<optional>) && __cplusplus >= 201703L
  6635. #include <optional>
  6636. #define CLARA_CONFIG_OPTIONAL_TYPE std::optional
  6637. #endif
  6638. #endif
  6639. #endif
  6640. // ----------- #included from clara_textflow.hpp -----------
  6641. // TextFlowCpp
  6642. //
  6643. // A single-header library for wrapping and laying out basic text, by Phil Nash
  6644. //
  6645. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  6646. // file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6647. //
  6648. // This project is hosted at https://github.com/philsquared/textflowcpp
  6649. #include <cassert>
  6650. #include <ostream>
  6651. #include <sstream>
  6652. #include <vector>
  6653. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  6654. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80
  6655. #endif
  6656. namespace Catch {
  6657. namespace clara {
  6658. namespace TextFlow {
  6659. inline auto isWhitespace(char c) -> bool {
  6660. static std::string chars = " \t\n\r";
  6661. return chars.find(c) != std::string::npos;
  6662. }
  6663. inline auto isBreakableBefore(char c) -> bool {
  6664. static std::string chars = "[({<|";
  6665. return chars.find(c) != std::string::npos;
  6666. }
  6667. inline auto isBreakableAfter(char c) -> bool {
  6668. static std::string chars = "])}>.,:;*+-=&/\\";
  6669. return chars.find(c) != std::string::npos;
  6670. }
  6671. class Columns;
  6672. class Column {
  6673. std::vector<std::string> m_strings;
  6674. size_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH;
  6675. size_t m_indent = 0;
  6676. size_t m_initialIndent = std::string::npos;
  6677. public:
  6678. class iterator {
  6679. friend Column;
  6680. Column const& m_column;
  6681. size_t m_stringIndex = 0;
  6682. size_t m_pos = 0;
  6683. size_t m_len = 0;
  6684. size_t m_end = 0;
  6685. bool m_suffix = false;
  6686. iterator(Column const& column, size_t stringIndex)
  6687. : m_column(column),
  6688. m_stringIndex(stringIndex) {}
  6689. auto line() const -> std::string const& { return m_column.m_strings[m_stringIndex]; }
  6690. auto isBoundary(size_t at) const -> bool {
  6691. assert(at > 0);
  6692. assert(at <= line().size());
  6693. return at == line().size() ||
  6694. (isWhitespace(line()[at]) && !isWhitespace(line()[at - 1])) ||
  6695. isBreakableBefore(line()[at]) ||
  6696. isBreakableAfter(line()[at - 1]);
  6697. }
  6698. void calcLength() {
  6699. assert(m_stringIndex < m_column.m_strings.size());
  6700. m_suffix = false;
  6701. auto width = m_column.m_width - indent();
  6702. m_end = m_pos;
  6703. if (line()[m_pos] == '\n') {
  6704. ++m_end;
  6705. }
  6706. while (m_end < line().size() && line()[m_end] != '\n')
  6707. ++m_end;
  6708. if (m_end < m_pos + width) {
  6709. m_len = m_end - m_pos;
  6710. } else {
  6711. size_t len = width;
  6712. while (len > 0 && !isBoundary(m_pos + len))
  6713. --len;
  6714. while (len > 0 && isWhitespace(line()[m_pos + len - 1]))
  6715. --len;
  6716. if (len > 0) {
  6717. m_len = len;
  6718. } else {
  6719. m_suffix = true;
  6720. m_len = width - 1;
  6721. }
  6722. }
  6723. }
  6724. auto indent() const -> size_t {
  6725. auto initial = m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos;
  6726. return initial == std::string::npos ? m_column.m_indent : initial;
  6727. }
  6728. auto addIndentAndSuffix(std::string const &plain) const -> std::string {
  6729. return std::string(indent(), ' ') + (m_suffix ? plain + "-" : plain);
  6730. }
  6731. public:
  6732. using difference_type = std::ptrdiff_t;
  6733. using value_type = std::string;
  6734. using pointer = value_type * ;
  6735. using reference = value_type & ;
  6736. using iterator_category = std::forward_iterator_tag;
  6737. explicit iterator(Column const& column) : m_column(column) {
  6738. assert(m_column.m_width > m_column.m_indent);
  6739. assert(m_column.m_initialIndent == std::string::npos || m_column.m_width > m_column.m_initialIndent);
  6740. calcLength();
  6741. if (m_len == 0)
  6742. m_stringIndex++; // Empty string
  6743. }
  6744. auto operator *() const -> std::string {
  6745. assert(m_stringIndex < m_column.m_strings.size());
  6746. assert(m_pos <= m_end);
  6747. return addIndentAndSuffix(line().substr(m_pos, m_len));
  6748. }
  6749. auto operator ++() -> iterator& {
  6750. m_pos += m_len;
  6751. if (m_pos < line().size() && line()[m_pos] == '\n')
  6752. m_pos += 1;
  6753. else
  6754. while (m_pos < line().size() && isWhitespace(line()[m_pos]))
  6755. ++m_pos;
  6756. if (m_pos == line().size()) {
  6757. m_pos = 0;
  6758. ++m_stringIndex;
  6759. }
  6760. if (m_stringIndex < m_column.m_strings.size())
  6761. calcLength();
  6762. return *this;
  6763. }
  6764. auto operator ++(int) -> iterator {
  6765. iterator prev(*this);
  6766. operator++();
  6767. return prev;
  6768. }
  6769. auto operator ==(iterator const& other) const -> bool {
  6770. return
  6771. m_pos == other.m_pos &&
  6772. m_stringIndex == other.m_stringIndex &&
  6773. &m_column == &other.m_column;
  6774. }
  6775. auto operator !=(iterator const& other) const -> bool {
  6776. return !operator==(other);
  6777. }
  6778. };
  6779. using const_iterator = iterator;
  6780. explicit Column(std::string const& text) { m_strings.push_back(text); }
  6781. auto width(size_t newWidth) -> Column& {
  6782. assert(newWidth > 0);
  6783. m_width = newWidth;
  6784. return *this;
  6785. }
  6786. auto indent(size_t newIndent) -> Column& {
  6787. m_indent = newIndent;
  6788. return *this;
  6789. }
  6790. auto initialIndent(size_t newIndent) -> Column& {
  6791. m_initialIndent = newIndent;
  6792. return *this;
  6793. }
  6794. auto width() const -> size_t { return m_width; }
  6795. auto begin() const -> iterator { return iterator(*this); }
  6796. auto end() const -> iterator { return { *this, m_strings.size() }; }
  6797. inline friend std::ostream& operator << (std::ostream& os, Column const& col) {
  6798. bool first = true;
  6799. for (auto line : col) {
  6800. if (first)
  6801. first = false;
  6802. else
  6803. os << "\n";
  6804. os << line;
  6805. }
  6806. return os;
  6807. }
  6808. auto operator + (Column const& other)->Columns;
  6809. auto toString() const -> std::string {
  6810. std::ostringstream oss;
  6811. oss << *this;
  6812. return oss.str();
  6813. }
  6814. };
  6815. class Spacer : public Column {
  6816. public:
  6817. explicit Spacer(size_t spaceWidth) : Column("") {
  6818. width(spaceWidth);
  6819. }
  6820. };
  6821. class Columns {
  6822. std::vector<Column> m_columns;
  6823. public:
  6824. class iterator {
  6825. friend Columns;
  6826. struct EndTag {};
  6827. std::vector<Column> const& m_columns;
  6828. std::vector<Column::iterator> m_iterators;
  6829. size_t m_activeIterators;
  6830. iterator(Columns const& columns, EndTag)
  6831. : m_columns(columns.m_columns),
  6832. m_activeIterators(0) {
  6833. m_iterators.reserve(m_columns.size());
  6834. for (auto const& col : m_columns)
  6835. m_iterators.push_back(col.end());
  6836. }
  6837. public:
  6838. using difference_type = std::ptrdiff_t;
  6839. using value_type = std::string;
  6840. using pointer = value_type * ;
  6841. using reference = value_type & ;
  6842. using iterator_category = std::forward_iterator_tag;
  6843. explicit iterator(Columns const& columns)
  6844. : m_columns(columns.m_columns),
  6845. m_activeIterators(m_columns.size()) {
  6846. m_iterators.reserve(m_columns.size());
  6847. for (auto const& col : m_columns)
  6848. m_iterators.push_back(col.begin());
  6849. }
  6850. auto operator ==(iterator const& other) const -> bool {
  6851. return m_iterators == other.m_iterators;
  6852. }
  6853. auto operator !=(iterator const& other) const -> bool {
  6854. return m_iterators != other.m_iterators;
  6855. }
  6856. auto operator *() const -> std::string {
  6857. std::string row, padding;
  6858. for (size_t i = 0; i < m_columns.size(); ++i) {
  6859. auto width = m_columns[i].width();
  6860. if (m_iterators[i] != m_columns[i].end()) {
  6861. std::string col = *m_iterators[i];
  6862. row += padding + col;
  6863. if (col.size() < width)
  6864. padding = std::string(width - col.size(), ' ');
  6865. else
  6866. padding = "";
  6867. } else {
  6868. padding += std::string(width, ' ');
  6869. }
  6870. }
  6871. return row;
  6872. }
  6873. auto operator ++() -> iterator& {
  6874. for (size_t i = 0; i < m_columns.size(); ++i) {
  6875. if (m_iterators[i] != m_columns[i].end())
  6876. ++m_iterators[i];
  6877. }
  6878. return *this;
  6879. }
  6880. auto operator ++(int) -> iterator {
  6881. iterator prev(*this);
  6882. operator++();
  6883. return prev;
  6884. }
  6885. };
  6886. using const_iterator = iterator;
  6887. auto begin() const -> iterator { return iterator(*this); }
  6888. auto end() const -> iterator { return { *this, iterator::EndTag() }; }
  6889. auto operator += (Column const& col) -> Columns& {
  6890. m_columns.push_back(col);
  6891. return *this;
  6892. }
  6893. auto operator + (Column const& col) -> Columns {
  6894. Columns combined = *this;
  6895. combined += col;
  6896. return combined;
  6897. }
  6898. inline friend std::ostream& operator << (std::ostream& os, Columns const& cols) {
  6899. bool first = true;
  6900. for (auto line : cols) {
  6901. if (first)
  6902. first = false;
  6903. else
  6904. os << "\n";
  6905. os << line;
  6906. }
  6907. return os;
  6908. }
  6909. auto toString() const -> std::string {
  6910. std::ostringstream oss;
  6911. oss << *this;
  6912. return oss.str();
  6913. }
  6914. };
  6915. inline auto Column::operator + (Column const& other) -> Columns {
  6916. Columns cols;
  6917. cols += *this;
  6918. cols += other;
  6919. return cols;
  6920. }
  6921. }
  6922. }
  6923. }
  6924. // ----------- end of #include from clara_textflow.hpp -----------
  6925. // ........... back in clara.hpp
  6926. #include <cctype>
  6927. #include <string>
  6928. #include <memory>
  6929. #include <set>
  6930. #include <algorithm>
  6931. #if !defined(CATCH_PLATFORM_WINDOWS) && ( defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) )
  6932. #define CATCH_PLATFORM_WINDOWS
  6933. #endif
  6934. namespace Catch { namespace clara {
  6935. namespace detail {
  6936. // Traits for extracting arg and return type of lambdas (for single argument lambdas)
  6937. template<typename L>
  6938. struct UnaryLambdaTraits : UnaryLambdaTraits<decltype( &L::operator() )> {};
  6939. template<typename ClassT, typename ReturnT, typename... Args>
  6940. struct UnaryLambdaTraits<ReturnT( ClassT::* )( Args... ) const> {
  6941. static const bool isValid = false;
  6942. };
  6943. template<typename ClassT, typename ReturnT, typename ArgT>
  6944. struct UnaryLambdaTraits<ReturnT( ClassT::* )( ArgT ) const> {
  6945. static const bool isValid = true;
  6946. using ArgType = typename std::remove_const<typename std::remove_reference<ArgT>::type>::type;
  6947. using ReturnType = ReturnT;
  6948. };
  6949. class TokenStream;
  6950. // Transport for raw args (copied from main args, or supplied via init list for testing)
  6951. class Args {
  6952. friend TokenStream;
  6953. std::string m_exeName;
  6954. std::vector<std::string> m_args;
  6955. public:
  6956. Args( int argc, char const* const* argv )
  6957. : m_exeName(argv[0]),
  6958. m_args(argv + 1, argv + argc) {}
  6959. Args( std::initializer_list<std::string> args )
  6960. : m_exeName( *args.begin() ),
  6961. m_args( args.begin()+1, args.end() )
  6962. {}
  6963. auto exeName() const -> std::string {
  6964. return m_exeName;
  6965. }
  6966. };
  6967. // Wraps a token coming from a token stream. These may not directly correspond to strings as a single string
  6968. // may encode an option + its argument if the : or = form is used
  6969. enum class TokenType {
  6970. Option, Argument
  6971. };
  6972. struct Token {
  6973. TokenType type;
  6974. std::string token;
  6975. };
  6976. inline auto isOptPrefix( char c ) -> bool {
  6977. return c == '-'
  6978. #ifdef CATCH_PLATFORM_WINDOWS
  6979. || c == '/'
  6980. #endif
  6981. ;
  6982. }
  6983. // Abstracts iterators into args as a stream of tokens, with option arguments uniformly handled
  6984. class TokenStream {
  6985. using Iterator = std::vector<std::string>::const_iterator;
  6986. Iterator it;
  6987. Iterator itEnd;
  6988. std::vector<Token> m_tokenBuffer;
  6989. void loadBuffer() {
  6990. m_tokenBuffer.resize( 0 );
  6991. // Skip any empty strings
  6992. while( it != itEnd && it->empty() )
  6993. ++it;
  6994. if( it != itEnd ) {
  6995. auto const &next = *it;
  6996. if( isOptPrefix( next[0] ) ) {
  6997. auto delimiterPos = next.find_first_of( " :=" );
  6998. if( delimiterPos != std::string::npos ) {
  6999. m_tokenBuffer.push_back( { TokenType::Option, next.substr( 0, delimiterPos ) } );
  7000. m_tokenBuffer.push_back( { TokenType::Argument, next.substr( delimiterPos + 1 ) } );
  7001. } else {
  7002. if( next[1] != '-' && next.size() > 2 ) {
  7003. std::string opt = "- ";
  7004. for( size_t i = 1; i < next.size(); ++i ) {
  7005. opt[1] = next[i];
  7006. m_tokenBuffer.push_back( { TokenType::Option, opt } );
  7007. }
  7008. } else {
  7009. m_tokenBuffer.push_back( { TokenType::Option, next } );
  7010. }
  7011. }
  7012. } else {
  7013. m_tokenBuffer.push_back( { TokenType::Argument, next } );
  7014. }
  7015. }
  7016. }
  7017. public:
  7018. explicit TokenStream( Args const &args ) : TokenStream( args.m_args.begin(), args.m_args.end() ) {}
  7019. TokenStream( Iterator it, Iterator itEnd ) : it( it ), itEnd( itEnd ) {
  7020. loadBuffer();
  7021. }
  7022. explicit operator bool() const {
  7023. return !m_tokenBuffer.empty() || it != itEnd;
  7024. }
  7025. auto count() const -> size_t { return m_tokenBuffer.size() + (itEnd - it); }
  7026. auto operator*() const -> Token {
  7027. assert( !m_tokenBuffer.empty() );
  7028. return m_tokenBuffer.front();
  7029. }
  7030. auto operator->() const -> Token const * {
  7031. assert( !m_tokenBuffer.empty() );
  7032. return &m_tokenBuffer.front();
  7033. }
  7034. auto operator++() -> TokenStream & {
  7035. if( m_tokenBuffer.size() >= 2 ) {
  7036. m_tokenBuffer.erase( m_tokenBuffer.begin() );
  7037. } else {
  7038. if( it != itEnd )
  7039. ++it;
  7040. loadBuffer();
  7041. }
  7042. return *this;
  7043. }
  7044. };
  7045. class ResultBase {
  7046. public:
  7047. enum Type {
  7048. Ok, LogicError, RuntimeError
  7049. };
  7050. protected:
  7051. ResultBase( Type type ) : m_type( type ) {}
  7052. virtual ~ResultBase() = default;
  7053. virtual void enforceOk() const = 0;
  7054. Type m_type;
  7055. };
  7056. template<typename T>
  7057. class ResultValueBase : public ResultBase {
  7058. public:
  7059. auto value() const -> T const & {
  7060. enforceOk();
  7061. return m_value;
  7062. }
  7063. protected:
  7064. ResultValueBase( Type type ) : ResultBase( type ) {}
  7065. ResultValueBase( ResultValueBase const &other ) : ResultBase( other ) {
  7066. if( m_type == ResultBase::Ok )
  7067. new( &m_value ) T( other.m_value );
  7068. }
  7069. ResultValueBase( Type, T const &value ) : ResultBase( Ok ) {
  7070. new( &m_value ) T( value );
  7071. }
  7072. auto operator=( ResultValueBase const &other ) -> ResultValueBase & {
  7073. if( m_type == ResultBase::Ok )
  7074. m_value.~T();
  7075. ResultBase::operator=(other);
  7076. if( m_type == ResultBase::Ok )
  7077. new( &m_value ) T( other.m_value );
  7078. return *this;
  7079. }
  7080. ~ResultValueBase() override {
  7081. if( m_type == Ok )
  7082. m_value.~T();
  7083. }
  7084. union {
  7085. T m_value;
  7086. };
  7087. };
  7088. template<>
  7089. class ResultValueBase<void> : public ResultBase {
  7090. protected:
  7091. using ResultBase::ResultBase;
  7092. };
  7093. template<typename T = void>
  7094. class BasicResult : public ResultValueBase<T> {
  7095. public:
  7096. template<typename U>
  7097. explicit BasicResult( BasicResult<U> const &other )
  7098. : ResultValueBase<T>( other.type() ),
  7099. m_errorMessage( other.errorMessage() )
  7100. {
  7101. assert( type() != ResultBase::Ok );
  7102. }
  7103. template<typename U>
  7104. static auto ok( U const &value ) -> BasicResult { return { ResultBase::Ok, value }; }
  7105. static auto ok() -> BasicResult { return { ResultBase::Ok }; }
  7106. static auto logicError( std::string const &message ) -> BasicResult { return { ResultBase::LogicError, message }; }
  7107. static auto runtimeError( std::string const &message ) -> BasicResult { return { ResultBase::RuntimeError, message }; }
  7108. explicit operator bool() const { return m_type == ResultBase::Ok; }
  7109. auto type() const -> ResultBase::Type { return m_type; }
  7110. auto errorMessage() const -> std::string { return m_errorMessage; }
  7111. protected:
  7112. void enforceOk() const override {
  7113. // Errors shouldn't reach this point, but if they do
  7114. // the actual error message will be in m_errorMessage
  7115. assert( m_type != ResultBase::LogicError );
  7116. assert( m_type != ResultBase::RuntimeError );
  7117. if( m_type != ResultBase::Ok )
  7118. std::abort();
  7119. }
  7120. std::string m_errorMessage; // Only populated if resultType is an error
  7121. BasicResult( ResultBase::Type type, std::string const &message )
  7122. : ResultValueBase<T>(type),
  7123. m_errorMessage(message)
  7124. {
  7125. assert( m_type != ResultBase::Ok );
  7126. }
  7127. using ResultValueBase<T>::ResultValueBase;
  7128. using ResultBase::m_type;
  7129. };
  7130. enum class ParseResultType {
  7131. Matched, NoMatch, ShortCircuitAll, ShortCircuitSame
  7132. };
  7133. class ParseState {
  7134. public:
  7135. ParseState( ParseResultType type, TokenStream const &remainingTokens )
  7136. : m_type(type),
  7137. m_remainingTokens( remainingTokens )
  7138. {}
  7139. auto type() const -> ParseResultType { return m_type; }
  7140. auto remainingTokens() const -> TokenStream { return m_remainingTokens; }
  7141. private:
  7142. ParseResultType m_type;
  7143. TokenStream m_remainingTokens;
  7144. };
  7145. using Result = BasicResult<void>;
  7146. using ParserResult = BasicResult<ParseResultType>;
  7147. using InternalParseResult = BasicResult<ParseState>;
  7148. struct HelpColumns {
  7149. std::string left;
  7150. std::string right;
  7151. };
  7152. template<typename T>
  7153. inline auto convertInto( std::string const &source, T& target ) -> ParserResult {
  7154. std::stringstream ss;
  7155. ss << source;
  7156. ss >> target;
  7157. if( ss.fail() )
  7158. return ParserResult::runtimeError( "Unable to convert '" + source + "' to destination type" );
  7159. else
  7160. return ParserResult::ok( ParseResultType::Matched );
  7161. }
  7162. inline auto convertInto( std::string const &source, std::string& target ) -> ParserResult {
  7163. target = source;
  7164. return ParserResult::ok( ParseResultType::Matched );
  7165. }
  7166. inline auto convertInto( std::string const &source, bool &target ) -> ParserResult {
  7167. std::string srcLC = source;
  7168. std::transform( srcLC.begin(), srcLC.end(), srcLC.begin(), []( char c ) { return static_cast<char>( std::tolower(c) ); } );
  7169. if (srcLC == "y" || srcLC == "1" || srcLC == "true" || srcLC == "yes" || srcLC == "on")
  7170. target = true;
  7171. else if (srcLC == "n" || srcLC == "0" || srcLC == "false" || srcLC == "no" || srcLC == "off")
  7172. target = false;
  7173. else
  7174. return ParserResult::runtimeError( "Expected a boolean value but did not recognise: '" + source + "'" );
  7175. return ParserResult::ok( ParseResultType::Matched );
  7176. }
  7177. #ifdef CLARA_CONFIG_OPTIONAL_TYPE
  7178. template<typename T>
  7179. inline auto convertInto( std::string const &source, CLARA_CONFIG_OPTIONAL_TYPE<T>& target ) -> ParserResult {
  7180. T temp;
  7181. auto result = convertInto( source, temp );
  7182. if( result )
  7183. target = std::move(temp);
  7184. return result;
  7185. }
  7186. #endif // CLARA_CONFIG_OPTIONAL_TYPE
  7187. struct NonCopyable {
  7188. NonCopyable() = default;
  7189. NonCopyable( NonCopyable const & ) = delete;
  7190. NonCopyable( NonCopyable && ) = delete;
  7191. NonCopyable &operator=( NonCopyable const & ) = delete;
  7192. NonCopyable &operator=( NonCopyable && ) = delete;
  7193. };
  7194. struct BoundRef : NonCopyable {
  7195. virtual ~BoundRef() = default;
  7196. virtual auto isContainer() const -> bool { return false; }
  7197. virtual auto isFlag() const -> bool { return false; }
  7198. };
  7199. struct BoundValueRefBase : BoundRef {
  7200. virtual auto setValue( std::string const &arg ) -> ParserResult = 0;
  7201. };
  7202. struct BoundFlagRefBase : BoundRef {
  7203. virtual auto setFlag( bool flag ) -> ParserResult = 0;
  7204. virtual auto isFlag() const -> bool { return true; }
  7205. };
  7206. template<typename T>
  7207. struct BoundValueRef : BoundValueRefBase {
  7208. T &m_ref;
  7209. explicit BoundValueRef( T &ref ) : m_ref( ref ) {}
  7210. auto setValue( std::string const &arg ) -> ParserResult override {
  7211. return convertInto( arg, m_ref );
  7212. }
  7213. };
  7214. template<typename T>
  7215. struct BoundValueRef<std::vector<T>> : BoundValueRefBase {
  7216. std::vector<T> &m_ref;
  7217. explicit BoundValueRef( std::vector<T> &ref ) : m_ref( ref ) {}
  7218. auto isContainer() const -> bool override { return true; }
  7219. auto setValue( std::string const &arg ) -> ParserResult override {
  7220. T temp;
  7221. auto result = convertInto( arg, temp );
  7222. if( result )
  7223. m_ref.push_back( temp );
  7224. return result;
  7225. }
  7226. };
  7227. struct BoundFlagRef : BoundFlagRefBase {
  7228. bool &m_ref;
  7229. explicit BoundFlagRef( bool &ref ) : m_ref( ref ) {}
  7230. auto setFlag( bool flag ) -> ParserResult override {
  7231. m_ref = flag;
  7232. return ParserResult::ok( ParseResultType::Matched );
  7233. }
  7234. };
  7235. template<typename ReturnType>
  7236. struct LambdaInvoker {
  7237. static_assert( std::is_same<ReturnType, ParserResult>::value, "Lambda must return void or clara::ParserResult" );
  7238. template<typename L, typename ArgType>
  7239. static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
  7240. return lambda( arg );
  7241. }
  7242. };
  7243. template<>
  7244. struct LambdaInvoker<void> {
  7245. template<typename L, typename ArgType>
  7246. static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
  7247. lambda( arg );
  7248. return ParserResult::ok( ParseResultType::Matched );
  7249. }
  7250. };
  7251. template<typename ArgType, typename L>
  7252. inline auto invokeLambda( L const &lambda, std::string const &arg ) -> ParserResult {
  7253. ArgType temp{};
  7254. auto result = convertInto( arg, temp );
  7255. return !result
  7256. ? result
  7257. : LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( lambda, temp );
  7258. }
  7259. template<typename L>
  7260. struct BoundLambda : BoundValueRefBase {
  7261. L m_lambda;
  7262. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  7263. explicit BoundLambda( L const &lambda ) : m_lambda( lambda ) {}
  7264. auto setValue( std::string const &arg ) -> ParserResult override {
  7265. return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>( m_lambda, arg );
  7266. }
  7267. };
  7268. template<typename L>
  7269. struct BoundFlagLambda : BoundFlagRefBase {
  7270. L m_lambda;
  7271. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  7272. static_assert( std::is_same<typename UnaryLambdaTraits<L>::ArgType, bool>::value, "flags must be boolean" );
  7273. explicit BoundFlagLambda( L const &lambda ) : m_lambda( lambda ) {}
  7274. auto setFlag( bool flag ) -> ParserResult override {
  7275. return LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( m_lambda, flag );
  7276. }
  7277. };
  7278. enum class Optionality { Optional, Required };
  7279. struct Parser;
  7280. class ParserBase {
  7281. public:
  7282. virtual ~ParserBase() = default;
  7283. virtual auto validate() const -> Result { return Result::ok(); }
  7284. virtual auto parse( std::string const& exeName, TokenStream const &tokens) const -> InternalParseResult = 0;
  7285. virtual auto cardinality() const -> size_t { return 1; }
  7286. auto parse( Args const &args ) const -> InternalParseResult {
  7287. return parse( args.exeName(), TokenStream( args ) );
  7288. }
  7289. };
  7290. template<typename DerivedT>
  7291. class ComposableParserImpl : public ParserBase {
  7292. public:
  7293. template<typename T>
  7294. auto operator|( T const &other ) const -> Parser;
  7295. template<typename T>
  7296. auto operator+( T const &other ) const -> Parser;
  7297. };
  7298. // Common code and state for Args and Opts
  7299. template<typename DerivedT>
  7300. class ParserRefImpl : public ComposableParserImpl<DerivedT> {
  7301. protected:
  7302. Optionality m_optionality = Optionality::Optional;
  7303. std::shared_ptr<BoundRef> m_ref;
  7304. std::string m_hint;
  7305. std::string m_description;
  7306. explicit ParserRefImpl( std::shared_ptr<BoundRef> const &ref ) : m_ref( ref ) {}
  7307. public:
  7308. template<typename T>
  7309. ParserRefImpl( T &ref, std::string const &hint )
  7310. : m_ref( std::make_shared<BoundValueRef<T>>( ref ) ),
  7311. m_hint( hint )
  7312. {}
  7313. template<typename LambdaT>
  7314. ParserRefImpl( LambdaT const &ref, std::string const &hint )
  7315. : m_ref( std::make_shared<BoundLambda<LambdaT>>( ref ) ),
  7316. m_hint(hint)
  7317. {}
  7318. auto operator()( std::string const &description ) -> DerivedT & {
  7319. m_description = description;
  7320. return static_cast<DerivedT &>( *this );
  7321. }
  7322. auto optional() -> DerivedT & {
  7323. m_optionality = Optionality::Optional;
  7324. return static_cast<DerivedT &>( *this );
  7325. };
  7326. auto required() -> DerivedT & {
  7327. m_optionality = Optionality::Required;
  7328. return static_cast<DerivedT &>( *this );
  7329. };
  7330. auto isOptional() const -> bool {
  7331. return m_optionality == Optionality::Optional;
  7332. }
  7333. auto cardinality() const -> size_t override {
  7334. if( m_ref->isContainer() )
  7335. return 0;
  7336. else
  7337. return 1;
  7338. }
  7339. auto hint() const -> std::string { return m_hint; }
  7340. };
  7341. class ExeName : public ComposableParserImpl<ExeName> {
  7342. std::shared_ptr<std::string> m_name;
  7343. std::shared_ptr<BoundValueRefBase> m_ref;
  7344. template<typename LambdaT>
  7345. static auto makeRef(LambdaT const &lambda) -> std::shared_ptr<BoundValueRefBase> {
  7346. return std::make_shared<BoundLambda<LambdaT>>( lambda) ;
  7347. }
  7348. public:
  7349. ExeName() : m_name( std::make_shared<std::string>( "<executable>" ) ) {}
  7350. explicit ExeName( std::string &ref ) : ExeName() {
  7351. m_ref = std::make_shared<BoundValueRef<std::string>>( ref );
  7352. }
  7353. template<typename LambdaT>
  7354. explicit ExeName( LambdaT const& lambda ) : ExeName() {
  7355. m_ref = std::make_shared<BoundLambda<LambdaT>>( lambda );
  7356. }
  7357. // The exe name is not parsed out of the normal tokens, but is handled specially
  7358. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  7359. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
  7360. }
  7361. auto name() const -> std::string { return *m_name; }
  7362. auto set( std::string const& newName ) -> ParserResult {
  7363. auto lastSlash = newName.find_last_of( "\\/" );
  7364. auto filename = ( lastSlash == std::string::npos )
  7365. ? newName
  7366. : newName.substr( lastSlash+1 );
  7367. *m_name = filename;
  7368. if( m_ref )
  7369. return m_ref->setValue( filename );
  7370. else
  7371. return ParserResult::ok( ParseResultType::Matched );
  7372. }
  7373. };
  7374. class Arg : public ParserRefImpl<Arg> {
  7375. public:
  7376. using ParserRefImpl::ParserRefImpl;
  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. auto const &token = *remainingTokens;
  7383. if( token.type != TokenType::Argument )
  7384. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
  7385. assert( !m_ref->isFlag() );
  7386. auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
  7387. auto result = valueRef->setValue( remainingTokens->token );
  7388. if( !result )
  7389. return InternalParseResult( result );
  7390. else
  7391. return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
  7392. }
  7393. };
  7394. inline auto normaliseOpt( std::string const &optName ) -> std::string {
  7395. #ifdef CATCH_PLATFORM_WINDOWS
  7396. if( optName[0] == '/' )
  7397. return "-" + optName.substr( 1 );
  7398. else
  7399. #endif
  7400. return optName;
  7401. }
  7402. class Opt : public ParserRefImpl<Opt> {
  7403. protected:
  7404. std::vector<std::string> m_optNames;
  7405. public:
  7406. template<typename LambdaT>
  7407. explicit Opt( LambdaT const &ref ) : ParserRefImpl( std::make_shared<BoundFlagLambda<LambdaT>>( ref ) ) {}
  7408. explicit Opt( bool &ref ) : ParserRefImpl( std::make_shared<BoundFlagRef>( ref ) ) {}
  7409. template<typename LambdaT>
  7410. Opt( LambdaT const &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  7411. template<typename T>
  7412. Opt( T &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  7413. auto operator[]( std::string const &optName ) -> Opt & {
  7414. m_optNames.push_back( optName );
  7415. return *this;
  7416. }
  7417. auto getHelpColumns() const -> std::vector<HelpColumns> {
  7418. std::ostringstream oss;
  7419. bool first = true;
  7420. for( auto const &opt : m_optNames ) {
  7421. if (first)
  7422. first = false;
  7423. else
  7424. oss << ", ";
  7425. oss << opt;
  7426. }
  7427. if( !m_hint.empty() )
  7428. oss << " <" << m_hint << ">";
  7429. return { { oss.str(), m_description } };
  7430. }
  7431. auto isMatch( std::string const &optToken ) const -> bool {
  7432. auto normalisedToken = normaliseOpt( optToken );
  7433. for( auto const &name : m_optNames ) {
  7434. if( normaliseOpt( name ) == normalisedToken )
  7435. return true;
  7436. }
  7437. return false;
  7438. }
  7439. using ParserBase::parse;
  7440. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  7441. auto validationResult = validate();
  7442. if( !validationResult )
  7443. return InternalParseResult( validationResult );
  7444. auto remainingTokens = tokens;
  7445. if( remainingTokens && remainingTokens->type == TokenType::Option ) {
  7446. auto const &token = *remainingTokens;
  7447. if( isMatch(token.token ) ) {
  7448. if( m_ref->isFlag() ) {
  7449. auto flagRef = static_cast<detail::BoundFlagRefBase*>( m_ref.get() );
  7450. auto result = flagRef->setFlag( true );
  7451. if( !result )
  7452. return InternalParseResult( result );
  7453. if( result.value() == ParseResultType::ShortCircuitAll )
  7454. return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
  7455. } else {
  7456. auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
  7457. ++remainingTokens;
  7458. if( !remainingTokens )
  7459. return InternalParseResult::runtimeError( "Expected argument following " + token.token );
  7460. auto const &argToken = *remainingTokens;
  7461. if( argToken.type != TokenType::Argument )
  7462. return InternalParseResult::runtimeError( "Expected argument following " + token.token );
  7463. auto result = valueRef->setValue( argToken.token );
  7464. if( !result )
  7465. return InternalParseResult( result );
  7466. if( result.value() == ParseResultType::ShortCircuitAll )
  7467. return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
  7468. }
  7469. return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
  7470. }
  7471. }
  7472. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
  7473. }
  7474. auto validate() const -> Result override {
  7475. if( m_optNames.empty() )
  7476. return Result::logicError( "No options supplied to Opt" );
  7477. for( auto const &name : m_optNames ) {
  7478. if( name.empty() )
  7479. return Result::logicError( "Option name cannot be empty" );
  7480. #ifdef CATCH_PLATFORM_WINDOWS
  7481. if( name[0] != '-' && name[0] != '/' )
  7482. return Result::logicError( "Option name must begin with '-' or '/'" );
  7483. #else
  7484. if( name[0] != '-' )
  7485. return Result::logicError( "Option name must begin with '-'" );
  7486. #endif
  7487. }
  7488. return ParserRefImpl::validate();
  7489. }
  7490. };
  7491. struct Help : Opt {
  7492. Help( bool &showHelpFlag )
  7493. : Opt([&]( bool flag ) {
  7494. showHelpFlag = flag;
  7495. return ParserResult::ok( ParseResultType::ShortCircuitAll );
  7496. })
  7497. {
  7498. static_cast<Opt &>( *this )
  7499. ("display usage information")
  7500. ["-?"]["-h"]["--help"]
  7501. .optional();
  7502. }
  7503. };
  7504. struct Parser : ParserBase {
  7505. mutable ExeName m_exeName;
  7506. std::vector<Opt> m_options;
  7507. std::vector<Arg> m_args;
  7508. auto operator|=( ExeName const &exeName ) -> Parser & {
  7509. m_exeName = exeName;
  7510. return *this;
  7511. }
  7512. auto operator|=( Arg const &arg ) -> Parser & {
  7513. m_args.push_back(arg);
  7514. return *this;
  7515. }
  7516. auto operator|=( Opt const &opt ) -> Parser & {
  7517. m_options.push_back(opt);
  7518. return *this;
  7519. }
  7520. auto operator|=( Parser const &other ) -> Parser & {
  7521. m_options.insert(m_options.end(), other.m_options.begin(), other.m_options.end());
  7522. m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end());
  7523. return *this;
  7524. }
  7525. template<typename T>
  7526. auto operator|( T const &other ) const -> Parser {
  7527. return Parser( *this ) |= other;
  7528. }
  7529. // Forward deprecated interface with '+' instead of '|'
  7530. template<typename T>
  7531. auto operator+=( T const &other ) -> Parser & { return operator|=( other ); }
  7532. template<typename T>
  7533. auto operator+( T const &other ) const -> Parser { return operator|( other ); }
  7534. auto getHelpColumns() const -> std::vector<HelpColumns> {
  7535. std::vector<HelpColumns> cols;
  7536. for (auto const &o : m_options) {
  7537. auto childCols = o.getHelpColumns();
  7538. cols.insert( cols.end(), childCols.begin(), childCols.end() );
  7539. }
  7540. return cols;
  7541. }
  7542. void writeToStream( std::ostream &os ) const {
  7543. if (!m_exeName.name().empty()) {
  7544. os << "usage:\n" << " " << m_exeName.name() << " ";
  7545. bool required = true, first = true;
  7546. for( auto const &arg : m_args ) {
  7547. if (first)
  7548. first = false;
  7549. else
  7550. os << " ";
  7551. if( arg.isOptional() && required ) {
  7552. os << "[";
  7553. required = false;
  7554. }
  7555. os << "<" << arg.hint() << ">";
  7556. if( arg.cardinality() == 0 )
  7557. os << " ... ";
  7558. }
  7559. if( !required )
  7560. os << "]";
  7561. if( !m_options.empty() )
  7562. os << " options";
  7563. os << "\n\nwhere options are:" << std::endl;
  7564. }
  7565. auto rows = getHelpColumns();
  7566. size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH;
  7567. size_t optWidth = 0;
  7568. for( auto const &cols : rows )
  7569. optWidth = (std::max)(optWidth, cols.left.size() + 2);
  7570. optWidth = (std::min)(optWidth, consoleWidth/2);
  7571. for( auto const &cols : rows ) {
  7572. auto row =
  7573. TextFlow::Column( cols.left ).width( optWidth ).indent( 2 ) +
  7574. TextFlow::Spacer(4) +
  7575. TextFlow::Column( cols.right ).width( consoleWidth - 7 - optWidth );
  7576. os << row << std::endl;
  7577. }
  7578. }
  7579. friend auto operator<<( std::ostream &os, Parser const &parser ) -> std::ostream& {
  7580. parser.writeToStream( os );
  7581. return os;
  7582. }
  7583. auto validate() const -> Result override {
  7584. for( auto const &opt : m_options ) {
  7585. auto result = opt.validate();
  7586. if( !result )
  7587. return result;
  7588. }
  7589. for( auto const &arg : m_args ) {
  7590. auto result = arg.validate();
  7591. if( !result )
  7592. return result;
  7593. }
  7594. return Result::ok();
  7595. }
  7596. using ParserBase::parse;
  7597. auto parse( std::string const& exeName, TokenStream const &tokens ) const -> InternalParseResult override {
  7598. struct ParserInfo {
  7599. ParserBase const* parser = nullptr;
  7600. size_t count = 0;
  7601. };
  7602. const size_t totalParsers = m_options.size() + m_args.size();
  7603. assert( totalParsers < 512 );
  7604. // ParserInfo parseInfos[totalParsers]; // <-- this is what we really want to do
  7605. ParserInfo parseInfos[512];
  7606. {
  7607. size_t i = 0;
  7608. for (auto const &opt : m_options) parseInfos[i++].parser = &opt;
  7609. for (auto const &arg : m_args) parseInfos[i++].parser = &arg;
  7610. }
  7611. m_exeName.set( exeName );
  7612. auto result = InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
  7613. while( result.value().remainingTokens() ) {
  7614. bool tokenParsed = false;
  7615. for( size_t i = 0; i < totalParsers; ++i ) {
  7616. auto& parseInfo = parseInfos[i];
  7617. if( parseInfo.parser->cardinality() == 0 || parseInfo.count < parseInfo.parser->cardinality() ) {
  7618. result = parseInfo.parser->parse(exeName, result.value().remainingTokens());
  7619. if (!result)
  7620. return result;
  7621. if (result.value().type() != ParseResultType::NoMatch) {
  7622. tokenParsed = true;
  7623. ++parseInfo.count;
  7624. break;
  7625. }
  7626. }
  7627. }
  7628. if( result.value().type() == ParseResultType::ShortCircuitAll )
  7629. return result;
  7630. if( !tokenParsed )
  7631. return InternalParseResult::runtimeError( "Unrecognised token: " + result.value().remainingTokens()->token );
  7632. }
  7633. // !TBD Check missing required options
  7634. return result;
  7635. }
  7636. };
  7637. template<typename DerivedT>
  7638. template<typename T>
  7639. auto ComposableParserImpl<DerivedT>::operator|( T const &other ) const -> Parser {
  7640. return Parser() | static_cast<DerivedT const &>( *this ) | other;
  7641. }
  7642. } // namespace detail
  7643. // A Combined parser
  7644. using detail::Parser;
  7645. // A parser for options
  7646. using detail::Opt;
  7647. // A parser for arguments
  7648. using detail::Arg;
  7649. // Wrapper for argc, argv from main()
  7650. using detail::Args;
  7651. // Specifies the name of the executable
  7652. using detail::ExeName;
  7653. // Convenience wrapper for option parser that specifies the help option
  7654. using detail::Help;
  7655. // enum of result types from a parse
  7656. using detail::ParseResultType;
  7657. // Result type for parser operation
  7658. using detail::ParserResult;
  7659. }} // namespace Catch::clara
  7660. // end clara.hpp
  7661. #ifdef __clang__
  7662. #pragma clang diagnostic pop
  7663. #endif
  7664. // Restore Clara's value for console width, if present
  7665. #ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  7666. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  7667. #undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  7668. #endif
  7669. // end catch_clara.h
  7670. namespace Catch {
  7671. clara::Parser makeCommandLineParser( ConfigData& config );
  7672. } // end namespace Catch
  7673. // end catch_commandline.h
  7674. #include <fstream>
  7675. #include <ctime>
  7676. namespace Catch {
  7677. clara::Parser makeCommandLineParser( ConfigData& config ) {
  7678. using namespace clara;
  7679. auto const setWarning = [&]( std::string const& warning ) {
  7680. auto warningSet = [&]() {
  7681. if( warning == "NoAssertions" )
  7682. return WarnAbout::NoAssertions;
  7683. if ( warning == "NoTests" )
  7684. return WarnAbout::NoTests;
  7685. return WarnAbout::Nothing;
  7686. }();
  7687. if (warningSet == WarnAbout::Nothing)
  7688. return ParserResult::runtimeError( "Unrecognised warning: '" + warning + "'" );
  7689. config.warnings = static_cast<WarnAbout::What>( config.warnings | warningSet );
  7690. return ParserResult::ok( ParseResultType::Matched );
  7691. };
  7692. auto const loadTestNamesFromFile = [&]( std::string const& filename ) {
  7693. std::ifstream f( filename.c_str() );
  7694. if( !f.is_open() )
  7695. return ParserResult::runtimeError( "Unable to load input file: '" + filename + "'" );
  7696. std::string line;
  7697. while( std::getline( f, line ) ) {
  7698. line = trim(line);
  7699. if( !line.empty() && !startsWith( line, '#' ) ) {
  7700. if( !startsWith( line, '"' ) )
  7701. line = '"' + line + '"';
  7702. config.testsOrTags.push_back( line + ',' );
  7703. }
  7704. }
  7705. return ParserResult::ok( ParseResultType::Matched );
  7706. };
  7707. auto const setTestOrder = [&]( std::string const& order ) {
  7708. if( startsWith( "declared", order ) )
  7709. config.runOrder = RunTests::InDeclarationOrder;
  7710. else if( startsWith( "lexical", order ) )
  7711. config.runOrder = RunTests::InLexicographicalOrder;
  7712. else if( startsWith( "random", order ) )
  7713. config.runOrder = RunTests::InRandomOrder;
  7714. else
  7715. return clara::ParserResult::runtimeError( "Unrecognised ordering: '" + order + "'" );
  7716. return ParserResult::ok( ParseResultType::Matched );
  7717. };
  7718. auto const setRngSeed = [&]( std::string const& seed ) {
  7719. if( seed != "time" )
  7720. return clara::detail::convertInto( seed, config.rngSeed );
  7721. config.rngSeed = static_cast<unsigned int>( std::time(nullptr) );
  7722. return ParserResult::ok( ParseResultType::Matched );
  7723. };
  7724. auto const setColourUsage = [&]( std::string const& useColour ) {
  7725. auto mode = toLower( useColour );
  7726. if( mode == "yes" )
  7727. config.useColour = UseColour::Yes;
  7728. else if( mode == "no" )
  7729. config.useColour = UseColour::No;
  7730. else if( mode == "auto" )
  7731. config.useColour = UseColour::Auto;
  7732. else
  7733. return ParserResult::runtimeError( "colour mode must be one of: auto, yes or no. '" + useColour + "' not recognised" );
  7734. return ParserResult::ok( ParseResultType::Matched );
  7735. };
  7736. auto const setWaitForKeypress = [&]( std::string const& keypress ) {
  7737. auto keypressLc = toLower( keypress );
  7738. if( keypressLc == "start" )
  7739. config.waitForKeypress = WaitForKeypress::BeforeStart;
  7740. else if( keypressLc == "exit" )
  7741. config.waitForKeypress = WaitForKeypress::BeforeExit;
  7742. else if( keypressLc == "both" )
  7743. config.waitForKeypress = WaitForKeypress::BeforeStartAndExit;
  7744. else
  7745. return ParserResult::runtimeError( "keypress argument must be one of: start, exit or both. '" + keypress + "' not recognised" );
  7746. return ParserResult::ok( ParseResultType::Matched );
  7747. };
  7748. auto const setVerbosity = [&]( std::string const& verbosity ) {
  7749. auto lcVerbosity = toLower( verbosity );
  7750. if( lcVerbosity == "quiet" )
  7751. config.verbosity = Verbosity::Quiet;
  7752. else if( lcVerbosity == "normal" )
  7753. config.verbosity = Verbosity::Normal;
  7754. else if( lcVerbosity == "high" )
  7755. config.verbosity = Verbosity::High;
  7756. else
  7757. return ParserResult::runtimeError( "Unrecognised verbosity, '" + verbosity + "'" );
  7758. return ParserResult::ok( ParseResultType::Matched );
  7759. };
  7760. auto const setReporter = [&]( std::string const& reporter ) {
  7761. IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
  7762. auto lcReporter = toLower( reporter );
  7763. auto result = factories.find( lcReporter );
  7764. if( factories.end() != result )
  7765. config.reporterName = lcReporter;
  7766. else
  7767. return ParserResult::runtimeError( "Unrecognized reporter, '" + reporter + "'. Check available with --list-reporters" );
  7768. return ParserResult::ok( ParseResultType::Matched );
  7769. };
  7770. auto cli
  7771. = ExeName( config.processName )
  7772. | Help( config.showHelp )
  7773. | Opt( config.listTests )
  7774. ["-l"]["--list-tests"]
  7775. ( "list all/matching test cases" )
  7776. | Opt( config.listTags )
  7777. ["-t"]["--list-tags"]
  7778. ( "list all/matching tags" )
  7779. | Opt( config.showSuccessfulTests )
  7780. ["-s"]["--success"]
  7781. ( "include successful tests in output" )
  7782. | Opt( config.shouldDebugBreak )
  7783. ["-b"]["--break"]
  7784. ( "break into debugger on failure" )
  7785. | Opt( config.noThrow )
  7786. ["-e"]["--nothrow"]
  7787. ( "skip exception tests" )
  7788. | Opt( config.showInvisibles )
  7789. ["-i"]["--invisibles"]
  7790. ( "show invisibles (tabs, newlines)" )
  7791. | Opt( config.outputFilename, "filename" )
  7792. ["-o"]["--out"]
  7793. ( "output filename" )
  7794. | Opt( setReporter, "name" )
  7795. ["-r"]["--reporter"]
  7796. ( "reporter to use (defaults to console)" )
  7797. | Opt( config.name, "name" )
  7798. ["-n"]["--name"]
  7799. ( "suite name" )
  7800. | Opt( [&]( bool ){ config.abortAfter = 1; } )
  7801. ["-a"]["--abort"]
  7802. ( "abort at first failure" )
  7803. | Opt( [&]( int x ){ config.abortAfter = x; }, "no. failures" )
  7804. ["-x"]["--abortx"]
  7805. ( "abort after x failures" )
  7806. | Opt( setWarning, "warning name" )
  7807. ["-w"]["--warn"]
  7808. ( "enable warnings" )
  7809. | Opt( [&]( bool flag ) { config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never; }, "yes|no" )
  7810. ["-d"]["--durations"]
  7811. ( "show test durations" )
  7812. | Opt( loadTestNamesFromFile, "filename" )
  7813. ["-f"]["--input-file"]
  7814. ( "load test names to run from a file" )
  7815. | Opt( config.filenamesAsTags )
  7816. ["-#"]["--filenames-as-tags"]
  7817. ( "adds a tag for the filename" )
  7818. | Opt( config.sectionsToRun, "section name" )
  7819. ["-c"]["--section"]
  7820. ( "specify section to run" )
  7821. | Opt( setVerbosity, "quiet|normal|high" )
  7822. ["-v"]["--verbosity"]
  7823. ( "set output verbosity" )
  7824. | Opt( config.listTestNamesOnly )
  7825. ["--list-test-names-only"]
  7826. ( "list all/matching test cases names only" )
  7827. | Opt( config.listReporters )
  7828. ["--list-reporters"]
  7829. ( "list all reporters" )
  7830. | Opt( setTestOrder, "decl|lex|rand" )
  7831. ["--order"]
  7832. ( "test case order (defaults to decl)" )
  7833. | Opt( setRngSeed, "'time'|number" )
  7834. ["--rng-seed"]
  7835. ( "set a specific seed for random numbers" )
  7836. | Opt( setColourUsage, "yes|no" )
  7837. ["--use-colour"]
  7838. ( "should output be colourised" )
  7839. | Opt( config.libIdentify )
  7840. ["--libidentify"]
  7841. ( "report name and version according to libidentify standard" )
  7842. | Opt( setWaitForKeypress, "start|exit|both" )
  7843. ["--wait-for-keypress"]
  7844. ( "waits for a keypress before exiting" )
  7845. | Opt( config.benchmarkSamples, "samples" )
  7846. ["--benchmark-samples"]
  7847. ( "number of samples to collect (default: 100)" )
  7848. | Opt( config.benchmarkResamples, "resamples" )
  7849. ["--benchmark-resamples"]
  7850. ( "number of resamples for the bootstrap (default: 100000)" )
  7851. | Opt( config.benchmarkConfidenceInterval, "confidence interval" )
  7852. ["--benchmark-confidence-interval"]
  7853. ( "confidence interval for the bootstrap (between 0 and 1, default: 0.95)" )
  7854. | Opt( config.benchmarkNoAnalysis )
  7855. ["--benchmark-no-analysis"]
  7856. ( "perform only measurements; do not perform any analysis" )
  7857. | Arg( config.testsOrTags, "test name|pattern|tags" )
  7858. ( "which test or tests to use" );
  7859. return cli;
  7860. }
  7861. } // end namespace Catch
  7862. // end catch_commandline.cpp
  7863. // start catch_common.cpp
  7864. #include <cstring>
  7865. #include <ostream>
  7866. namespace Catch {
  7867. bool SourceLineInfo::empty() const noexcept {
  7868. return file[0] == '\0';
  7869. }
  7870. bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const noexcept {
  7871. return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0);
  7872. }
  7873. bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const noexcept {
  7874. // We can assume that the same file will usually have the same pointer.
  7875. // Thus, if the pointers are the same, there is no point in calling the strcmp
  7876. return line < other.line || ( line == other.line && file != other.file && (std::strcmp(file, other.file) < 0));
  7877. }
  7878. std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) {
  7879. #ifndef __GNUG__
  7880. os << info.file << '(' << info.line << ')';
  7881. #else
  7882. os << info.file << ':' << info.line;
  7883. #endif
  7884. return os;
  7885. }
  7886. std::string StreamEndStop::operator+() const {
  7887. return std::string();
  7888. }
  7889. NonCopyable::NonCopyable() = default;
  7890. NonCopyable::~NonCopyable() = default;
  7891. }
  7892. // end catch_common.cpp
  7893. // start catch_config.cpp
  7894. namespace Catch {
  7895. Config::Config( ConfigData const& data )
  7896. : m_data( data ),
  7897. m_stream( openStream() )
  7898. {
  7899. TestSpecParser parser(ITagAliasRegistry::get());
  7900. if (!data.testsOrTags.empty()) {
  7901. m_hasTestFilters = true;
  7902. for( auto const& testOrTags : data.testsOrTags )
  7903. parser.parse( testOrTags );
  7904. }
  7905. m_testSpec = parser.testSpec();
  7906. }
  7907. std::string const& Config::getFilename() const {
  7908. return m_data.outputFilename ;
  7909. }
  7910. bool Config::listTests() const { return m_data.listTests; }
  7911. bool Config::listTestNamesOnly() const { return m_data.listTestNamesOnly; }
  7912. bool Config::listTags() const { return m_data.listTags; }
  7913. bool Config::listReporters() const { return m_data.listReporters; }
  7914. std::string Config::getProcessName() const { return m_data.processName; }
  7915. std::string const& Config::getReporterName() const { return m_data.reporterName; }
  7916. std::vector<std::string> const& Config::getTestsOrTags() const { return m_data.testsOrTags; }
  7917. std::vector<std::string> const& Config::getSectionsToRun() const { return m_data.sectionsToRun; }
  7918. TestSpec const& Config::testSpec() const { return m_testSpec; }
  7919. bool Config::hasTestFilters() const { return m_hasTestFilters; }
  7920. bool Config::showHelp() const { return m_data.showHelp; }
  7921. // IConfig interface
  7922. bool Config::allowThrows() const { return !m_data.noThrow; }
  7923. std::ostream& Config::stream() const { return m_stream->stream(); }
  7924. std::string Config::name() const { return m_data.name.empty() ? m_data.processName : m_data.name; }
  7925. bool Config::includeSuccessfulResults() const { return m_data.showSuccessfulTests; }
  7926. bool Config::warnAboutMissingAssertions() const { return !!(m_data.warnings & WarnAbout::NoAssertions); }
  7927. bool Config::warnAboutNoTests() const { return !!(m_data.warnings & WarnAbout::NoTests); }
  7928. ShowDurations::OrNot Config::showDurations() const { return m_data.showDurations; }
  7929. RunTests::InWhatOrder Config::runOrder() const { return m_data.runOrder; }
  7930. unsigned int Config::rngSeed() const { return m_data.rngSeed; }
  7931. UseColour::YesOrNo Config::useColour() const { return m_data.useColour; }
  7932. bool Config::shouldDebugBreak() const { return m_data.shouldDebugBreak; }
  7933. int Config::abortAfter() const { return m_data.abortAfter; }
  7934. bool Config::showInvisibles() const { return m_data.showInvisibles; }
  7935. Verbosity Config::verbosity() const { return m_data.verbosity; }
  7936. bool Config::benchmarkNoAnalysis() const { return m_data.benchmarkNoAnalysis; }
  7937. int Config::benchmarkSamples() const { return m_data.benchmarkSamples; }
  7938. double Config::benchmarkConfidenceInterval() const { return m_data.benchmarkConfidenceInterval; }
  7939. unsigned int Config::benchmarkResamples() const { return m_data.benchmarkResamples; }
  7940. IStream const* Config::openStream() {
  7941. return Catch::makeStream(m_data.outputFilename);
  7942. }
  7943. } // end namespace Catch
  7944. // end catch_config.cpp
  7945. // start catch_console_colour.cpp
  7946. #if defined(__clang__)
  7947. # pragma clang diagnostic push
  7948. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  7949. #endif
  7950. // start catch_errno_guard.h
  7951. namespace Catch {
  7952. class ErrnoGuard {
  7953. public:
  7954. ErrnoGuard();
  7955. ~ErrnoGuard();
  7956. private:
  7957. int m_oldErrno;
  7958. };
  7959. }
  7960. // end catch_errno_guard.h
  7961. #include <sstream>
  7962. namespace Catch {
  7963. namespace {
  7964. struct IColourImpl {
  7965. virtual ~IColourImpl() = default;
  7966. virtual void use( Colour::Code _colourCode ) = 0;
  7967. };
  7968. struct NoColourImpl : IColourImpl {
  7969. void use( Colour::Code ) {}
  7970. static IColourImpl* instance() {
  7971. static NoColourImpl s_instance;
  7972. return &s_instance;
  7973. }
  7974. };
  7975. } // anon namespace
  7976. } // namespace Catch
  7977. #if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI )
  7978. # ifdef CATCH_PLATFORM_WINDOWS
  7979. # define CATCH_CONFIG_COLOUR_WINDOWS
  7980. # else
  7981. # define CATCH_CONFIG_COLOUR_ANSI
  7982. # endif
  7983. #endif
  7984. #if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) /////////////////////////////////////////
  7985. namespace Catch {
  7986. namespace {
  7987. class Win32ColourImpl : public IColourImpl {
  7988. public:
  7989. Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) )
  7990. {
  7991. CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
  7992. GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo );
  7993. originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY );
  7994. originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY );
  7995. }
  7996. void use( Colour::Code _colourCode ) override {
  7997. switch( _colourCode ) {
  7998. case Colour::None: return setTextAttribute( originalForegroundAttributes );
  7999. case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  8000. case Colour::Red: return setTextAttribute( FOREGROUND_RED );
  8001. case Colour::Green: return setTextAttribute( FOREGROUND_GREEN );
  8002. case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE );
  8003. case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN );
  8004. case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN );
  8005. case Colour::Grey: return setTextAttribute( 0 );
  8006. case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY );
  8007. case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED );
  8008. case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN );
  8009. case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  8010. case Colour::BrightYellow: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN );
  8011. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  8012. default:
  8013. CATCH_ERROR( "Unknown colour requested" );
  8014. }
  8015. }
  8016. private:
  8017. void setTextAttribute( WORD _textAttribute ) {
  8018. SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes );
  8019. }
  8020. HANDLE stdoutHandle;
  8021. WORD originalForegroundAttributes;
  8022. WORD originalBackgroundAttributes;
  8023. };
  8024. IColourImpl* platformColourInstance() {
  8025. static Win32ColourImpl s_instance;
  8026. IConfigPtr config = getCurrentContext().getConfig();
  8027. UseColour::YesOrNo colourMode = config
  8028. ? config->useColour()
  8029. : UseColour::Auto;
  8030. if( colourMode == UseColour::Auto )
  8031. colourMode = UseColour::Yes;
  8032. return colourMode == UseColour::Yes
  8033. ? &s_instance
  8034. : NoColourImpl::instance();
  8035. }
  8036. } // end anon namespace
  8037. } // end namespace Catch
  8038. #elif defined( CATCH_CONFIG_COLOUR_ANSI ) //////////////////////////////////////
  8039. #include <unistd.h>
  8040. namespace Catch {
  8041. namespace {
  8042. // use POSIX/ ANSI console terminal codes
  8043. // Thanks to Adam Strzelecki for original contribution
  8044. // (http://github.com/nanoant)
  8045. // https://github.com/philsquared/Catch/pull/131
  8046. class PosixColourImpl : public IColourImpl {
  8047. public:
  8048. void use( Colour::Code _colourCode ) override {
  8049. switch( _colourCode ) {
  8050. case Colour::None:
  8051. case Colour::White: return setColour( "[0m" );
  8052. case Colour::Red: return setColour( "[0;31m" );
  8053. case Colour::Green: return setColour( "[0;32m" );
  8054. case Colour::Blue: return setColour( "[0;34m" );
  8055. case Colour::Cyan: return setColour( "[0;36m" );
  8056. case Colour::Yellow: return setColour( "[0;33m" );
  8057. case Colour::Grey: return setColour( "[1;30m" );
  8058. case Colour::LightGrey: return setColour( "[0;37m" );
  8059. case Colour::BrightRed: return setColour( "[1;31m" );
  8060. case Colour::BrightGreen: return setColour( "[1;32m" );
  8061. case Colour::BrightWhite: return setColour( "[1;37m" );
  8062. case Colour::BrightYellow: return setColour( "[1;33m" );
  8063. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  8064. default: CATCH_INTERNAL_ERROR( "Unknown colour requested" );
  8065. }
  8066. }
  8067. static IColourImpl* instance() {
  8068. static PosixColourImpl s_instance;
  8069. return &s_instance;
  8070. }
  8071. private:
  8072. void setColour( const char* _escapeCode ) {
  8073. getCurrentContext().getConfig()->stream()
  8074. << '\033' << _escapeCode;
  8075. }
  8076. };
  8077. bool useColourOnPlatform() {
  8078. return
  8079. #ifdef CATCH_PLATFORM_MAC
  8080. !isDebuggerActive() &&
  8081. #endif
  8082. #if !(defined(__DJGPP__) && defined(__STRICT_ANSI__))
  8083. isatty(STDOUT_FILENO)
  8084. #else
  8085. false
  8086. #endif
  8087. ;
  8088. }
  8089. IColourImpl* platformColourInstance() {
  8090. ErrnoGuard guard;
  8091. IConfigPtr config = getCurrentContext().getConfig();
  8092. UseColour::YesOrNo colourMode = config
  8093. ? config->useColour()
  8094. : UseColour::Auto;
  8095. if( colourMode == UseColour::Auto )
  8096. colourMode = useColourOnPlatform()
  8097. ? UseColour::Yes
  8098. : UseColour::No;
  8099. return colourMode == UseColour::Yes
  8100. ? PosixColourImpl::instance()
  8101. : NoColourImpl::instance();
  8102. }
  8103. } // end anon namespace
  8104. } // end namespace Catch
  8105. #else // not Windows or ANSI ///////////////////////////////////////////////
  8106. namespace Catch {
  8107. static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); }
  8108. } // end namespace Catch
  8109. #endif // Windows/ ANSI/ None
  8110. namespace Catch {
  8111. Colour::Colour( Code _colourCode ) { use( _colourCode ); }
  8112. Colour::Colour( Colour&& rhs ) noexcept {
  8113. m_moved = rhs.m_moved;
  8114. rhs.m_moved = true;
  8115. }
  8116. Colour& Colour::operator=( Colour&& rhs ) noexcept {
  8117. m_moved = rhs.m_moved;
  8118. rhs.m_moved = true;
  8119. return *this;
  8120. }
  8121. Colour::~Colour(){ if( !m_moved ) use( None ); }
  8122. void Colour::use( Code _colourCode ) {
  8123. static IColourImpl* impl = platformColourInstance();
  8124. // Strictly speaking, this cannot possibly happen.
  8125. // However, under some conditions it does happen (see #1626),
  8126. // and this change is small enough that we can let practicality
  8127. // triumph over purity in this case.
  8128. if (impl != NULL) {
  8129. impl->use( _colourCode );
  8130. }
  8131. }
  8132. std::ostream& operator << ( std::ostream& os, Colour const& ) {
  8133. return os;
  8134. }
  8135. } // end namespace Catch
  8136. #if defined(__clang__)
  8137. # pragma clang diagnostic pop
  8138. #endif
  8139. // end catch_console_colour.cpp
  8140. // start catch_context.cpp
  8141. namespace Catch {
  8142. class Context : public IMutableContext, NonCopyable {
  8143. public: // IContext
  8144. IResultCapture* getResultCapture() override {
  8145. return m_resultCapture;
  8146. }
  8147. IRunner* getRunner() override {
  8148. return m_runner;
  8149. }
  8150. IConfigPtr const& getConfig() const override {
  8151. return m_config;
  8152. }
  8153. ~Context() override;
  8154. public: // IMutableContext
  8155. void setResultCapture( IResultCapture* resultCapture ) override {
  8156. m_resultCapture = resultCapture;
  8157. }
  8158. void setRunner( IRunner* runner ) override {
  8159. m_runner = runner;
  8160. }
  8161. void setConfig( IConfigPtr const& config ) override {
  8162. m_config = config;
  8163. }
  8164. friend IMutableContext& getCurrentMutableContext();
  8165. private:
  8166. IConfigPtr m_config;
  8167. IRunner* m_runner = nullptr;
  8168. IResultCapture* m_resultCapture = nullptr;
  8169. };
  8170. IMutableContext *IMutableContext::currentContext = nullptr;
  8171. void IMutableContext::createContext()
  8172. {
  8173. currentContext = new Context();
  8174. }
  8175. void cleanUpContext() {
  8176. delete IMutableContext::currentContext;
  8177. IMutableContext::currentContext = nullptr;
  8178. }
  8179. IContext::~IContext() = default;
  8180. IMutableContext::~IMutableContext() = default;
  8181. Context::~Context() = default;
  8182. }
  8183. // end catch_context.cpp
  8184. // start catch_debug_console.cpp
  8185. // start catch_debug_console.h
  8186. #include <string>
  8187. namespace Catch {
  8188. void writeToDebugConsole( std::string const& text );
  8189. }
  8190. // end catch_debug_console.h
  8191. #if defined(__ANDROID__)
  8192. #include <android/log.h>
  8193. namespace Catch {
  8194. void writeToDebugConsole( std::string const& text ) {
  8195. __android_log_print( ANDROID_LOG_DEBUG, "Catch", text.c_str() );
  8196. }
  8197. }
  8198. #elif defined(CATCH_PLATFORM_WINDOWS)
  8199. namespace Catch {
  8200. void writeToDebugConsole( std::string const& text ) {
  8201. ::OutputDebugStringA( text.c_str() );
  8202. }
  8203. }
  8204. #else
  8205. namespace Catch {
  8206. void writeToDebugConsole( std::string const& text ) {
  8207. // !TBD: Need a version for Mac/ XCode and other IDEs
  8208. Catch::cout() << text;
  8209. }
  8210. }
  8211. #endif // Platform
  8212. // end catch_debug_console.cpp
  8213. // start catch_debugger.cpp
  8214. #ifdef CATCH_PLATFORM_MAC
  8215. # include <assert.h>
  8216. # include <stdbool.h>
  8217. # include <sys/types.h>
  8218. # include <unistd.h>
  8219. # include <cstddef>
  8220. # include <ostream>
  8221. #ifdef __apple_build_version__
  8222. // These headers will only compile with AppleClang (XCode)
  8223. // For other compilers (Clang, GCC, ... ) we need to exclude them
  8224. # include <sys/sysctl.h>
  8225. #endif
  8226. namespace Catch {
  8227. #ifdef __apple_build_version__
  8228. // The following function is taken directly from the following technical note:
  8229. // https://developer.apple.com/library/archive/qa/qa1361/_index.html
  8230. // Returns true if the current process is being debugged (either
  8231. // running under the debugger or has a debugger attached post facto).
  8232. bool isDebuggerActive(){
  8233. int mib[4];
  8234. struct kinfo_proc info;
  8235. std::size_t size;
  8236. // Initialize the flags so that, if sysctl fails for some bizarre
  8237. // reason, we get a predictable result.
  8238. info.kp_proc.p_flag = 0;
  8239. // Initialize mib, which tells sysctl the info we want, in this case
  8240. // we're looking for information about a specific process ID.
  8241. mib[0] = CTL_KERN;
  8242. mib[1] = KERN_PROC;
  8243. mib[2] = KERN_PROC_PID;
  8244. mib[3] = getpid();
  8245. // Call sysctl.
  8246. size = sizeof(info);
  8247. if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0) != 0 ) {
  8248. Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl;
  8249. return false;
  8250. }
  8251. // We're being debugged if the P_TRACED flag is set.
  8252. return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
  8253. }
  8254. #else
  8255. bool isDebuggerActive() {
  8256. // We need to find another way to determine this for non-appleclang compilers on macOS
  8257. return false;
  8258. }
  8259. #endif
  8260. } // namespace Catch
  8261. #elif defined(CATCH_PLATFORM_LINUX)
  8262. #include <fstream>
  8263. #include <string>
  8264. namespace Catch{
  8265. // The standard POSIX way of detecting a debugger is to attempt to
  8266. // ptrace() the process, but this needs to be done from a child and not
  8267. // this process itself to still allow attaching to this process later
  8268. // if wanted, so is rather heavy. Under Linux we have the PID of the
  8269. // "debugger" (which doesn't need to be gdb, of course, it could also
  8270. // be strace, for example) in /proc/$PID/status, so just get it from
  8271. // there instead.
  8272. bool isDebuggerActive(){
  8273. // Libstdc++ has a bug, where std::ifstream sets errno to 0
  8274. // This way our users can properly assert over errno values
  8275. ErrnoGuard guard;
  8276. std::ifstream in("/proc/self/status");
  8277. for( std::string line; std::getline(in, line); ) {
  8278. static const int PREFIX_LEN = 11;
  8279. if( line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0 ) {
  8280. // We're traced if the PID is not 0 and no other PID starts
  8281. // with 0 digit, so it's enough to check for just a single
  8282. // character.
  8283. return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0';
  8284. }
  8285. }
  8286. return false;
  8287. }
  8288. } // namespace Catch
  8289. #elif defined(_MSC_VER)
  8290. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  8291. namespace Catch {
  8292. bool isDebuggerActive() {
  8293. return IsDebuggerPresent() != 0;
  8294. }
  8295. }
  8296. #elif defined(__MINGW32__)
  8297. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  8298. namespace Catch {
  8299. bool isDebuggerActive() {
  8300. return IsDebuggerPresent() != 0;
  8301. }
  8302. }
  8303. #else
  8304. namespace Catch {
  8305. bool isDebuggerActive() { return false; }
  8306. }
  8307. #endif // Platform
  8308. // end catch_debugger.cpp
  8309. // start catch_decomposer.cpp
  8310. namespace Catch {
  8311. ITransientExpression::~ITransientExpression() = default;
  8312. void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs ) {
  8313. if( lhs.size() + rhs.size() < 40 &&
  8314. lhs.find('\n') == std::string::npos &&
  8315. rhs.find('\n') == std::string::npos )
  8316. os << lhs << " " << op << " " << rhs;
  8317. else
  8318. os << lhs << "\n" << op << "\n" << rhs;
  8319. }
  8320. }
  8321. // end catch_decomposer.cpp
  8322. // start catch_enforce.cpp
  8323. #include <stdexcept>
  8324. namespace Catch {
  8325. #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS_CUSTOM_HANDLER)
  8326. [[noreturn]]
  8327. void throw_exception(std::exception const& e) {
  8328. Catch::cerr() << "Catch will terminate because it needed to throw an exception.\n"
  8329. << "The message was: " << e.what() << '\n';
  8330. std::terminate();
  8331. }
  8332. #endif
  8333. [[noreturn]]
  8334. void throw_logic_error(std::string const& msg) {
  8335. throw_exception(std::logic_error(msg));
  8336. }
  8337. [[noreturn]]
  8338. void throw_domain_error(std::string const& msg) {
  8339. throw_exception(std::domain_error(msg));
  8340. }
  8341. [[noreturn]]
  8342. void throw_runtime_error(std::string const& msg) {
  8343. throw_exception(std::runtime_error(msg));
  8344. }
  8345. } // namespace Catch;
  8346. // end catch_enforce.cpp
  8347. // start catch_enum_values_registry.cpp
  8348. // start catch_enum_values_registry.h
  8349. #include <vector>
  8350. #include <memory>
  8351. namespace Catch {
  8352. namespace Detail {
  8353. std::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int> const& values );
  8354. class EnumValuesRegistry : public IMutableEnumValuesRegistry {
  8355. std::vector<std::unique_ptr<EnumInfo>> m_enumInfos;
  8356. EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::vector<int> const& values) override;
  8357. };
  8358. std::vector<std::string> parseEnums( StringRef enums );
  8359. } // Detail
  8360. } // Catch
  8361. // end catch_enum_values_registry.h
  8362. #include <map>
  8363. #include <cassert>
  8364. namespace Catch {
  8365. IMutableEnumValuesRegistry::~IMutableEnumValuesRegistry() {}
  8366. namespace Detail {
  8367. std::vector<std::string> parseEnums( StringRef enums ) {
  8368. auto enumValues = splitStringRef( enums, ',' );
  8369. std::vector<std::string> parsed;
  8370. parsed.reserve( enumValues.size() );
  8371. for( auto const& enumValue : enumValues ) {
  8372. auto identifiers = splitStringRef( enumValue, ':' );
  8373. parsed.push_back( Catch::trim( identifiers.back() ) );
  8374. }
  8375. return parsed;
  8376. }
  8377. EnumInfo::~EnumInfo() {}
  8378. StringRef EnumInfo::lookup( int value ) const {
  8379. for( auto const& valueToName : m_values ) {
  8380. if( valueToName.first == value )
  8381. return valueToName.second;
  8382. }
  8383. return "{** unexpected enum value **}";
  8384. }
  8385. std::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ) {
  8386. std::unique_ptr<EnumInfo> enumInfo( new EnumInfo );
  8387. enumInfo->m_name = enumName;
  8388. enumInfo->m_values.reserve( values.size() );
  8389. const auto valueNames = Catch::Detail::parseEnums( allValueNames );
  8390. assert( valueNames.size() == values.size() );
  8391. std::size_t i = 0;
  8392. for( auto value : values )
  8393. enumInfo->m_values.push_back({ value, valueNames[i++] });
  8394. return enumInfo;
  8395. }
  8396. EnumInfo const& EnumValuesRegistry::registerEnum( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ) {
  8397. auto enumInfo = makeEnumInfo( enumName, allValueNames, values );
  8398. EnumInfo* raw = enumInfo.get();
  8399. m_enumInfos.push_back( std::move( enumInfo ) );
  8400. return *raw;
  8401. }
  8402. } // Detail
  8403. } // Catch
  8404. // end catch_enum_values_registry.cpp
  8405. // start catch_errno_guard.cpp
  8406. #include <cerrno>
  8407. namespace Catch {
  8408. ErrnoGuard::ErrnoGuard():m_oldErrno(errno){}
  8409. ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; }
  8410. }
  8411. // end catch_errno_guard.cpp
  8412. // start catch_exception_translator_registry.cpp
  8413. // start catch_exception_translator_registry.h
  8414. #include <vector>
  8415. #include <string>
  8416. #include <memory>
  8417. namespace Catch {
  8418. class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry {
  8419. public:
  8420. ~ExceptionTranslatorRegistry();
  8421. virtual void registerTranslator( const IExceptionTranslator* translator );
  8422. std::string translateActiveException() const override;
  8423. std::string tryTranslators() const;
  8424. private:
  8425. std::vector<std::unique_ptr<IExceptionTranslator const>> m_translators;
  8426. };
  8427. }
  8428. // end catch_exception_translator_registry.h
  8429. #ifdef __OBJC__
  8430. #import "Foundation/Foundation.h"
  8431. #endif
  8432. namespace Catch {
  8433. ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {
  8434. }
  8435. void ExceptionTranslatorRegistry::registerTranslator( const IExceptionTranslator* translator ) {
  8436. m_translators.push_back( std::unique_ptr<const IExceptionTranslator>( translator ) );
  8437. }
  8438. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  8439. std::string ExceptionTranslatorRegistry::translateActiveException() const {
  8440. try {
  8441. #ifdef __OBJC__
  8442. // In Objective-C try objective-c exceptions first
  8443. @try {
  8444. return tryTranslators();
  8445. }
  8446. @catch (NSException *exception) {
  8447. return Catch::Detail::stringify( [exception description] );
  8448. }
  8449. #else
  8450. // Compiling a mixed mode project with MSVC means that CLR
  8451. // exceptions will be caught in (...) as well. However, these
  8452. // do not fill-in std::current_exception and thus lead to crash
  8453. // when attempting rethrow.
  8454. // /EHa switch also causes structured exceptions to be caught
  8455. // here, but they fill-in current_exception properly, so
  8456. // at worst the output should be a little weird, instead of
  8457. // causing a crash.
  8458. if (std::current_exception() == nullptr) {
  8459. return "Non C++ exception. Possibly a CLR exception.";
  8460. }
  8461. return tryTranslators();
  8462. #endif
  8463. }
  8464. catch( TestFailureException& ) {
  8465. std::rethrow_exception(std::current_exception());
  8466. }
  8467. catch( std::exception& ex ) {
  8468. return ex.what();
  8469. }
  8470. catch( std::string& msg ) {
  8471. return msg;
  8472. }
  8473. catch( const char* msg ) {
  8474. return msg;
  8475. }
  8476. catch(...) {
  8477. return "Unknown exception";
  8478. }
  8479. }
  8480. std::string ExceptionTranslatorRegistry::tryTranslators() const {
  8481. if (m_translators.empty()) {
  8482. std::rethrow_exception(std::current_exception());
  8483. } else {
  8484. return m_translators[0]->translate(m_translators.begin() + 1, m_translators.end());
  8485. }
  8486. }
  8487. #else // ^^ Exceptions are enabled // Exceptions are disabled vv
  8488. std::string ExceptionTranslatorRegistry::translateActiveException() const {
  8489. CATCH_INTERNAL_ERROR("Attempted to translate active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
  8490. }
  8491. std::string ExceptionTranslatorRegistry::tryTranslators() const {
  8492. CATCH_INTERNAL_ERROR("Attempted to use exception translators under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
  8493. }
  8494. #endif
  8495. }
  8496. // end catch_exception_translator_registry.cpp
  8497. // start catch_fatal_condition.cpp
  8498. #if defined(__GNUC__)
  8499. # pragma GCC diagnostic push
  8500. # pragma GCC diagnostic ignored "-Wmissing-field-initializers"
  8501. #endif
  8502. #if defined( CATCH_CONFIG_WINDOWS_SEH ) || defined( CATCH_CONFIG_POSIX_SIGNALS )
  8503. namespace {
  8504. // Report the error condition
  8505. void reportFatal( char const * const message ) {
  8506. Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition( message );
  8507. }
  8508. }
  8509. #endif // signals/SEH handling
  8510. #if defined( CATCH_CONFIG_WINDOWS_SEH )
  8511. namespace Catch {
  8512. struct SignalDefs { DWORD id; const char* name; };
  8513. // There is no 1-1 mapping between signals and windows exceptions.
  8514. // Windows can easily distinguish between SO and SigSegV,
  8515. // but SigInt, SigTerm, etc are handled differently.
  8516. static SignalDefs signalDefs[] = {
  8517. { static_cast<DWORD>(EXCEPTION_ILLEGAL_INSTRUCTION), "SIGILL - Illegal instruction signal" },
  8518. { static_cast<DWORD>(EXCEPTION_STACK_OVERFLOW), "SIGSEGV - Stack overflow" },
  8519. { static_cast<DWORD>(EXCEPTION_ACCESS_VIOLATION), "SIGSEGV - Segmentation violation signal" },
  8520. { static_cast<DWORD>(EXCEPTION_INT_DIVIDE_BY_ZERO), "Divide by zero error" },
  8521. };
  8522. LONG CALLBACK FatalConditionHandler::handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {
  8523. for (auto const& def : signalDefs) {
  8524. if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) {
  8525. reportFatal(def.name);
  8526. }
  8527. }
  8528. // If its not an exception we care about, pass it along.
  8529. // This stops us from eating debugger breaks etc.
  8530. return EXCEPTION_CONTINUE_SEARCH;
  8531. }
  8532. FatalConditionHandler::FatalConditionHandler() {
  8533. isSet = true;
  8534. // 32k seems enough for Catch to handle stack overflow,
  8535. // but the value was found experimentally, so there is no strong guarantee
  8536. guaranteeSize = 32 * 1024;
  8537. exceptionHandlerHandle = nullptr;
  8538. // Register as first handler in current chain
  8539. exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);
  8540. // Pass in guarantee size to be filled
  8541. SetThreadStackGuarantee(&guaranteeSize);
  8542. }
  8543. void FatalConditionHandler::reset() {
  8544. if (isSet) {
  8545. RemoveVectoredExceptionHandler(exceptionHandlerHandle);
  8546. SetThreadStackGuarantee(&guaranteeSize);
  8547. exceptionHandlerHandle = nullptr;
  8548. isSet = false;
  8549. }
  8550. }
  8551. FatalConditionHandler::~FatalConditionHandler() {
  8552. reset();
  8553. }
  8554. bool FatalConditionHandler::isSet = false;
  8555. ULONG FatalConditionHandler::guaranteeSize = 0;
  8556. PVOID FatalConditionHandler::exceptionHandlerHandle = nullptr;
  8557. } // namespace Catch
  8558. #elif defined( CATCH_CONFIG_POSIX_SIGNALS )
  8559. namespace Catch {
  8560. struct SignalDefs {
  8561. int id;
  8562. const char* name;
  8563. };
  8564. // 32kb for the alternate stack seems to be sufficient. However, this value
  8565. // is experimentally determined, so that's not guaranteed.
  8566. static constexpr std::size_t sigStackSize = 32768 >= MINSIGSTKSZ ? 32768 : MINSIGSTKSZ;
  8567. static SignalDefs signalDefs[] = {
  8568. { SIGINT, "SIGINT - Terminal interrupt signal" },
  8569. { SIGILL, "SIGILL - Illegal instruction signal" },
  8570. { SIGFPE, "SIGFPE - Floating point error signal" },
  8571. { SIGSEGV, "SIGSEGV - Segmentation violation signal" },
  8572. { SIGTERM, "SIGTERM - Termination request signal" },
  8573. { SIGABRT, "SIGABRT - Abort (abnormal termination) signal" }
  8574. };
  8575. void FatalConditionHandler::handleSignal( int sig ) {
  8576. char const * name = "<unknown signal>";
  8577. for (auto const& def : signalDefs) {
  8578. if (sig == def.id) {
  8579. name = def.name;
  8580. break;
  8581. }
  8582. }
  8583. reset();
  8584. reportFatal(name);
  8585. raise( sig );
  8586. }
  8587. FatalConditionHandler::FatalConditionHandler() {
  8588. isSet = true;
  8589. stack_t sigStack;
  8590. sigStack.ss_sp = altStackMem;
  8591. sigStack.ss_size = sigStackSize;
  8592. sigStack.ss_flags = 0;
  8593. sigaltstack(&sigStack, &oldSigStack);
  8594. struct sigaction sa = { };
  8595. sa.sa_handler = handleSignal;
  8596. sa.sa_flags = SA_ONSTACK;
  8597. for (std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i) {
  8598. sigaction(signalDefs[i].id, &sa, &oldSigActions[i]);
  8599. }
  8600. }
  8601. FatalConditionHandler::~FatalConditionHandler() {
  8602. reset();
  8603. }
  8604. void FatalConditionHandler::reset() {
  8605. if( isSet ) {
  8606. // Set signals back to previous values -- hopefully nobody overwrote them in the meantime
  8607. for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) {
  8608. sigaction(signalDefs[i].id, &oldSigActions[i], nullptr);
  8609. }
  8610. // Return the old stack
  8611. sigaltstack(&oldSigStack, nullptr);
  8612. isSet = false;
  8613. }
  8614. }
  8615. bool FatalConditionHandler::isSet = false;
  8616. struct sigaction FatalConditionHandler::oldSigActions[sizeof(signalDefs)/sizeof(SignalDefs)] = {};
  8617. stack_t FatalConditionHandler::oldSigStack = {};
  8618. char FatalConditionHandler::altStackMem[sigStackSize] = {};
  8619. } // namespace Catch
  8620. #else
  8621. namespace Catch {
  8622. void FatalConditionHandler::reset() {}
  8623. }
  8624. #endif // signals/SEH handling
  8625. #if defined(__GNUC__)
  8626. # pragma GCC diagnostic pop
  8627. #endif
  8628. // end catch_fatal_condition.cpp
  8629. // start catch_generators.cpp
  8630. // start catch_random_number_generator.h
  8631. #include <algorithm>
  8632. #include <random>
  8633. namespace Catch {
  8634. struct IConfig;
  8635. std::mt19937& rng();
  8636. void seedRng( IConfig const& config );
  8637. unsigned int rngSeed();
  8638. }
  8639. // end catch_random_number_generator.h
  8640. #include <limits>
  8641. #include <set>
  8642. namespace Catch {
  8643. IGeneratorTracker::~IGeneratorTracker() {}
  8644. const char* GeneratorException::what() const noexcept {
  8645. return m_msg;
  8646. }
  8647. namespace Generators {
  8648. GeneratorUntypedBase::~GeneratorUntypedBase() {}
  8649. auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
  8650. return getResultCapture().acquireGeneratorTracker( lineInfo );
  8651. }
  8652. } // namespace Generators
  8653. } // namespace Catch
  8654. // end catch_generators.cpp
  8655. // start catch_interfaces_capture.cpp
  8656. namespace Catch {
  8657. IResultCapture::~IResultCapture() = default;
  8658. }
  8659. // end catch_interfaces_capture.cpp
  8660. // start catch_interfaces_config.cpp
  8661. namespace Catch {
  8662. IConfig::~IConfig() = default;
  8663. }
  8664. // end catch_interfaces_config.cpp
  8665. // start catch_interfaces_exception.cpp
  8666. namespace Catch {
  8667. IExceptionTranslator::~IExceptionTranslator() = default;
  8668. IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() = default;
  8669. }
  8670. // end catch_interfaces_exception.cpp
  8671. // start catch_interfaces_registry_hub.cpp
  8672. namespace Catch {
  8673. IRegistryHub::~IRegistryHub() = default;
  8674. IMutableRegistryHub::~IMutableRegistryHub() = default;
  8675. }
  8676. // end catch_interfaces_registry_hub.cpp
  8677. // start catch_interfaces_reporter.cpp
  8678. // start catch_reporter_listening.h
  8679. namespace Catch {
  8680. class ListeningReporter : public IStreamingReporter {
  8681. using Reporters = std::vector<IStreamingReporterPtr>;
  8682. Reporters m_listeners;
  8683. IStreamingReporterPtr m_reporter = nullptr;
  8684. ReporterPreferences m_preferences;
  8685. public:
  8686. ListeningReporter();
  8687. void addListener( IStreamingReporterPtr&& listener );
  8688. void addReporter( IStreamingReporterPtr&& reporter );
  8689. public: // IStreamingReporter
  8690. ReporterPreferences getPreferences() const override;
  8691. void noMatchingTestCases( std::string const& spec ) override;
  8692. static std::set<Verbosity> getSupportedVerbosities();
  8693. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  8694. void benchmarkPreparing(std::string const& name) override;
  8695. void benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) override;
  8696. void benchmarkEnded( BenchmarkStats<> const& benchmarkStats ) override;
  8697. void benchmarkFailed(std::string const&) override;
  8698. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  8699. void testRunStarting( TestRunInfo const& testRunInfo ) override;
  8700. void testGroupStarting( GroupInfo const& groupInfo ) override;
  8701. void testCaseStarting( TestCaseInfo const& testInfo ) override;
  8702. void sectionStarting( SectionInfo const& sectionInfo ) override;
  8703. void assertionStarting( AssertionInfo const& assertionInfo ) override;
  8704. // The return value indicates if the messages buffer should be cleared:
  8705. bool assertionEnded( AssertionStats const& assertionStats ) override;
  8706. void sectionEnded( SectionStats const& sectionStats ) override;
  8707. void testCaseEnded( TestCaseStats const& testCaseStats ) override;
  8708. void testGroupEnded( TestGroupStats const& testGroupStats ) override;
  8709. void testRunEnded( TestRunStats const& testRunStats ) override;
  8710. void skipTest( TestCaseInfo const& testInfo ) override;
  8711. bool isMulti() const override;
  8712. };
  8713. } // end namespace Catch
  8714. // end catch_reporter_listening.h
  8715. namespace Catch {
  8716. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig )
  8717. : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {}
  8718. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream )
  8719. : m_stream( &_stream ), m_fullConfig( _fullConfig ) {}
  8720. std::ostream& ReporterConfig::stream() const { return *m_stream; }
  8721. IConfigPtr ReporterConfig::fullConfig() const { return m_fullConfig; }
  8722. TestRunInfo::TestRunInfo( std::string const& _name ) : name( _name ) {}
  8723. GroupInfo::GroupInfo( std::string const& _name,
  8724. std::size_t _groupIndex,
  8725. std::size_t _groupsCount )
  8726. : name( _name ),
  8727. groupIndex( _groupIndex ),
  8728. groupsCounts( _groupsCount )
  8729. {}
  8730. AssertionStats::AssertionStats( AssertionResult const& _assertionResult,
  8731. std::vector<MessageInfo> const& _infoMessages,
  8732. Totals const& _totals )
  8733. : assertionResult( _assertionResult ),
  8734. infoMessages( _infoMessages ),
  8735. totals( _totals )
  8736. {
  8737. assertionResult.m_resultData.lazyExpression.m_transientExpression = _assertionResult.m_resultData.lazyExpression.m_transientExpression;
  8738. if( assertionResult.hasMessage() ) {
  8739. // Copy message into messages list.
  8740. // !TBD This should have been done earlier, somewhere
  8741. MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() );
  8742. builder << assertionResult.getMessage();
  8743. builder.m_info.message = builder.m_stream.str();
  8744. infoMessages.push_back( builder.m_info );
  8745. }
  8746. }
  8747. AssertionStats::~AssertionStats() = default;
  8748. SectionStats::SectionStats( SectionInfo const& _sectionInfo,
  8749. Counts const& _assertions,
  8750. double _durationInSeconds,
  8751. bool _missingAssertions )
  8752. : sectionInfo( _sectionInfo ),
  8753. assertions( _assertions ),
  8754. durationInSeconds( _durationInSeconds ),
  8755. missingAssertions( _missingAssertions )
  8756. {}
  8757. SectionStats::~SectionStats() = default;
  8758. TestCaseStats::TestCaseStats( TestCaseInfo const& _testInfo,
  8759. Totals const& _totals,
  8760. std::string const& _stdOut,
  8761. std::string const& _stdErr,
  8762. bool _aborting )
  8763. : testInfo( _testInfo ),
  8764. totals( _totals ),
  8765. stdOut( _stdOut ),
  8766. stdErr( _stdErr ),
  8767. aborting( _aborting )
  8768. {}
  8769. TestCaseStats::~TestCaseStats() = default;
  8770. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo,
  8771. Totals const& _totals,
  8772. bool _aborting )
  8773. : groupInfo( _groupInfo ),
  8774. totals( _totals ),
  8775. aborting( _aborting )
  8776. {}
  8777. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo )
  8778. : groupInfo( _groupInfo ),
  8779. aborting( false )
  8780. {}
  8781. TestGroupStats::~TestGroupStats() = default;
  8782. TestRunStats::TestRunStats( TestRunInfo const& _runInfo,
  8783. Totals const& _totals,
  8784. bool _aborting )
  8785. : runInfo( _runInfo ),
  8786. totals( _totals ),
  8787. aborting( _aborting )
  8788. {}
  8789. TestRunStats::~TestRunStats() = default;
  8790. void IStreamingReporter::fatalErrorEncountered( StringRef ) {}
  8791. bool IStreamingReporter::isMulti() const { return false; }
  8792. IReporterFactory::~IReporterFactory() = default;
  8793. IReporterRegistry::~IReporterRegistry() = default;
  8794. } // end namespace Catch
  8795. // end catch_interfaces_reporter.cpp
  8796. // start catch_interfaces_runner.cpp
  8797. namespace Catch {
  8798. IRunner::~IRunner() = default;
  8799. }
  8800. // end catch_interfaces_runner.cpp
  8801. // start catch_interfaces_testcase.cpp
  8802. namespace Catch {
  8803. ITestInvoker::~ITestInvoker() = default;
  8804. ITestCaseRegistry::~ITestCaseRegistry() = default;
  8805. }
  8806. // end catch_interfaces_testcase.cpp
  8807. // start catch_leak_detector.cpp
  8808. #ifdef CATCH_CONFIG_WINDOWS_CRTDBG
  8809. #include <crtdbg.h>
  8810. namespace Catch {
  8811. LeakDetector::LeakDetector() {
  8812. int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
  8813. flag |= _CRTDBG_LEAK_CHECK_DF;
  8814. flag |= _CRTDBG_ALLOC_MEM_DF;
  8815. _CrtSetDbgFlag(flag);
  8816. _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
  8817. _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
  8818. // Change this to leaking allocation's number to break there
  8819. _CrtSetBreakAlloc(-1);
  8820. }
  8821. }
  8822. #else
  8823. Catch::LeakDetector::LeakDetector() {}
  8824. #endif
  8825. Catch::LeakDetector::~LeakDetector() {
  8826. Catch::cleanUp();
  8827. }
  8828. // end catch_leak_detector.cpp
  8829. // start catch_list.cpp
  8830. // start catch_list.h
  8831. #include <set>
  8832. namespace Catch {
  8833. std::size_t listTests( Config const& config );
  8834. std::size_t listTestsNamesOnly( Config const& config );
  8835. struct TagInfo {
  8836. void add( std::string const& spelling );
  8837. std::string all() const;
  8838. std::set<std::string> spellings;
  8839. std::size_t count = 0;
  8840. };
  8841. std::size_t listTags( Config const& config );
  8842. std::size_t listReporters();
  8843. Option<std::size_t> list( std::shared_ptr<Config> const& config );
  8844. } // end namespace Catch
  8845. // end catch_list.h
  8846. // start catch_text.h
  8847. namespace Catch {
  8848. using namespace clara::TextFlow;
  8849. }
  8850. // end catch_text.h
  8851. #include <limits>
  8852. #include <algorithm>
  8853. #include <iomanip>
  8854. namespace Catch {
  8855. std::size_t listTests( Config const& config ) {
  8856. TestSpec testSpec = config.testSpec();
  8857. if( config.hasTestFilters() )
  8858. Catch::cout() << "Matching test cases:\n";
  8859. else {
  8860. Catch::cout() << "All available test cases:\n";
  8861. }
  8862. auto matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  8863. for( auto const& testCaseInfo : matchedTestCases ) {
  8864. Colour::Code colour = testCaseInfo.isHidden()
  8865. ? Colour::SecondaryText
  8866. : Colour::None;
  8867. Colour colourGuard( colour );
  8868. Catch::cout() << Column( testCaseInfo.name ).initialIndent( 2 ).indent( 4 ) << "\n";
  8869. if( config.verbosity() >= Verbosity::High ) {
  8870. Catch::cout() << Column( Catch::Detail::stringify( testCaseInfo.lineInfo ) ).indent(4) << std::endl;
  8871. std::string description = testCaseInfo.description;
  8872. if( description.empty() )
  8873. description = "(NO DESCRIPTION)";
  8874. Catch::cout() << Column( description ).indent(4) << std::endl;
  8875. }
  8876. if( !testCaseInfo.tags.empty() )
  8877. Catch::cout() << Column( testCaseInfo.tagsAsString() ).indent( 6 ) << "\n";
  8878. }
  8879. if( !config.hasTestFilters() )
  8880. Catch::cout() << pluralise( matchedTestCases.size(), "test case" ) << '\n' << std::endl;
  8881. else
  8882. Catch::cout() << pluralise( matchedTestCases.size(), "matching test case" ) << '\n' << std::endl;
  8883. return matchedTestCases.size();
  8884. }
  8885. std::size_t listTestsNamesOnly( Config const& config ) {
  8886. TestSpec testSpec = config.testSpec();
  8887. std::size_t matchedTests = 0;
  8888. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  8889. for( auto const& testCaseInfo : matchedTestCases ) {
  8890. matchedTests++;
  8891. if( startsWith( testCaseInfo.name, '#' ) )
  8892. Catch::cout() << '"' << testCaseInfo.name << '"';
  8893. else
  8894. Catch::cout() << testCaseInfo.name;
  8895. if ( config.verbosity() >= Verbosity::High )
  8896. Catch::cout() << "\t@" << testCaseInfo.lineInfo;
  8897. Catch::cout() << std::endl;
  8898. }
  8899. return matchedTests;
  8900. }
  8901. void TagInfo::add( std::string const& spelling ) {
  8902. ++count;
  8903. spellings.insert( spelling );
  8904. }
  8905. std::string TagInfo::all() const {
  8906. size_t size = 0;
  8907. for (auto const& spelling : spellings) {
  8908. // Add 2 for the brackes
  8909. size += spelling.size() + 2;
  8910. }
  8911. std::string out; out.reserve(size);
  8912. for (auto const& spelling : spellings) {
  8913. out += '[';
  8914. out += spelling;
  8915. out += ']';
  8916. }
  8917. return out;
  8918. }
  8919. std::size_t listTags( Config const& config ) {
  8920. TestSpec testSpec = config.testSpec();
  8921. if( config.hasTestFilters() )
  8922. Catch::cout() << "Tags for matching test cases:\n";
  8923. else {
  8924. Catch::cout() << "All available tags:\n";
  8925. }
  8926. std::map<std::string, TagInfo> tagCounts;
  8927. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  8928. for( auto const& testCase : matchedTestCases ) {
  8929. for( auto const& tagName : testCase.getTestCaseInfo().tags ) {
  8930. std::string lcaseTagName = toLower( tagName );
  8931. auto countIt = tagCounts.find( lcaseTagName );
  8932. if( countIt == tagCounts.end() )
  8933. countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first;
  8934. countIt->second.add( tagName );
  8935. }
  8936. }
  8937. for( auto const& tagCount : tagCounts ) {
  8938. ReusableStringStream rss;
  8939. rss << " " << std::setw(2) << tagCount.second.count << " ";
  8940. auto str = rss.str();
  8941. auto wrapper = Column( tagCount.second.all() )
  8942. .initialIndent( 0 )
  8943. .indent( str.size() )
  8944. .width( CATCH_CONFIG_CONSOLE_WIDTH-10 );
  8945. Catch::cout() << str << wrapper << '\n';
  8946. }
  8947. Catch::cout() << pluralise( tagCounts.size(), "tag" ) << '\n' << std::endl;
  8948. return tagCounts.size();
  8949. }
  8950. std::size_t listReporters() {
  8951. Catch::cout() << "Available reporters:\n";
  8952. IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
  8953. std::size_t maxNameLen = 0;
  8954. for( auto const& factoryKvp : factories )
  8955. maxNameLen = (std::max)( maxNameLen, factoryKvp.first.size() );
  8956. for( auto const& factoryKvp : factories ) {
  8957. Catch::cout()
  8958. << Column( factoryKvp.first + ":" )
  8959. .indent(2)
  8960. .width( 5+maxNameLen )
  8961. + Column( factoryKvp.second->getDescription() )
  8962. .initialIndent(0)
  8963. .indent(2)
  8964. .width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 )
  8965. << "\n";
  8966. }
  8967. Catch::cout() << std::endl;
  8968. return factories.size();
  8969. }
  8970. Option<std::size_t> list( std::shared_ptr<Config> const& config ) {
  8971. Option<std::size_t> listedCount;
  8972. getCurrentMutableContext().setConfig( config );
  8973. if( config->listTests() )
  8974. listedCount = listedCount.valueOr(0) + listTests( *config );
  8975. if( config->listTestNamesOnly() )
  8976. listedCount = listedCount.valueOr(0) + listTestsNamesOnly( *config );
  8977. if( config->listTags() )
  8978. listedCount = listedCount.valueOr(0) + listTags( *config );
  8979. if( config->listReporters() )
  8980. listedCount = listedCount.valueOr(0) + listReporters();
  8981. return listedCount;
  8982. }
  8983. } // end namespace Catch
  8984. // end catch_list.cpp
  8985. // start catch_matchers.cpp
  8986. namespace Catch {
  8987. namespace Matchers {
  8988. namespace Impl {
  8989. std::string MatcherUntypedBase::toString() const {
  8990. if( m_cachedToString.empty() )
  8991. m_cachedToString = describe();
  8992. return m_cachedToString;
  8993. }
  8994. MatcherUntypedBase::~MatcherUntypedBase() = default;
  8995. } // namespace Impl
  8996. } // namespace Matchers
  8997. using namespace Matchers;
  8998. using Matchers::Impl::MatcherBase;
  8999. } // namespace Catch
  9000. // end catch_matchers.cpp
  9001. // start catch_matchers_floating.cpp
  9002. // start catch_polyfills.hpp
  9003. namespace Catch {
  9004. bool isnan(float f);
  9005. bool isnan(double d);
  9006. }
  9007. // end catch_polyfills.hpp
  9008. // start catch_to_string.hpp
  9009. #include <string>
  9010. namespace Catch {
  9011. template <typename T>
  9012. std::string to_string(T const& t) {
  9013. #if defined(CATCH_CONFIG_CPP11_TO_STRING)
  9014. return std::to_string(t);
  9015. #else
  9016. ReusableStringStream rss;
  9017. rss << t;
  9018. return rss.str();
  9019. #endif
  9020. }
  9021. } // end namespace Catch
  9022. // end catch_to_string.hpp
  9023. #include <cstdlib>
  9024. #include <cstdint>
  9025. #include <cstring>
  9026. #include <sstream>
  9027. #include <iomanip>
  9028. #include <limits>
  9029. namespace Catch {
  9030. namespace Matchers {
  9031. namespace Floating {
  9032. enum class FloatingPointKind : uint8_t {
  9033. Float,
  9034. Double
  9035. };
  9036. }
  9037. }
  9038. }
  9039. namespace {
  9040. template <typename T>
  9041. struct Converter;
  9042. template <>
  9043. struct Converter<float> {
  9044. static_assert(sizeof(float) == sizeof(int32_t), "Important ULP matcher assumption violated");
  9045. Converter(float f) {
  9046. std::memcpy(&i, &f, sizeof(f));
  9047. }
  9048. int32_t i;
  9049. };
  9050. template <>
  9051. struct Converter<double> {
  9052. static_assert(sizeof(double) == sizeof(int64_t), "Important ULP matcher assumption violated");
  9053. Converter(double d) {
  9054. std::memcpy(&i, &d, sizeof(d));
  9055. }
  9056. int64_t i;
  9057. };
  9058. template <typename T>
  9059. auto convert(T t) -> Converter<T> {
  9060. return Converter<T>(t);
  9061. }
  9062. template <typename FP>
  9063. bool almostEqualUlps(FP lhs, FP rhs, int maxUlpDiff) {
  9064. // Comparison with NaN should always be false.
  9065. // This way we can rule it out before getting into the ugly details
  9066. if (Catch::isnan(lhs) || Catch::isnan(rhs)) {
  9067. return false;
  9068. }
  9069. auto lc = convert(lhs);
  9070. auto rc = convert(rhs);
  9071. if ((lc.i < 0) != (rc.i < 0)) {
  9072. // Potentially we can have +0 and -0
  9073. return lhs == rhs;
  9074. }
  9075. auto ulpDiff = std::abs(lc.i - rc.i);
  9076. return ulpDiff <= maxUlpDiff;
  9077. }
  9078. template <typename FP>
  9079. FP step(FP start, FP direction, int steps) {
  9080. for (int i = 0; i < steps; ++i) {
  9081. start = std::nextafter(start, direction);
  9082. }
  9083. return start;
  9084. }
  9085. } // end anonymous namespace
  9086. namespace Catch {
  9087. namespace Matchers {
  9088. namespace Floating {
  9089. WithinAbsMatcher::WithinAbsMatcher(double target, double margin)
  9090. :m_target{ target }, m_margin{ margin } {
  9091. CATCH_ENFORCE(margin >= 0, "Invalid margin: " << margin << '.'
  9092. << " Margin has to be non-negative.");
  9093. }
  9094. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  9095. // But without the subtraction to allow for INFINITY in comparison
  9096. bool WithinAbsMatcher::match(double const& matchee) const {
  9097. return (matchee + m_margin >= m_target) && (m_target + m_margin >= matchee);
  9098. }
  9099. std::string WithinAbsMatcher::describe() const {
  9100. return "is within " + ::Catch::Detail::stringify(m_margin) + " of " + ::Catch::Detail::stringify(m_target);
  9101. }
  9102. WithinUlpsMatcher::WithinUlpsMatcher(double target, int ulps, FloatingPointKind baseType)
  9103. :m_target{ target }, m_ulps{ ulps }, m_type{ baseType } {
  9104. CATCH_ENFORCE(ulps >= 0, "Invalid ULP setting: " << ulps << '.'
  9105. << " ULPs have to be non-negative.");
  9106. }
  9107. #if defined(__clang__)
  9108. #pragma clang diagnostic push
  9109. // Clang <3.5 reports on the default branch in the switch below
  9110. #pragma clang diagnostic ignored "-Wunreachable-code"
  9111. #endif
  9112. bool WithinUlpsMatcher::match(double const& matchee) const {
  9113. switch (m_type) {
  9114. case FloatingPointKind::Float:
  9115. return almostEqualUlps<float>(static_cast<float>(matchee), static_cast<float>(m_target), m_ulps);
  9116. case FloatingPointKind::Double:
  9117. return almostEqualUlps<double>(matchee, m_target, m_ulps);
  9118. default:
  9119. CATCH_INTERNAL_ERROR( "Unknown FloatingPointKind value" );
  9120. }
  9121. }
  9122. #if defined(__clang__)
  9123. #pragma clang diagnostic pop
  9124. #endif
  9125. std::string WithinUlpsMatcher::describe() const {
  9126. std::stringstream ret;
  9127. ret << "is within " << m_ulps << " ULPs of " << ::Catch::Detail::stringify(m_target);
  9128. if (m_type == FloatingPointKind::Float) {
  9129. ret << 'f';
  9130. }
  9131. ret << " ([";
  9132. ret << std::fixed << std::setprecision(std::numeric_limits<double>::max_digits10);
  9133. if (m_type == FloatingPointKind::Double) {
  9134. ret << step(m_target, static_cast<double>(-INFINITY), m_ulps)
  9135. << ", "
  9136. << step(m_target, static_cast<double>(INFINITY), m_ulps);
  9137. } else {
  9138. ret << step<float>(static_cast<float>(m_target), -INFINITY, m_ulps)
  9139. << ", "
  9140. << step<float>(static_cast<float>(m_target), INFINITY, m_ulps);
  9141. }
  9142. ret << "])";
  9143. return ret.str();
  9144. //return "is within " + Catch::to_string(m_ulps) + " ULPs of " + ::Catch::Detail::stringify(m_target) + ((m_type == FloatingPointKind::Float)? "f" : "");
  9145. }
  9146. }// namespace Floating
  9147. Floating::WithinUlpsMatcher WithinULP(double target, int maxUlpDiff) {
  9148. return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Double);
  9149. }
  9150. Floating::WithinUlpsMatcher WithinULP(float target, int maxUlpDiff) {
  9151. return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Float);
  9152. }
  9153. Floating::WithinAbsMatcher WithinAbs(double target, double margin) {
  9154. return Floating::WithinAbsMatcher(target, margin);
  9155. }
  9156. } // namespace Matchers
  9157. } // namespace Catch
  9158. // end catch_matchers_floating.cpp
  9159. // start catch_matchers_generic.cpp
  9160. std::string Catch::Matchers::Generic::Detail::finalizeDescription(const std::string& desc) {
  9161. if (desc.empty()) {
  9162. return "matches undescribed predicate";
  9163. } else {
  9164. return "matches predicate: \"" + desc + '"';
  9165. }
  9166. }
  9167. // end catch_matchers_generic.cpp
  9168. // start catch_matchers_string.cpp
  9169. #include <regex>
  9170. namespace Catch {
  9171. namespace Matchers {
  9172. namespace StdString {
  9173. CasedString::CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity )
  9174. : m_caseSensitivity( caseSensitivity ),
  9175. m_str( adjustString( str ) )
  9176. {}
  9177. std::string CasedString::adjustString( std::string const& str ) const {
  9178. return m_caseSensitivity == CaseSensitive::No
  9179. ? toLower( str )
  9180. : str;
  9181. }
  9182. std::string CasedString::caseSensitivitySuffix() const {
  9183. return m_caseSensitivity == CaseSensitive::No
  9184. ? " (case insensitive)"
  9185. : std::string();
  9186. }
  9187. StringMatcherBase::StringMatcherBase( std::string const& operation, CasedString const& comparator )
  9188. : m_comparator( comparator ),
  9189. m_operation( operation ) {
  9190. }
  9191. std::string StringMatcherBase::describe() const {
  9192. std::string description;
  9193. description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
  9194. m_comparator.caseSensitivitySuffix().size());
  9195. description += m_operation;
  9196. description += ": \"";
  9197. description += m_comparator.m_str;
  9198. description += "\"";
  9199. description += m_comparator.caseSensitivitySuffix();
  9200. return description;
  9201. }
  9202. EqualsMatcher::EqualsMatcher( CasedString const& comparator ) : StringMatcherBase( "equals", comparator ) {}
  9203. bool EqualsMatcher::match( std::string const& source ) const {
  9204. return m_comparator.adjustString( source ) == m_comparator.m_str;
  9205. }
  9206. ContainsMatcher::ContainsMatcher( CasedString const& comparator ) : StringMatcherBase( "contains", comparator ) {}
  9207. bool ContainsMatcher::match( std::string const& source ) const {
  9208. return contains( m_comparator.adjustString( source ), m_comparator.m_str );
  9209. }
  9210. StartsWithMatcher::StartsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "starts with", comparator ) {}
  9211. bool StartsWithMatcher::match( std::string const& source ) const {
  9212. return startsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  9213. }
  9214. EndsWithMatcher::EndsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "ends with", comparator ) {}
  9215. bool EndsWithMatcher::match( std::string const& source ) const {
  9216. return endsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  9217. }
  9218. RegexMatcher::RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity): m_regex(std::move(regex)), m_caseSensitivity(caseSensitivity) {}
  9219. bool RegexMatcher::match(std::string const& matchee) const {
  9220. auto flags = std::regex::ECMAScript; // ECMAScript is the default syntax option anyway
  9221. if (m_caseSensitivity == CaseSensitive::Choice::No) {
  9222. flags |= std::regex::icase;
  9223. }
  9224. auto reg = std::regex(m_regex, flags);
  9225. return std::regex_match(matchee, reg);
  9226. }
  9227. std::string RegexMatcher::describe() const {
  9228. return "matches " + ::Catch::Detail::stringify(m_regex) + ((m_caseSensitivity == CaseSensitive::Choice::Yes)? " case sensitively" : " case insensitively");
  9229. }
  9230. } // namespace StdString
  9231. StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  9232. return StdString::EqualsMatcher( StdString::CasedString( str, caseSensitivity) );
  9233. }
  9234. StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  9235. return StdString::ContainsMatcher( StdString::CasedString( str, caseSensitivity) );
  9236. }
  9237. StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  9238. return StdString::EndsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  9239. }
  9240. StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  9241. return StdString::StartsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  9242. }
  9243. StdString::RegexMatcher Matches(std::string const& regex, CaseSensitive::Choice caseSensitivity) {
  9244. return StdString::RegexMatcher(regex, caseSensitivity);
  9245. }
  9246. } // namespace Matchers
  9247. } // namespace Catch
  9248. // end catch_matchers_string.cpp
  9249. // start catch_message.cpp
  9250. // start catch_uncaught_exceptions.h
  9251. namespace Catch {
  9252. bool uncaught_exceptions();
  9253. } // end namespace Catch
  9254. // end catch_uncaught_exceptions.h
  9255. #include <cassert>
  9256. #include <stack>
  9257. namespace Catch {
  9258. MessageInfo::MessageInfo( StringRef const& _macroName,
  9259. SourceLineInfo const& _lineInfo,
  9260. ResultWas::OfType _type )
  9261. : macroName( _macroName ),
  9262. lineInfo( _lineInfo ),
  9263. type( _type ),
  9264. sequence( ++globalCount )
  9265. {}
  9266. bool MessageInfo::operator==( MessageInfo const& other ) const {
  9267. return sequence == other.sequence;
  9268. }
  9269. bool MessageInfo::operator<( MessageInfo const& other ) const {
  9270. return sequence < other.sequence;
  9271. }
  9272. // This may need protecting if threading support is added
  9273. unsigned int MessageInfo::globalCount = 0;
  9274. ////////////////////////////////////////////////////////////////////////////
  9275. Catch::MessageBuilder::MessageBuilder( StringRef const& macroName,
  9276. SourceLineInfo const& lineInfo,
  9277. ResultWas::OfType type )
  9278. :m_info(macroName, lineInfo, type) {}
  9279. ////////////////////////////////////////////////////////////////////////////
  9280. ScopedMessage::ScopedMessage( MessageBuilder const& builder )
  9281. : m_info( builder.m_info ), m_moved()
  9282. {
  9283. m_info.message = builder.m_stream.str();
  9284. getResultCapture().pushScopedMessage( m_info );
  9285. }
  9286. ScopedMessage::ScopedMessage( ScopedMessage&& old )
  9287. : m_info( old.m_info ), m_moved()
  9288. {
  9289. old.m_moved = true;
  9290. }
  9291. ScopedMessage::~ScopedMessage() {
  9292. if ( !uncaught_exceptions() && !m_moved ){
  9293. getResultCapture().popScopedMessage(m_info);
  9294. }
  9295. }
  9296. Capturer::Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names ) {
  9297. auto trimmed = [&] (size_t start, size_t end) {
  9298. while (names[start] == ',' || isspace(names[start])) {
  9299. ++start;
  9300. }
  9301. while (names[end] == ',' || isspace(names[end])) {
  9302. --end;
  9303. }
  9304. return names.substr(start, end - start + 1);
  9305. };
  9306. auto skipq = [&] (size_t start, char quote) {
  9307. for (auto i = start + 1; i < names.size() ; ++i) {
  9308. if (names[i] == quote)
  9309. return i;
  9310. if (names[i] == '\\')
  9311. ++i;
  9312. }
  9313. CATCH_INTERNAL_ERROR("CAPTURE parsing encountered unmatched quote");
  9314. };
  9315. size_t start = 0;
  9316. std::stack<char> openings;
  9317. for (size_t pos = 0; pos < names.size(); ++pos) {
  9318. char c = names[pos];
  9319. switch (c) {
  9320. case '[':
  9321. case '{':
  9322. case '(':
  9323. // It is basically impossible to disambiguate between
  9324. // comparison and start of template args in this context
  9325. // case '<':
  9326. openings.push(c);
  9327. break;
  9328. case ']':
  9329. case '}':
  9330. case ')':
  9331. // case '>':
  9332. openings.pop();
  9333. break;
  9334. case '"':
  9335. case '\'':
  9336. pos = skipq(pos, c);
  9337. break;
  9338. case ',':
  9339. if (start != pos && openings.size() == 0) {
  9340. m_messages.emplace_back(macroName, lineInfo, resultType);
  9341. m_messages.back().message = trimmed(start, pos);
  9342. m_messages.back().message += " := ";
  9343. start = pos;
  9344. }
  9345. }
  9346. }
  9347. assert(openings.size() == 0 && "Mismatched openings");
  9348. m_messages.emplace_back(macroName, lineInfo, resultType);
  9349. m_messages.back().message = trimmed(start, names.size() - 1);
  9350. m_messages.back().message += " := ";
  9351. }
  9352. Capturer::~Capturer() {
  9353. if ( !uncaught_exceptions() ){
  9354. assert( m_captured == m_messages.size() );
  9355. for( size_t i = 0; i < m_captured; ++i )
  9356. m_resultCapture.popScopedMessage( m_messages[i] );
  9357. }
  9358. }
  9359. void Capturer::captureValue( size_t index, std::string const& value ) {
  9360. assert( index < m_messages.size() );
  9361. m_messages[index].message += value;
  9362. m_resultCapture.pushScopedMessage( m_messages[index] );
  9363. m_captured++;
  9364. }
  9365. } // end namespace Catch
  9366. // end catch_message.cpp
  9367. // start catch_output_redirect.cpp
  9368. // start catch_output_redirect.h
  9369. #ifndef TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  9370. #define TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  9371. #include <cstdio>
  9372. #include <iosfwd>
  9373. #include <string>
  9374. namespace Catch {
  9375. class RedirectedStream {
  9376. std::ostream& m_originalStream;
  9377. std::ostream& m_redirectionStream;
  9378. std::streambuf* m_prevBuf;
  9379. public:
  9380. RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream );
  9381. ~RedirectedStream();
  9382. };
  9383. class RedirectedStdOut {
  9384. ReusableStringStream m_rss;
  9385. RedirectedStream m_cout;
  9386. public:
  9387. RedirectedStdOut();
  9388. auto str() const -> std::string;
  9389. };
  9390. // StdErr has two constituent streams in C++, std::cerr and std::clog
  9391. // This means that we need to redirect 2 streams into 1 to keep proper
  9392. // order of writes
  9393. class RedirectedStdErr {
  9394. ReusableStringStream m_rss;
  9395. RedirectedStream m_cerr;
  9396. RedirectedStream m_clog;
  9397. public:
  9398. RedirectedStdErr();
  9399. auto str() const -> std::string;
  9400. };
  9401. class RedirectedStreams {
  9402. public:
  9403. RedirectedStreams(RedirectedStreams const&) = delete;
  9404. RedirectedStreams& operator=(RedirectedStreams const&) = delete;
  9405. RedirectedStreams(RedirectedStreams&&) = delete;
  9406. RedirectedStreams& operator=(RedirectedStreams&&) = delete;
  9407. RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr);
  9408. ~RedirectedStreams();
  9409. private:
  9410. std::string& m_redirectedCout;
  9411. std::string& m_redirectedCerr;
  9412. RedirectedStdOut m_redirectedStdOut;
  9413. RedirectedStdErr m_redirectedStdErr;
  9414. };
  9415. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  9416. // Windows's implementation of std::tmpfile is terrible (it tries
  9417. // to create a file inside system folder, thus requiring elevated
  9418. // privileges for the binary), so we have to use tmpnam(_s) and
  9419. // create the file ourselves there.
  9420. class TempFile {
  9421. public:
  9422. TempFile(TempFile const&) = delete;
  9423. TempFile& operator=(TempFile const&) = delete;
  9424. TempFile(TempFile&&) = delete;
  9425. TempFile& operator=(TempFile&&) = delete;
  9426. TempFile();
  9427. ~TempFile();
  9428. std::FILE* getFile();
  9429. std::string getContents();
  9430. private:
  9431. std::FILE* m_file = nullptr;
  9432. #if defined(_MSC_VER)
  9433. char m_buffer[L_tmpnam] = { 0 };
  9434. #endif
  9435. };
  9436. class OutputRedirect {
  9437. public:
  9438. OutputRedirect(OutputRedirect const&) = delete;
  9439. OutputRedirect& operator=(OutputRedirect const&) = delete;
  9440. OutputRedirect(OutputRedirect&&) = delete;
  9441. OutputRedirect& operator=(OutputRedirect&&) = delete;
  9442. OutputRedirect(std::string& stdout_dest, std::string& stderr_dest);
  9443. ~OutputRedirect();
  9444. private:
  9445. int m_originalStdout = -1;
  9446. int m_originalStderr = -1;
  9447. TempFile m_stdoutFile;
  9448. TempFile m_stderrFile;
  9449. std::string& m_stdoutDest;
  9450. std::string& m_stderrDest;
  9451. };
  9452. #endif
  9453. } // end namespace Catch
  9454. #endif // TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  9455. // end catch_output_redirect.h
  9456. #include <cstdio>
  9457. #include <cstring>
  9458. #include <fstream>
  9459. #include <sstream>
  9460. #include <stdexcept>
  9461. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  9462. #if defined(_MSC_VER)
  9463. #include <io.h> //_dup and _dup2
  9464. #define dup _dup
  9465. #define dup2 _dup2
  9466. #define fileno _fileno
  9467. #else
  9468. #include <unistd.h> // dup and dup2
  9469. #endif
  9470. #endif
  9471. namespace Catch {
  9472. RedirectedStream::RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream )
  9473. : m_originalStream( originalStream ),
  9474. m_redirectionStream( redirectionStream ),
  9475. m_prevBuf( m_originalStream.rdbuf() )
  9476. {
  9477. m_originalStream.rdbuf( m_redirectionStream.rdbuf() );
  9478. }
  9479. RedirectedStream::~RedirectedStream() {
  9480. m_originalStream.rdbuf( m_prevBuf );
  9481. }
  9482. RedirectedStdOut::RedirectedStdOut() : m_cout( Catch::cout(), m_rss.get() ) {}
  9483. auto RedirectedStdOut::str() const -> std::string { return m_rss.str(); }
  9484. RedirectedStdErr::RedirectedStdErr()
  9485. : m_cerr( Catch::cerr(), m_rss.get() ),
  9486. m_clog( Catch::clog(), m_rss.get() )
  9487. {}
  9488. auto RedirectedStdErr::str() const -> std::string { return m_rss.str(); }
  9489. RedirectedStreams::RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr)
  9490. : m_redirectedCout(redirectedCout),
  9491. m_redirectedCerr(redirectedCerr)
  9492. {}
  9493. RedirectedStreams::~RedirectedStreams() {
  9494. m_redirectedCout += m_redirectedStdOut.str();
  9495. m_redirectedCerr += m_redirectedStdErr.str();
  9496. }
  9497. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  9498. #if defined(_MSC_VER)
  9499. TempFile::TempFile() {
  9500. if (tmpnam_s(m_buffer)) {
  9501. CATCH_RUNTIME_ERROR("Could not get a temp filename");
  9502. }
  9503. if (fopen_s(&m_file, m_buffer, "w")) {
  9504. char buffer[100];
  9505. if (strerror_s(buffer, errno)) {
  9506. CATCH_RUNTIME_ERROR("Could not translate errno to a string");
  9507. }
  9508. CATCH_RUNTIME_ERROR("Could not open the temp file: '" << m_buffer << "' because: " << buffer);
  9509. }
  9510. }
  9511. #else
  9512. TempFile::TempFile() {
  9513. m_file = std::tmpfile();
  9514. if (!m_file) {
  9515. CATCH_RUNTIME_ERROR("Could not create a temp file.");
  9516. }
  9517. }
  9518. #endif
  9519. TempFile::~TempFile() {
  9520. // TBD: What to do about errors here?
  9521. std::fclose(m_file);
  9522. // We manually create the file on Windows only, on Linux
  9523. // it will be autodeleted
  9524. #if defined(_MSC_VER)
  9525. std::remove(m_buffer);
  9526. #endif
  9527. }
  9528. FILE* TempFile::getFile() {
  9529. return m_file;
  9530. }
  9531. std::string TempFile::getContents() {
  9532. std::stringstream sstr;
  9533. char buffer[100] = {};
  9534. std::rewind(m_file);
  9535. while (std::fgets(buffer, sizeof(buffer), m_file)) {
  9536. sstr << buffer;
  9537. }
  9538. return sstr.str();
  9539. }
  9540. OutputRedirect::OutputRedirect(std::string& stdout_dest, std::string& stderr_dest) :
  9541. m_originalStdout(dup(1)),
  9542. m_originalStderr(dup(2)),
  9543. m_stdoutDest(stdout_dest),
  9544. m_stderrDest(stderr_dest) {
  9545. dup2(fileno(m_stdoutFile.getFile()), 1);
  9546. dup2(fileno(m_stderrFile.getFile()), 2);
  9547. }
  9548. OutputRedirect::~OutputRedirect() {
  9549. Catch::cout() << std::flush;
  9550. fflush(stdout);
  9551. // Since we support overriding these streams, we flush cerr
  9552. // even though std::cerr is unbuffered
  9553. Catch::cerr() << std::flush;
  9554. Catch::clog() << std::flush;
  9555. fflush(stderr);
  9556. dup2(m_originalStdout, 1);
  9557. dup2(m_originalStderr, 2);
  9558. m_stdoutDest += m_stdoutFile.getContents();
  9559. m_stderrDest += m_stderrFile.getContents();
  9560. }
  9561. #endif // CATCH_CONFIG_NEW_CAPTURE
  9562. } // namespace Catch
  9563. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  9564. #if defined(_MSC_VER)
  9565. #undef dup
  9566. #undef dup2
  9567. #undef fileno
  9568. #endif
  9569. #endif
  9570. // end catch_output_redirect.cpp
  9571. // start catch_polyfills.cpp
  9572. #include <cmath>
  9573. namespace Catch {
  9574. #if !defined(CATCH_CONFIG_POLYFILL_ISNAN)
  9575. bool isnan(float f) {
  9576. return std::isnan(f);
  9577. }
  9578. bool isnan(double d) {
  9579. return std::isnan(d);
  9580. }
  9581. #else
  9582. // For now we only use this for embarcadero
  9583. bool isnan(float f) {
  9584. return std::_isnan(f);
  9585. }
  9586. bool isnan(double d) {
  9587. return std::_isnan(d);
  9588. }
  9589. #endif
  9590. } // end namespace Catch
  9591. // end catch_polyfills.cpp
  9592. // start catch_random_number_generator.cpp
  9593. namespace Catch {
  9594. std::mt19937& rng() {
  9595. static std::mt19937 s_rng;
  9596. return s_rng;
  9597. }
  9598. void seedRng( IConfig const& config ) {
  9599. if( config.rngSeed() != 0 ) {
  9600. std::srand( config.rngSeed() );
  9601. rng().seed( config.rngSeed() );
  9602. }
  9603. }
  9604. unsigned int rngSeed() {
  9605. return getCurrentContext().getConfig()->rngSeed();
  9606. }
  9607. }
  9608. // end catch_random_number_generator.cpp
  9609. // start catch_registry_hub.cpp
  9610. // start catch_test_case_registry_impl.h
  9611. #include <vector>
  9612. #include <set>
  9613. #include <algorithm>
  9614. #include <ios>
  9615. namespace Catch {
  9616. class TestCase;
  9617. struct IConfig;
  9618. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases );
  9619. bool isThrowSafe( TestCase const& testCase, IConfig const& config );
  9620. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
  9621. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions );
  9622. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
  9623. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
  9624. class TestRegistry : public ITestCaseRegistry {
  9625. public:
  9626. virtual ~TestRegistry() = default;
  9627. virtual void registerTest( TestCase const& testCase );
  9628. std::vector<TestCase> const& getAllTests() const override;
  9629. std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const override;
  9630. private:
  9631. std::vector<TestCase> m_functions;
  9632. mutable RunTests::InWhatOrder m_currentSortOrder = RunTests::InDeclarationOrder;
  9633. mutable std::vector<TestCase> m_sortedFunctions;
  9634. std::size_t m_unnamedCount = 0;
  9635. std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised
  9636. };
  9637. ///////////////////////////////////////////////////////////////////////////
  9638. class TestInvokerAsFunction : public ITestInvoker {
  9639. void(*m_testAsFunction)();
  9640. public:
  9641. TestInvokerAsFunction( void(*testAsFunction)() ) noexcept;
  9642. void invoke() const override;
  9643. };
  9644. std::string extractClassName( StringRef const& classOrQualifiedMethodName );
  9645. ///////////////////////////////////////////////////////////////////////////
  9646. } // end namespace Catch
  9647. // end catch_test_case_registry_impl.h
  9648. // start catch_reporter_registry.h
  9649. #include <map>
  9650. namespace Catch {
  9651. class ReporterRegistry : public IReporterRegistry {
  9652. public:
  9653. ~ReporterRegistry() override;
  9654. IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const override;
  9655. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory );
  9656. void registerListener( IReporterFactoryPtr const& factory );
  9657. FactoryMap const& getFactories() const override;
  9658. Listeners const& getListeners() const override;
  9659. private:
  9660. FactoryMap m_factories;
  9661. Listeners m_listeners;
  9662. };
  9663. }
  9664. // end catch_reporter_registry.h
  9665. // start catch_tag_alias_registry.h
  9666. // start catch_tag_alias.h
  9667. #include <string>
  9668. namespace Catch {
  9669. struct TagAlias {
  9670. TagAlias(std::string const& _tag, SourceLineInfo _lineInfo);
  9671. std::string tag;
  9672. SourceLineInfo lineInfo;
  9673. };
  9674. } // end namespace Catch
  9675. // end catch_tag_alias.h
  9676. #include <map>
  9677. namespace Catch {
  9678. class TagAliasRegistry : public ITagAliasRegistry {
  9679. public:
  9680. ~TagAliasRegistry() override;
  9681. TagAlias const* find( std::string const& alias ) const override;
  9682. std::string expandAliases( std::string const& unexpandedTestSpec ) const override;
  9683. void add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo );
  9684. private:
  9685. std::map<std::string, TagAlias> m_registry;
  9686. };
  9687. } // end namespace Catch
  9688. // end catch_tag_alias_registry.h
  9689. // start catch_startup_exception_registry.h
  9690. #include <vector>
  9691. #include <exception>
  9692. namespace Catch {
  9693. class StartupExceptionRegistry {
  9694. public:
  9695. void add(std::exception_ptr const& exception) noexcept;
  9696. std::vector<std::exception_ptr> const& getExceptions() const noexcept;
  9697. private:
  9698. std::vector<std::exception_ptr> m_exceptions;
  9699. };
  9700. } // end namespace Catch
  9701. // end catch_startup_exception_registry.h
  9702. // start catch_singletons.hpp
  9703. namespace Catch {
  9704. struct ISingleton {
  9705. virtual ~ISingleton();
  9706. };
  9707. void addSingleton( ISingleton* singleton );
  9708. void cleanupSingletons();
  9709. template<typename SingletonImplT, typename InterfaceT = SingletonImplT, typename MutableInterfaceT = InterfaceT>
  9710. class Singleton : SingletonImplT, public ISingleton {
  9711. static auto getInternal() -> Singleton* {
  9712. static Singleton* s_instance = nullptr;
  9713. if( !s_instance ) {
  9714. s_instance = new Singleton;
  9715. addSingleton( s_instance );
  9716. }
  9717. return s_instance;
  9718. }
  9719. public:
  9720. static auto get() -> InterfaceT const& {
  9721. return *getInternal();
  9722. }
  9723. static auto getMutable() -> MutableInterfaceT& {
  9724. return *getInternal();
  9725. }
  9726. };
  9727. } // namespace Catch
  9728. // end catch_singletons.hpp
  9729. namespace Catch {
  9730. namespace {
  9731. class RegistryHub : public IRegistryHub, public IMutableRegistryHub,
  9732. private NonCopyable {
  9733. public: // IRegistryHub
  9734. RegistryHub() = default;
  9735. IReporterRegistry const& getReporterRegistry() const override {
  9736. return m_reporterRegistry;
  9737. }
  9738. ITestCaseRegistry const& getTestCaseRegistry() const override {
  9739. return m_testCaseRegistry;
  9740. }
  9741. IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const override {
  9742. return m_exceptionTranslatorRegistry;
  9743. }
  9744. ITagAliasRegistry const& getTagAliasRegistry() const override {
  9745. return m_tagAliasRegistry;
  9746. }
  9747. StartupExceptionRegistry const& getStartupExceptionRegistry() const override {
  9748. return m_exceptionRegistry;
  9749. }
  9750. public: // IMutableRegistryHub
  9751. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) override {
  9752. m_reporterRegistry.registerReporter( name, factory );
  9753. }
  9754. void registerListener( IReporterFactoryPtr const& factory ) override {
  9755. m_reporterRegistry.registerListener( factory );
  9756. }
  9757. void registerTest( TestCase const& testInfo ) override {
  9758. m_testCaseRegistry.registerTest( testInfo );
  9759. }
  9760. void registerTranslator( const IExceptionTranslator* translator ) override {
  9761. m_exceptionTranslatorRegistry.registerTranslator( translator );
  9762. }
  9763. void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) override {
  9764. m_tagAliasRegistry.add( alias, tag, lineInfo );
  9765. }
  9766. void registerStartupException() noexcept override {
  9767. m_exceptionRegistry.add(std::current_exception());
  9768. }
  9769. IMutableEnumValuesRegistry& getMutableEnumValuesRegistry() override {
  9770. return m_enumValuesRegistry;
  9771. }
  9772. private:
  9773. TestRegistry m_testCaseRegistry;
  9774. ReporterRegistry m_reporterRegistry;
  9775. ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
  9776. TagAliasRegistry m_tagAliasRegistry;
  9777. StartupExceptionRegistry m_exceptionRegistry;
  9778. Detail::EnumValuesRegistry m_enumValuesRegistry;
  9779. };
  9780. }
  9781. using RegistryHubSingleton = Singleton<RegistryHub, IRegistryHub, IMutableRegistryHub>;
  9782. IRegistryHub const& getRegistryHub() {
  9783. return RegistryHubSingleton::get();
  9784. }
  9785. IMutableRegistryHub& getMutableRegistryHub() {
  9786. return RegistryHubSingleton::getMutable();
  9787. }
  9788. void cleanUp() {
  9789. cleanupSingletons();
  9790. cleanUpContext();
  9791. }
  9792. std::string translateActiveException() {
  9793. return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException();
  9794. }
  9795. } // end namespace Catch
  9796. // end catch_registry_hub.cpp
  9797. // start catch_reporter_registry.cpp
  9798. namespace Catch {
  9799. ReporterRegistry::~ReporterRegistry() = default;
  9800. IStreamingReporterPtr ReporterRegistry::create( std::string const& name, IConfigPtr const& config ) const {
  9801. auto it = m_factories.find( name );
  9802. if( it == m_factories.end() )
  9803. return nullptr;
  9804. return it->second->create( ReporterConfig( config ) );
  9805. }
  9806. void ReporterRegistry::registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) {
  9807. m_factories.emplace(name, factory);
  9808. }
  9809. void ReporterRegistry::registerListener( IReporterFactoryPtr const& factory ) {
  9810. m_listeners.push_back( factory );
  9811. }
  9812. IReporterRegistry::FactoryMap const& ReporterRegistry::getFactories() const {
  9813. return m_factories;
  9814. }
  9815. IReporterRegistry::Listeners const& ReporterRegistry::getListeners() const {
  9816. return m_listeners;
  9817. }
  9818. }
  9819. // end catch_reporter_registry.cpp
  9820. // start catch_result_type.cpp
  9821. namespace Catch {
  9822. bool isOk( ResultWas::OfType resultType ) {
  9823. return ( resultType & ResultWas::FailureBit ) == 0;
  9824. }
  9825. bool isJustInfo( int flags ) {
  9826. return flags == ResultWas::Info;
  9827. }
  9828. ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) {
  9829. return static_cast<ResultDisposition::Flags>( static_cast<int>( lhs ) | static_cast<int>( rhs ) );
  9830. }
  9831. bool shouldContinueOnFailure( int flags ) { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; }
  9832. bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; }
  9833. } // end namespace Catch
  9834. // end catch_result_type.cpp
  9835. // start catch_run_context.cpp
  9836. #include <cassert>
  9837. #include <algorithm>
  9838. #include <sstream>
  9839. namespace Catch {
  9840. namespace Generators {
  9841. struct GeneratorTracker : TestCaseTracking::TrackerBase, IGeneratorTracker {
  9842. GeneratorBasePtr m_generator;
  9843. GeneratorTracker( TestCaseTracking::NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  9844. : TrackerBase( nameAndLocation, ctx, parent )
  9845. {}
  9846. ~GeneratorTracker();
  9847. static GeneratorTracker& acquire( TrackerContext& ctx, TestCaseTracking::NameAndLocation const& nameAndLocation ) {
  9848. std::shared_ptr<GeneratorTracker> tracker;
  9849. ITracker& currentTracker = ctx.currentTracker();
  9850. if( TestCaseTracking::ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  9851. assert( childTracker );
  9852. assert( childTracker->isGeneratorTracker() );
  9853. tracker = std::static_pointer_cast<GeneratorTracker>( childTracker );
  9854. }
  9855. else {
  9856. tracker = std::make_shared<GeneratorTracker>( nameAndLocation, ctx, &currentTracker );
  9857. currentTracker.addChild( tracker );
  9858. }
  9859. if( !ctx.completedCycle() && !tracker->isComplete() ) {
  9860. tracker->open();
  9861. }
  9862. return *tracker;
  9863. }
  9864. // TrackerBase interface
  9865. bool isGeneratorTracker() const override { return true; }
  9866. auto hasGenerator() const -> bool override {
  9867. return !!m_generator;
  9868. }
  9869. void close() override {
  9870. TrackerBase::close();
  9871. // Generator interface only finds out if it has another item on atual move
  9872. if (m_runState == CompletedSuccessfully && m_generator->next()) {
  9873. m_children.clear();
  9874. m_runState = Executing;
  9875. }
  9876. }
  9877. // IGeneratorTracker interface
  9878. auto getGenerator() const -> GeneratorBasePtr const& override {
  9879. return m_generator;
  9880. }
  9881. void setGenerator( GeneratorBasePtr&& generator ) override {
  9882. m_generator = std::move( generator );
  9883. }
  9884. };
  9885. GeneratorTracker::~GeneratorTracker() {}
  9886. }
  9887. RunContext::RunContext(IConfigPtr const& _config, IStreamingReporterPtr&& reporter)
  9888. : m_runInfo(_config->name()),
  9889. m_context(getCurrentMutableContext()),
  9890. m_config(_config),
  9891. m_reporter(std::move(reporter)),
  9892. m_lastAssertionInfo{ StringRef(), SourceLineInfo("",0), StringRef(), ResultDisposition::Normal },
  9893. m_includeSuccessfulResults( m_config->includeSuccessfulResults() || m_reporter->getPreferences().shouldReportAllAssertions )
  9894. {
  9895. m_context.setRunner(this);
  9896. m_context.setConfig(m_config);
  9897. m_context.setResultCapture(this);
  9898. m_reporter->testRunStarting(m_runInfo);
  9899. }
  9900. RunContext::~RunContext() {
  9901. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting()));
  9902. }
  9903. void RunContext::testGroupStarting(std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount) {
  9904. m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount));
  9905. }
  9906. void RunContext::testGroupEnded(std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount) {
  9907. m_reporter->testGroupEnded(TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting()));
  9908. }
  9909. Totals RunContext::runTest(TestCase const& testCase) {
  9910. Totals prevTotals = m_totals;
  9911. std::string redirectedCout;
  9912. std::string redirectedCerr;
  9913. auto const& testInfo = testCase.getTestCaseInfo();
  9914. m_reporter->testCaseStarting(testInfo);
  9915. m_activeTestCase = &testCase;
  9916. ITracker& rootTracker = m_trackerContext.startRun();
  9917. assert(rootTracker.isSectionTracker());
  9918. static_cast<SectionTracker&>(rootTracker).addInitialFilters(m_config->getSectionsToRun());
  9919. do {
  9920. m_trackerContext.startCycle();
  9921. m_testCaseTracker = &SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo));
  9922. runCurrentTest(redirectedCout, redirectedCerr);
  9923. } while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting());
  9924. Totals deltaTotals = m_totals.delta(prevTotals);
  9925. if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) {
  9926. deltaTotals.assertions.failed++;
  9927. deltaTotals.testCases.passed--;
  9928. deltaTotals.testCases.failed++;
  9929. }
  9930. m_totals.testCases += deltaTotals.testCases;
  9931. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  9932. deltaTotals,
  9933. redirectedCout,
  9934. redirectedCerr,
  9935. aborting()));
  9936. m_activeTestCase = nullptr;
  9937. m_testCaseTracker = nullptr;
  9938. return deltaTotals;
  9939. }
  9940. IConfigPtr RunContext::config() const {
  9941. return m_config;
  9942. }
  9943. IStreamingReporter& RunContext::reporter() const {
  9944. return *m_reporter;
  9945. }
  9946. void RunContext::assertionEnded(AssertionResult const & result) {
  9947. if (result.getResultType() == ResultWas::Ok) {
  9948. m_totals.assertions.passed++;
  9949. m_lastAssertionPassed = true;
  9950. } else if (!result.isOk()) {
  9951. m_lastAssertionPassed = false;
  9952. if( m_activeTestCase->getTestCaseInfo().okToFail() )
  9953. m_totals.assertions.failedButOk++;
  9954. else
  9955. m_totals.assertions.failed++;
  9956. }
  9957. else {
  9958. m_lastAssertionPassed = true;
  9959. }
  9960. // We have no use for the return value (whether messages should be cleared), because messages were made scoped
  9961. // and should be let to clear themselves out.
  9962. static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals)));
  9963. if (result.getResultType() != ResultWas::Warning)
  9964. m_messageScopes.clear();
  9965. // Reset working state
  9966. resetAssertionInfo();
  9967. m_lastResult = result;
  9968. }
  9969. void RunContext::resetAssertionInfo() {
  9970. m_lastAssertionInfo.macroName = StringRef();
  9971. m_lastAssertionInfo.capturedExpression = "{Unknown expression after the reported line}"_sr;
  9972. }
  9973. bool RunContext::sectionStarted(SectionInfo const & sectionInfo, Counts & assertions) {
  9974. ITracker& sectionTracker = SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(sectionInfo.name, sectionInfo.lineInfo));
  9975. if (!sectionTracker.isOpen())
  9976. return false;
  9977. m_activeSections.push_back(&sectionTracker);
  9978. m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;
  9979. m_reporter->sectionStarting(sectionInfo);
  9980. assertions = m_totals.assertions;
  9981. return true;
  9982. }
  9983. auto RunContext::acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
  9984. using namespace Generators;
  9985. GeneratorTracker& tracker = GeneratorTracker::acquire( m_trackerContext, TestCaseTracking::NameAndLocation( "generator", lineInfo ) );
  9986. assert( tracker.isOpen() );
  9987. m_lastAssertionInfo.lineInfo = lineInfo;
  9988. return tracker;
  9989. }
  9990. bool RunContext::testForMissingAssertions(Counts& assertions) {
  9991. if (assertions.total() != 0)
  9992. return false;
  9993. if (!m_config->warnAboutMissingAssertions())
  9994. return false;
  9995. if (m_trackerContext.currentTracker().hasChildren())
  9996. return false;
  9997. m_totals.assertions.failed++;
  9998. assertions.failed++;
  9999. return true;
  10000. }
  10001. void RunContext::sectionEnded(SectionEndInfo const & endInfo) {
  10002. Counts assertions = m_totals.assertions - endInfo.prevAssertions;
  10003. bool missingAssertions = testForMissingAssertions(assertions);
  10004. if (!m_activeSections.empty()) {
  10005. m_activeSections.back()->close();
  10006. m_activeSections.pop_back();
  10007. }
  10008. m_reporter->sectionEnded(SectionStats(endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions));
  10009. m_messages.clear();
  10010. m_messageScopes.clear();
  10011. }
  10012. void RunContext::sectionEndedEarly(SectionEndInfo const & endInfo) {
  10013. if (m_unfinishedSections.empty())
  10014. m_activeSections.back()->fail();
  10015. else
  10016. m_activeSections.back()->close();
  10017. m_activeSections.pop_back();
  10018. m_unfinishedSections.push_back(endInfo);
  10019. }
  10020. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  10021. void RunContext::benchmarkPreparing(std::string const& name) {
  10022. m_reporter->benchmarkPreparing(name);
  10023. }
  10024. void RunContext::benchmarkStarting( BenchmarkInfo const& info ) {
  10025. m_reporter->benchmarkStarting( info );
  10026. }
  10027. void RunContext::benchmarkEnded( BenchmarkStats<> const& stats ) {
  10028. m_reporter->benchmarkEnded( stats );
  10029. }
  10030. void RunContext::benchmarkFailed(std::string const & error) {
  10031. m_reporter->benchmarkFailed(error);
  10032. }
  10033. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  10034. void RunContext::pushScopedMessage(MessageInfo const & message) {
  10035. m_messages.push_back(message);
  10036. }
  10037. void RunContext::popScopedMessage(MessageInfo const & message) {
  10038. m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end());
  10039. }
  10040. void RunContext::emplaceUnscopedMessage( MessageBuilder const& builder ) {
  10041. m_messageScopes.emplace_back( builder );
  10042. }
  10043. std::string RunContext::getCurrentTestName() const {
  10044. return m_activeTestCase
  10045. ? m_activeTestCase->getTestCaseInfo().name
  10046. : std::string();
  10047. }
  10048. const AssertionResult * RunContext::getLastResult() const {
  10049. return &(*m_lastResult);
  10050. }
  10051. void RunContext::exceptionEarlyReported() {
  10052. m_shouldReportUnexpected = false;
  10053. }
  10054. void RunContext::handleFatalErrorCondition( StringRef message ) {
  10055. // First notify reporter that bad things happened
  10056. m_reporter->fatalErrorEncountered(message);
  10057. // Don't rebuild the result -- the stringification itself can cause more fatal errors
  10058. // Instead, fake a result data.
  10059. AssertionResultData tempResult( ResultWas::FatalErrorCondition, { false } );
  10060. tempResult.message = message;
  10061. AssertionResult result(m_lastAssertionInfo, tempResult);
  10062. assertionEnded(result);
  10063. handleUnfinishedSections();
  10064. // Recreate section for test case (as we will lose the one that was in scope)
  10065. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  10066. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
  10067. Counts assertions;
  10068. assertions.failed = 1;
  10069. SectionStats testCaseSectionStats(testCaseSection, assertions, 0, false);
  10070. m_reporter->sectionEnded(testCaseSectionStats);
  10071. auto const& testInfo = m_activeTestCase->getTestCaseInfo();
  10072. Totals deltaTotals;
  10073. deltaTotals.testCases.failed = 1;
  10074. deltaTotals.assertions.failed = 1;
  10075. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  10076. deltaTotals,
  10077. std::string(),
  10078. std::string(),
  10079. false));
  10080. m_totals.testCases.failed++;
  10081. testGroupEnded(std::string(), m_totals, 1, 1);
  10082. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, false));
  10083. }
  10084. bool RunContext::lastAssertionPassed() {
  10085. return m_lastAssertionPassed;
  10086. }
  10087. void RunContext::assertionPassed() {
  10088. m_lastAssertionPassed = true;
  10089. ++m_totals.assertions.passed;
  10090. resetAssertionInfo();
  10091. m_messageScopes.clear();
  10092. }
  10093. bool RunContext::aborting() const {
  10094. return m_totals.assertions.failed >= static_cast<std::size_t>(m_config->abortAfter());
  10095. }
  10096. void RunContext::runCurrentTest(std::string & redirectedCout, std::string & redirectedCerr) {
  10097. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  10098. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
  10099. m_reporter->sectionStarting(testCaseSection);
  10100. Counts prevAssertions = m_totals.assertions;
  10101. double duration = 0;
  10102. m_shouldReportUnexpected = true;
  10103. m_lastAssertionInfo = { "TEST_CASE"_sr, testCaseInfo.lineInfo, StringRef(), ResultDisposition::Normal };
  10104. seedRng(*m_config);
  10105. Timer timer;
  10106. CATCH_TRY {
  10107. if (m_reporter->getPreferences().shouldRedirectStdOut) {
  10108. #if !defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
  10109. RedirectedStreams redirectedStreams(redirectedCout, redirectedCerr);
  10110. timer.start();
  10111. invokeActiveTestCase();
  10112. #else
  10113. OutputRedirect r(redirectedCout, redirectedCerr);
  10114. timer.start();
  10115. invokeActiveTestCase();
  10116. #endif
  10117. } else {
  10118. timer.start();
  10119. invokeActiveTestCase();
  10120. }
  10121. duration = timer.getElapsedSeconds();
  10122. } CATCH_CATCH_ANON (TestFailureException&) {
  10123. // This just means the test was aborted due to failure
  10124. } CATCH_CATCH_ALL {
  10125. // Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under REQUIRE assertions
  10126. // are reported without translation at the point of origin.
  10127. if( m_shouldReportUnexpected ) {
  10128. AssertionReaction dummyReaction;
  10129. handleUnexpectedInflightException( m_lastAssertionInfo, translateActiveException(), dummyReaction );
  10130. }
  10131. }
  10132. Counts assertions = m_totals.assertions - prevAssertions;
  10133. bool missingAssertions = testForMissingAssertions(assertions);
  10134. m_testCaseTracker->close();
  10135. handleUnfinishedSections();
  10136. m_messages.clear();
  10137. m_messageScopes.clear();
  10138. SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions);
  10139. m_reporter->sectionEnded(testCaseSectionStats);
  10140. }
  10141. void RunContext::invokeActiveTestCase() {
  10142. FatalConditionHandler fatalConditionHandler; // Handle signals
  10143. m_activeTestCase->invoke();
  10144. fatalConditionHandler.reset();
  10145. }
  10146. void RunContext::handleUnfinishedSections() {
  10147. // If sections ended prematurely due to an exception we stored their
  10148. // infos here so we can tear them down outside the unwind process.
  10149. for (auto it = m_unfinishedSections.rbegin(),
  10150. itEnd = m_unfinishedSections.rend();
  10151. it != itEnd;
  10152. ++it)
  10153. sectionEnded(*it);
  10154. m_unfinishedSections.clear();
  10155. }
  10156. void RunContext::handleExpr(
  10157. AssertionInfo const& info,
  10158. ITransientExpression const& expr,
  10159. AssertionReaction& reaction
  10160. ) {
  10161. m_reporter->assertionStarting( info );
  10162. bool negated = isFalseTest( info.resultDisposition );
  10163. bool result = expr.getResult() != negated;
  10164. if( result ) {
  10165. if (!m_includeSuccessfulResults) {
  10166. assertionPassed();
  10167. }
  10168. else {
  10169. reportExpr(info, ResultWas::Ok, &expr, negated);
  10170. }
  10171. }
  10172. else {
  10173. reportExpr(info, ResultWas::ExpressionFailed, &expr, negated );
  10174. populateReaction( reaction );
  10175. }
  10176. }
  10177. void RunContext::reportExpr(
  10178. AssertionInfo const &info,
  10179. ResultWas::OfType resultType,
  10180. ITransientExpression const *expr,
  10181. bool negated ) {
  10182. m_lastAssertionInfo = info;
  10183. AssertionResultData data( resultType, LazyExpression( negated ) );
  10184. AssertionResult assertionResult{ info, data };
  10185. assertionResult.m_resultData.lazyExpression.m_transientExpression = expr;
  10186. assertionEnded( assertionResult );
  10187. }
  10188. void RunContext::handleMessage(
  10189. AssertionInfo const& info,
  10190. ResultWas::OfType resultType,
  10191. StringRef const& message,
  10192. AssertionReaction& reaction
  10193. ) {
  10194. m_reporter->assertionStarting( info );
  10195. m_lastAssertionInfo = info;
  10196. AssertionResultData data( resultType, LazyExpression( false ) );
  10197. data.message = message;
  10198. AssertionResult assertionResult{ m_lastAssertionInfo, data };
  10199. assertionEnded( assertionResult );
  10200. if( !assertionResult.isOk() )
  10201. populateReaction( reaction );
  10202. }
  10203. void RunContext::handleUnexpectedExceptionNotThrown(
  10204. AssertionInfo const& info,
  10205. AssertionReaction& reaction
  10206. ) {
  10207. handleNonExpr(info, Catch::ResultWas::DidntThrowException, reaction);
  10208. }
  10209. void RunContext::handleUnexpectedInflightException(
  10210. AssertionInfo const& info,
  10211. std::string const& message,
  10212. AssertionReaction& reaction
  10213. ) {
  10214. m_lastAssertionInfo = info;
  10215. AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
  10216. data.message = message;
  10217. AssertionResult assertionResult{ info, data };
  10218. assertionEnded( assertionResult );
  10219. populateReaction( reaction );
  10220. }
  10221. void RunContext::populateReaction( AssertionReaction& reaction ) {
  10222. reaction.shouldDebugBreak = m_config->shouldDebugBreak();
  10223. reaction.shouldThrow = aborting() || (m_lastAssertionInfo.resultDisposition & ResultDisposition::Normal);
  10224. }
  10225. void RunContext::handleIncomplete(
  10226. AssertionInfo const& info
  10227. ) {
  10228. m_lastAssertionInfo = info;
  10229. AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
  10230. data.message = "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE";
  10231. AssertionResult assertionResult{ info, data };
  10232. assertionEnded( assertionResult );
  10233. }
  10234. void RunContext::handleNonExpr(
  10235. AssertionInfo const &info,
  10236. ResultWas::OfType resultType,
  10237. AssertionReaction &reaction
  10238. ) {
  10239. m_lastAssertionInfo = info;
  10240. AssertionResultData data( resultType, LazyExpression( false ) );
  10241. AssertionResult assertionResult{ info, data };
  10242. assertionEnded( assertionResult );
  10243. if( !assertionResult.isOk() )
  10244. populateReaction( reaction );
  10245. }
  10246. IResultCapture& getResultCapture() {
  10247. if (auto* capture = getCurrentContext().getResultCapture())
  10248. return *capture;
  10249. else
  10250. CATCH_INTERNAL_ERROR("No result capture instance");
  10251. }
  10252. }
  10253. // end catch_run_context.cpp
  10254. // start catch_section.cpp
  10255. namespace Catch {
  10256. Section::Section( SectionInfo const& info )
  10257. : m_info( info ),
  10258. m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) )
  10259. {
  10260. m_timer.start();
  10261. }
  10262. Section::~Section() {
  10263. if( m_sectionIncluded ) {
  10264. SectionEndInfo endInfo{ m_info, m_assertions, m_timer.getElapsedSeconds() };
  10265. if( uncaught_exceptions() )
  10266. getResultCapture().sectionEndedEarly( endInfo );
  10267. else
  10268. getResultCapture().sectionEnded( endInfo );
  10269. }
  10270. }
  10271. // This indicates whether the section should be executed or not
  10272. Section::operator bool() const {
  10273. return m_sectionIncluded;
  10274. }
  10275. } // end namespace Catch
  10276. // end catch_section.cpp
  10277. // start catch_section_info.cpp
  10278. namespace Catch {
  10279. SectionInfo::SectionInfo
  10280. ( SourceLineInfo const& _lineInfo,
  10281. std::string const& _name )
  10282. : name( _name ),
  10283. lineInfo( _lineInfo )
  10284. {}
  10285. } // end namespace Catch
  10286. // end catch_section_info.cpp
  10287. // start catch_session.cpp
  10288. // start catch_session.h
  10289. #include <memory>
  10290. namespace Catch {
  10291. class Session : NonCopyable {
  10292. public:
  10293. Session();
  10294. ~Session() override;
  10295. void showHelp() const;
  10296. void libIdentify();
  10297. int applyCommandLine( int argc, char const * const * argv );
  10298. #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)
  10299. int applyCommandLine( int argc, wchar_t const * const * argv );
  10300. #endif
  10301. void useConfigData( ConfigData const& configData );
  10302. template<typename CharT>
  10303. int run(int argc, CharT const * const argv[]) {
  10304. if (m_startupExceptions)
  10305. return 1;
  10306. int returnCode = applyCommandLine(argc, argv);
  10307. if (returnCode == 0)
  10308. returnCode = run();
  10309. return returnCode;
  10310. }
  10311. int run();
  10312. clara::Parser const& cli() const;
  10313. void cli( clara::Parser const& newParser );
  10314. ConfigData& configData();
  10315. Config& config();
  10316. private:
  10317. int runInternal();
  10318. clara::Parser m_cli;
  10319. ConfigData m_configData;
  10320. std::shared_ptr<Config> m_config;
  10321. bool m_startupExceptions = false;
  10322. };
  10323. } // end namespace Catch
  10324. // end catch_session.h
  10325. // start catch_version.h
  10326. #include <iosfwd>
  10327. namespace Catch {
  10328. // Versioning information
  10329. struct Version {
  10330. Version( Version const& ) = delete;
  10331. Version& operator=( Version const& ) = delete;
  10332. Version( unsigned int _majorVersion,
  10333. unsigned int _minorVersion,
  10334. unsigned int _patchNumber,
  10335. char const * const _branchName,
  10336. unsigned int _buildNumber );
  10337. unsigned int const majorVersion;
  10338. unsigned int const minorVersion;
  10339. unsigned int const patchNumber;
  10340. // buildNumber is only used if branchName is not null
  10341. char const * const branchName;
  10342. unsigned int const buildNumber;
  10343. friend std::ostream& operator << ( std::ostream& os, Version const& version );
  10344. };
  10345. Version const& libraryVersion();
  10346. }
  10347. // end catch_version.h
  10348. #include <cstdlib>
  10349. #include <iomanip>
  10350. #include <set>
  10351. #include <iterator>
  10352. namespace Catch {
  10353. namespace {
  10354. const int MaxExitCode = 255;
  10355. IStreamingReporterPtr createReporter(std::string const& reporterName, IConfigPtr const& config) {
  10356. auto reporter = Catch::getRegistryHub().getReporterRegistry().create(reporterName, config);
  10357. CATCH_ENFORCE(reporter, "No reporter registered with name: '" << reporterName << "'");
  10358. return reporter;
  10359. }
  10360. IStreamingReporterPtr makeReporter(std::shared_ptr<Config> const& config) {
  10361. if (Catch::getRegistryHub().getReporterRegistry().getListeners().empty()) {
  10362. return createReporter(config->getReporterName(), config);
  10363. }
  10364. // On older platforms, returning std::unique_ptr<ListeningReporter>
  10365. // when the return type is std::unique_ptr<IStreamingReporter>
  10366. // doesn't compile without a std::move call. However, this causes
  10367. // a warning on newer platforms. Thus, we have to work around
  10368. // it a bit and downcast the pointer manually.
  10369. auto ret = std::unique_ptr<IStreamingReporter>(new ListeningReporter);
  10370. auto& multi = static_cast<ListeningReporter&>(*ret);
  10371. auto const& listeners = Catch::getRegistryHub().getReporterRegistry().getListeners();
  10372. for (auto const& listener : listeners) {
  10373. multi.addListener(listener->create(Catch::ReporterConfig(config)));
  10374. }
  10375. multi.addReporter(createReporter(config->getReporterName(), config));
  10376. return ret;
  10377. }
  10378. class TestGroup {
  10379. public:
  10380. explicit TestGroup(std::shared_ptr<Config> const& config)
  10381. : m_config{config}
  10382. , m_context{config, makeReporter(config)}
  10383. {
  10384. auto const& allTestCases = getAllTestCasesSorted(*m_config);
  10385. m_matches = m_config->testSpec().matchesByFilter(allTestCases, *m_config);
  10386. if (m_matches.empty()) {
  10387. for (auto const& test : allTestCases)
  10388. if (!test.isHidden())
  10389. m_tests.emplace(&test);
  10390. } else {
  10391. for (auto const& match : m_matches)
  10392. m_tests.insert(match.tests.begin(), match.tests.end());
  10393. }
  10394. }
  10395. Totals execute() {
  10396. Totals totals;
  10397. m_context.testGroupStarting(m_config->name(), 1, 1);
  10398. for (auto const& testCase : m_tests) {
  10399. if (!m_context.aborting())
  10400. totals += m_context.runTest(*testCase);
  10401. else
  10402. m_context.reporter().skipTest(*testCase);
  10403. }
  10404. for (auto const& match : m_matches) {
  10405. if (match.tests.empty()) {
  10406. m_context.reporter().noMatchingTestCases(match.name);
  10407. totals.error = -1;
  10408. }
  10409. }
  10410. m_context.testGroupEnded(m_config->name(), totals, 1, 1);
  10411. return totals;
  10412. }
  10413. private:
  10414. using Tests = std::set<TestCase const*>;
  10415. std::shared_ptr<Config> m_config;
  10416. RunContext m_context;
  10417. Tests m_tests;
  10418. TestSpec::Matches m_matches;
  10419. };
  10420. void applyFilenamesAsTags(Catch::IConfig const& config) {
  10421. auto& tests = const_cast<std::vector<TestCase>&>(getAllTestCasesSorted(config));
  10422. for (auto& testCase : tests) {
  10423. auto tags = testCase.tags;
  10424. std::string filename = testCase.lineInfo.file;
  10425. auto lastSlash = filename.find_last_of("\\/");
  10426. if (lastSlash != std::string::npos) {
  10427. filename.erase(0, lastSlash);
  10428. filename[0] = '#';
  10429. }
  10430. auto lastDot = filename.find_last_of('.');
  10431. if (lastDot != std::string::npos) {
  10432. filename.erase(lastDot);
  10433. }
  10434. tags.push_back(std::move(filename));
  10435. setTags(testCase, tags);
  10436. }
  10437. }
  10438. } // anon namespace
  10439. Session::Session() {
  10440. static bool alreadyInstantiated = false;
  10441. if( alreadyInstantiated ) {
  10442. CATCH_TRY { CATCH_INTERNAL_ERROR( "Only one instance of Catch::Session can ever be used" ); }
  10443. CATCH_CATCH_ALL { getMutableRegistryHub().registerStartupException(); }
  10444. }
  10445. // There cannot be exceptions at startup in no-exception mode.
  10446. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  10447. const auto& exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions();
  10448. if ( !exceptions.empty() ) {
  10449. config();
  10450. getCurrentMutableContext().setConfig(m_config);
  10451. m_startupExceptions = true;
  10452. Colour colourGuard( Colour::Red );
  10453. Catch::cerr() << "Errors occurred during startup!" << '\n';
  10454. // iterate over all exceptions and notify user
  10455. for ( const auto& ex_ptr : exceptions ) {
  10456. try {
  10457. std::rethrow_exception(ex_ptr);
  10458. } catch ( std::exception const& ex ) {
  10459. Catch::cerr() << Column( ex.what() ).indent(2) << '\n';
  10460. }
  10461. }
  10462. }
  10463. #endif
  10464. alreadyInstantiated = true;
  10465. m_cli = makeCommandLineParser( m_configData );
  10466. }
  10467. Session::~Session() {
  10468. Catch::cleanUp();
  10469. }
  10470. void Session::showHelp() const {
  10471. Catch::cout()
  10472. << "\nCatch v" << libraryVersion() << "\n"
  10473. << m_cli << std::endl
  10474. << "For more detailed usage please see the project docs\n" << std::endl;
  10475. }
  10476. void Session::libIdentify() {
  10477. Catch::cout()
  10478. << std::left << std::setw(16) << "description: " << "A Catch test executable\n"
  10479. << std::left << std::setw(16) << "category: " << "testframework\n"
  10480. << std::left << std::setw(16) << "framework: " << "Catch Test\n"
  10481. << std::left << std::setw(16) << "version: " << libraryVersion() << std::endl;
  10482. }
  10483. int Session::applyCommandLine( int argc, char const * const * argv ) {
  10484. if( m_startupExceptions )
  10485. return 1;
  10486. auto result = m_cli.parse( clara::Args( argc, argv ) );
  10487. if( !result ) {
  10488. config();
  10489. getCurrentMutableContext().setConfig(m_config);
  10490. Catch::cerr()
  10491. << Colour( Colour::Red )
  10492. << "\nError(s) in input:\n"
  10493. << Column( result.errorMessage() ).indent( 2 )
  10494. << "\n\n";
  10495. Catch::cerr() << "Run with -? for usage\n" << std::endl;
  10496. return MaxExitCode;
  10497. }
  10498. if( m_configData.showHelp )
  10499. showHelp();
  10500. if( m_configData.libIdentify )
  10501. libIdentify();
  10502. m_config.reset();
  10503. return 0;
  10504. }
  10505. #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)
  10506. int Session::applyCommandLine( int argc, wchar_t const * const * argv ) {
  10507. char **utf8Argv = new char *[ argc ];
  10508. for ( int i = 0; i < argc; ++i ) {
  10509. int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, NULL, 0, NULL, NULL );
  10510. utf8Argv[ i ] = new char[ bufSize ];
  10511. WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, NULL, NULL );
  10512. }
  10513. int returnCode = applyCommandLine( argc, utf8Argv );
  10514. for ( int i = 0; i < argc; ++i )
  10515. delete [] utf8Argv[ i ];
  10516. delete [] utf8Argv;
  10517. return returnCode;
  10518. }
  10519. #endif
  10520. void Session::useConfigData( ConfigData const& configData ) {
  10521. m_configData = configData;
  10522. m_config.reset();
  10523. }
  10524. int Session::run() {
  10525. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeStart ) != 0 ) {
  10526. Catch::cout() << "...waiting for enter/ return before starting" << std::endl;
  10527. static_cast<void>(std::getchar());
  10528. }
  10529. int exitCode = runInternal();
  10530. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeExit ) != 0 ) {
  10531. Catch::cout() << "...waiting for enter/ return before exiting, with code: " << exitCode << std::endl;
  10532. static_cast<void>(std::getchar());
  10533. }
  10534. return exitCode;
  10535. }
  10536. clara::Parser const& Session::cli() const {
  10537. return m_cli;
  10538. }
  10539. void Session::cli( clara::Parser const& newParser ) {
  10540. m_cli = newParser;
  10541. }
  10542. ConfigData& Session::configData() {
  10543. return m_configData;
  10544. }
  10545. Config& Session::config() {
  10546. if( !m_config )
  10547. m_config = std::make_shared<Config>( m_configData );
  10548. return *m_config;
  10549. }
  10550. int Session::runInternal() {
  10551. if( m_startupExceptions )
  10552. return 1;
  10553. if (m_configData.showHelp || m_configData.libIdentify) {
  10554. return 0;
  10555. }
  10556. CATCH_TRY {
  10557. config(); // Force config to be constructed
  10558. seedRng( *m_config );
  10559. if( m_configData.filenamesAsTags )
  10560. applyFilenamesAsTags( *m_config );
  10561. // Handle list request
  10562. if( Option<std::size_t> listed = list( m_config ) )
  10563. return static_cast<int>( *listed );
  10564. TestGroup tests { m_config };
  10565. auto const totals = tests.execute();
  10566. if( m_config->warnAboutNoTests() && totals.error == -1 )
  10567. return 2;
  10568. // Note that on unices only the lower 8 bits are usually used, clamping
  10569. // the return value to 255 prevents false negative when some multiple
  10570. // of 256 tests has failed
  10571. return (std::min) (MaxExitCode, (std::max) (totals.error, static_cast<int>(totals.assertions.failed)));
  10572. }
  10573. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  10574. catch( std::exception& ex ) {
  10575. Catch::cerr() << ex.what() << std::endl;
  10576. return MaxExitCode;
  10577. }
  10578. #endif
  10579. }
  10580. } // end namespace Catch
  10581. // end catch_session.cpp
  10582. // start catch_singletons.cpp
  10583. #include <vector>
  10584. namespace Catch {
  10585. namespace {
  10586. static auto getSingletons() -> std::vector<ISingleton*>*& {
  10587. static std::vector<ISingleton*>* g_singletons = nullptr;
  10588. if( !g_singletons )
  10589. g_singletons = new std::vector<ISingleton*>();
  10590. return g_singletons;
  10591. }
  10592. }
  10593. ISingleton::~ISingleton() {}
  10594. void addSingleton(ISingleton* singleton ) {
  10595. getSingletons()->push_back( singleton );
  10596. }
  10597. void cleanupSingletons() {
  10598. auto& singletons = getSingletons();
  10599. for( auto singleton : *singletons )
  10600. delete singleton;
  10601. delete singletons;
  10602. singletons = nullptr;
  10603. }
  10604. } // namespace Catch
  10605. // end catch_singletons.cpp
  10606. // start catch_startup_exception_registry.cpp
  10607. namespace Catch {
  10608. void StartupExceptionRegistry::add( std::exception_ptr const& exception ) noexcept {
  10609. CATCH_TRY {
  10610. m_exceptions.push_back(exception);
  10611. } CATCH_CATCH_ALL {
  10612. // If we run out of memory during start-up there's really not a lot more we can do about it
  10613. std::terminate();
  10614. }
  10615. }
  10616. std::vector<std::exception_ptr> const& StartupExceptionRegistry::getExceptions() const noexcept {
  10617. return m_exceptions;
  10618. }
  10619. } // end namespace Catch
  10620. // end catch_startup_exception_registry.cpp
  10621. // start catch_stream.cpp
  10622. #include <cstdio>
  10623. #include <iostream>
  10624. #include <fstream>
  10625. #include <sstream>
  10626. #include <vector>
  10627. #include <memory>
  10628. namespace Catch {
  10629. Catch::IStream::~IStream() = default;
  10630. namespace Detail { namespace {
  10631. template<typename WriterF, std::size_t bufferSize=256>
  10632. class StreamBufImpl : public std::streambuf {
  10633. char data[bufferSize];
  10634. WriterF m_writer;
  10635. public:
  10636. StreamBufImpl() {
  10637. setp( data, data + sizeof(data) );
  10638. }
  10639. ~StreamBufImpl() noexcept {
  10640. StreamBufImpl::sync();
  10641. }
  10642. private:
  10643. int overflow( int c ) override {
  10644. sync();
  10645. if( c != EOF ) {
  10646. if( pbase() == epptr() )
  10647. m_writer( std::string( 1, static_cast<char>( c ) ) );
  10648. else
  10649. sputc( static_cast<char>( c ) );
  10650. }
  10651. return 0;
  10652. }
  10653. int sync() override {
  10654. if( pbase() != pptr() ) {
  10655. m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) );
  10656. setp( pbase(), epptr() );
  10657. }
  10658. return 0;
  10659. }
  10660. };
  10661. ///////////////////////////////////////////////////////////////////////////
  10662. struct OutputDebugWriter {
  10663. void operator()( std::string const&str ) {
  10664. writeToDebugConsole( str );
  10665. }
  10666. };
  10667. ///////////////////////////////////////////////////////////////////////////
  10668. class FileStream : public IStream {
  10669. mutable std::ofstream m_ofs;
  10670. public:
  10671. FileStream( StringRef filename ) {
  10672. m_ofs.open( filename.c_str() );
  10673. CATCH_ENFORCE( !m_ofs.fail(), "Unable to open file: '" << filename << "'" );
  10674. }
  10675. ~FileStream() override = default;
  10676. public: // IStream
  10677. std::ostream& stream() const override {
  10678. return m_ofs;
  10679. }
  10680. };
  10681. ///////////////////////////////////////////////////////////////////////////
  10682. class CoutStream : public IStream {
  10683. mutable std::ostream m_os;
  10684. public:
  10685. // Store the streambuf from cout up-front because
  10686. // cout may get redirected when running tests
  10687. CoutStream() : m_os( Catch::cout().rdbuf() ) {}
  10688. ~CoutStream() override = default;
  10689. public: // IStream
  10690. std::ostream& stream() const override { return m_os; }
  10691. };
  10692. ///////////////////////////////////////////////////////////////////////////
  10693. class DebugOutStream : public IStream {
  10694. std::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf;
  10695. mutable std::ostream m_os;
  10696. public:
  10697. DebugOutStream()
  10698. : m_streamBuf( new StreamBufImpl<OutputDebugWriter>() ),
  10699. m_os( m_streamBuf.get() )
  10700. {}
  10701. ~DebugOutStream() override = default;
  10702. public: // IStream
  10703. std::ostream& stream() const override { return m_os; }
  10704. };
  10705. }} // namespace anon::detail
  10706. ///////////////////////////////////////////////////////////////////////////
  10707. auto makeStream( StringRef const &filename ) -> IStream const* {
  10708. if( filename.empty() )
  10709. return new Detail::CoutStream();
  10710. else if( filename[0] == '%' ) {
  10711. if( filename == "%debug" )
  10712. return new Detail::DebugOutStream();
  10713. else
  10714. CATCH_ERROR( "Unrecognised stream: '" << filename << "'" );
  10715. }
  10716. else
  10717. return new Detail::FileStream( filename );
  10718. }
  10719. // This class encapsulates the idea of a pool of ostringstreams that can be reused.
  10720. struct StringStreams {
  10721. std::vector<std::unique_ptr<std::ostringstream>> m_streams;
  10722. std::vector<std::size_t> m_unused;
  10723. std::ostringstream m_referenceStream; // Used for copy state/ flags from
  10724. auto add() -> std::size_t {
  10725. if( m_unused.empty() ) {
  10726. m_streams.push_back( std::unique_ptr<std::ostringstream>( new std::ostringstream ) );
  10727. return m_streams.size()-1;
  10728. }
  10729. else {
  10730. auto index = m_unused.back();
  10731. m_unused.pop_back();
  10732. return index;
  10733. }
  10734. }
  10735. void release( std::size_t index ) {
  10736. m_streams[index]->copyfmt( m_referenceStream ); // Restore initial flags and other state
  10737. m_unused.push_back(index);
  10738. }
  10739. };
  10740. ReusableStringStream::ReusableStringStream()
  10741. : m_index( Singleton<StringStreams>::getMutable().add() ),
  10742. m_oss( Singleton<StringStreams>::getMutable().m_streams[m_index].get() )
  10743. {}
  10744. ReusableStringStream::~ReusableStringStream() {
  10745. static_cast<std::ostringstream*>( m_oss )->str("");
  10746. m_oss->clear();
  10747. Singleton<StringStreams>::getMutable().release( m_index );
  10748. }
  10749. auto ReusableStringStream::str() const -> std::string {
  10750. return static_cast<std::ostringstream*>( m_oss )->str();
  10751. }
  10752. ///////////////////////////////////////////////////////////////////////////
  10753. #ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions
  10754. std::ostream& cout() { return std::cout; }
  10755. std::ostream& cerr() { return std::cerr; }
  10756. std::ostream& clog() { return std::clog; }
  10757. #endif
  10758. }
  10759. // end catch_stream.cpp
  10760. // start catch_string_manip.cpp
  10761. #include <algorithm>
  10762. #include <ostream>
  10763. #include <cstring>
  10764. #include <cctype>
  10765. #include <vector>
  10766. namespace Catch {
  10767. namespace {
  10768. char toLowerCh(char c) {
  10769. return static_cast<char>( std::tolower( c ) );
  10770. }
  10771. }
  10772. bool startsWith( std::string const& s, std::string const& prefix ) {
  10773. return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
  10774. }
  10775. bool startsWith( std::string const& s, char prefix ) {
  10776. return !s.empty() && s[0] == prefix;
  10777. }
  10778. bool endsWith( std::string const& s, std::string const& suffix ) {
  10779. return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
  10780. }
  10781. bool endsWith( std::string const& s, char suffix ) {
  10782. return !s.empty() && s[s.size()-1] == suffix;
  10783. }
  10784. bool contains( std::string const& s, std::string const& infix ) {
  10785. return s.find( infix ) != std::string::npos;
  10786. }
  10787. void toLowerInPlace( std::string& s ) {
  10788. std::transform( s.begin(), s.end(), s.begin(), toLowerCh );
  10789. }
  10790. std::string toLower( std::string const& s ) {
  10791. std::string lc = s;
  10792. toLowerInPlace( lc );
  10793. return lc;
  10794. }
  10795. std::string trim( std::string const& str ) {
  10796. static char const* whitespaceChars = "\n\r\t ";
  10797. std::string::size_type start = str.find_first_not_of( whitespaceChars );
  10798. std::string::size_type end = str.find_last_not_of( whitespaceChars );
  10799. return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string();
  10800. }
  10801. bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) {
  10802. bool replaced = false;
  10803. std::size_t i = str.find( replaceThis );
  10804. while( i != std::string::npos ) {
  10805. replaced = true;
  10806. str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() );
  10807. if( i < str.size()-withThis.size() )
  10808. i = str.find( replaceThis, i+withThis.size() );
  10809. else
  10810. i = std::string::npos;
  10811. }
  10812. return replaced;
  10813. }
  10814. std::vector<StringRef> splitStringRef( StringRef str, char delimiter ) {
  10815. std::vector<StringRef> subStrings;
  10816. std::size_t start = 0;
  10817. for(std::size_t pos = 0; pos < str.size(); ++pos ) {
  10818. if( str[pos] == delimiter ) {
  10819. if( pos - start > 1 )
  10820. subStrings.push_back( str.substr( start, pos-start ) );
  10821. start = pos+1;
  10822. }
  10823. }
  10824. if( start < str.size() )
  10825. subStrings.push_back( str.substr( start, str.size()-start ) );
  10826. return subStrings;
  10827. }
  10828. pluralise::pluralise( std::size_t count, std::string const& label )
  10829. : m_count( count ),
  10830. m_label( label )
  10831. {}
  10832. std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) {
  10833. os << pluraliser.m_count << ' ' << pluraliser.m_label;
  10834. if( pluraliser.m_count != 1 )
  10835. os << 's';
  10836. return os;
  10837. }
  10838. }
  10839. // end catch_string_manip.cpp
  10840. // start catch_stringref.cpp
  10841. #if defined(__clang__)
  10842. # pragma clang diagnostic push
  10843. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  10844. #endif
  10845. #include <ostream>
  10846. #include <cstring>
  10847. #include <cstdint>
  10848. namespace {
  10849. const uint32_t byte_2_lead = 0xC0;
  10850. const uint32_t byte_3_lead = 0xE0;
  10851. const uint32_t byte_4_lead = 0xF0;
  10852. }
  10853. namespace Catch {
  10854. StringRef::StringRef( char const* rawChars ) noexcept
  10855. : StringRef( rawChars, static_cast<StringRef::size_type>(std::strlen(rawChars) ) )
  10856. {}
  10857. StringRef::operator std::string() const {
  10858. return std::string( m_start, m_size );
  10859. }
  10860. void StringRef::swap( StringRef& other ) noexcept {
  10861. std::swap( m_start, other.m_start );
  10862. std::swap( m_size, other.m_size );
  10863. std::swap( m_data, other.m_data );
  10864. }
  10865. auto StringRef::c_str() const -> char const* {
  10866. if( !isSubstring() )
  10867. return m_start;
  10868. const_cast<StringRef *>( this )->takeOwnership();
  10869. return m_data;
  10870. }
  10871. auto StringRef::currentData() const noexcept -> char const* {
  10872. return m_start;
  10873. }
  10874. auto StringRef::isOwned() const noexcept -> bool {
  10875. return m_data != nullptr;
  10876. }
  10877. auto StringRef::isSubstring() const noexcept -> bool {
  10878. return m_start[m_size] != '\0';
  10879. }
  10880. void StringRef::takeOwnership() {
  10881. if( !isOwned() ) {
  10882. m_data = new char[m_size+1];
  10883. memcpy( m_data, m_start, m_size );
  10884. m_data[m_size] = '\0';
  10885. }
  10886. }
  10887. auto StringRef::substr( size_type start, size_type size ) const noexcept -> StringRef {
  10888. if( start < m_size )
  10889. return StringRef( m_start+start, size );
  10890. else
  10891. return StringRef();
  10892. }
  10893. auto StringRef::operator == ( StringRef const& other ) const noexcept -> bool {
  10894. return
  10895. size() == other.size() &&
  10896. (std::strncmp( m_start, other.m_start, size() ) == 0);
  10897. }
  10898. auto StringRef::operator != ( StringRef const& other ) const noexcept -> bool {
  10899. return !operator==( other );
  10900. }
  10901. auto StringRef::operator[](size_type index) const noexcept -> char {
  10902. return m_start[index];
  10903. }
  10904. auto StringRef::numberOfCharacters() const noexcept -> size_type {
  10905. size_type noChars = m_size;
  10906. // Make adjustments for uft encodings
  10907. for( size_type i=0; i < m_size; ++i ) {
  10908. char c = m_start[i];
  10909. if( ( c & byte_2_lead ) == byte_2_lead ) {
  10910. noChars--;
  10911. if (( c & byte_3_lead ) == byte_3_lead )
  10912. noChars--;
  10913. if( ( c & byte_4_lead ) == byte_4_lead )
  10914. noChars--;
  10915. }
  10916. }
  10917. return noChars;
  10918. }
  10919. auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string {
  10920. std::string str;
  10921. str.reserve( lhs.size() + rhs.size() );
  10922. str += lhs;
  10923. str += rhs;
  10924. return str;
  10925. }
  10926. auto operator + ( StringRef const& lhs, const char* rhs ) -> std::string {
  10927. return std::string( lhs ) + std::string( rhs );
  10928. }
  10929. auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string {
  10930. return std::string( lhs ) + std::string( rhs );
  10931. }
  10932. auto operator << ( std::ostream& os, StringRef const& str ) -> std::ostream& {
  10933. return os.write(str.currentData(), str.size());
  10934. }
  10935. auto operator+=( std::string& lhs, StringRef const& rhs ) -> std::string& {
  10936. lhs.append(rhs.currentData(), rhs.size());
  10937. return lhs;
  10938. }
  10939. } // namespace Catch
  10940. #if defined(__clang__)
  10941. # pragma clang diagnostic pop
  10942. #endif
  10943. // end catch_stringref.cpp
  10944. // start catch_tag_alias.cpp
  10945. namespace Catch {
  10946. TagAlias::TagAlias(std::string const & _tag, SourceLineInfo _lineInfo): tag(_tag), lineInfo(_lineInfo) {}
  10947. }
  10948. // end catch_tag_alias.cpp
  10949. // start catch_tag_alias_autoregistrar.cpp
  10950. namespace Catch {
  10951. RegistrarForTagAliases::RegistrarForTagAliases(char const* alias, char const* tag, SourceLineInfo const& lineInfo) {
  10952. CATCH_TRY {
  10953. getMutableRegistryHub().registerTagAlias(alias, tag, lineInfo);
  10954. } CATCH_CATCH_ALL {
  10955. // Do not throw when constructing global objects, instead register the exception to be processed later
  10956. getMutableRegistryHub().registerStartupException();
  10957. }
  10958. }
  10959. }
  10960. // end catch_tag_alias_autoregistrar.cpp
  10961. // start catch_tag_alias_registry.cpp
  10962. #include <sstream>
  10963. namespace Catch {
  10964. TagAliasRegistry::~TagAliasRegistry() {}
  10965. TagAlias const* TagAliasRegistry::find( std::string const& alias ) const {
  10966. auto it = m_registry.find( alias );
  10967. if( it != m_registry.end() )
  10968. return &(it->second);
  10969. else
  10970. return nullptr;
  10971. }
  10972. std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const {
  10973. std::string expandedTestSpec = unexpandedTestSpec;
  10974. for( auto const& registryKvp : m_registry ) {
  10975. std::size_t pos = expandedTestSpec.find( registryKvp.first );
  10976. if( pos != std::string::npos ) {
  10977. expandedTestSpec = expandedTestSpec.substr( 0, pos ) +
  10978. registryKvp.second.tag +
  10979. expandedTestSpec.substr( pos + registryKvp.first.size() );
  10980. }
  10981. }
  10982. return expandedTestSpec;
  10983. }
  10984. void TagAliasRegistry::add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) {
  10985. CATCH_ENFORCE( startsWith(alias, "[@") && endsWith(alias, ']'),
  10986. "error: tag alias, '" << alias << "' is not of the form [@alias name].\n" << lineInfo );
  10987. CATCH_ENFORCE( m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second,
  10988. "error: tag alias, '" << alias << "' already registered.\n"
  10989. << "\tFirst seen at: " << find(alias)->lineInfo << "\n"
  10990. << "\tRedefined at: " << lineInfo );
  10991. }
  10992. ITagAliasRegistry::~ITagAliasRegistry() {}
  10993. ITagAliasRegistry const& ITagAliasRegistry::get() {
  10994. return getRegistryHub().getTagAliasRegistry();
  10995. }
  10996. } // end namespace Catch
  10997. // end catch_tag_alias_registry.cpp
  10998. // start catch_test_case_info.cpp
  10999. #include <cctype>
  11000. #include <exception>
  11001. #include <algorithm>
  11002. #include <sstream>
  11003. namespace Catch {
  11004. namespace {
  11005. TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) {
  11006. if( startsWith( tag, '.' ) ||
  11007. tag == "!hide" )
  11008. return TestCaseInfo::IsHidden;
  11009. else if( tag == "!throws" )
  11010. return TestCaseInfo::Throws;
  11011. else if( tag == "!shouldfail" )
  11012. return TestCaseInfo::ShouldFail;
  11013. else if( tag == "!mayfail" )
  11014. return TestCaseInfo::MayFail;
  11015. else if( tag == "!nonportable" )
  11016. return TestCaseInfo::NonPortable;
  11017. else if( tag == "!benchmark" )
  11018. return static_cast<TestCaseInfo::SpecialProperties>( TestCaseInfo::Benchmark | TestCaseInfo::IsHidden );
  11019. else
  11020. return TestCaseInfo::None;
  11021. }
  11022. bool isReservedTag( std::string const& tag ) {
  11023. return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !std::isalnum( static_cast<unsigned char>(tag[0]) );
  11024. }
  11025. void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) {
  11026. CATCH_ENFORCE( !isReservedTag(tag),
  11027. "Tag name: [" << tag << "] is not allowed.\n"
  11028. << "Tag names starting with non alphanumeric characters are reserved\n"
  11029. << _lineInfo );
  11030. }
  11031. }
  11032. TestCase makeTestCase( ITestInvoker* _testCase,
  11033. std::string const& _className,
  11034. NameAndTags const& nameAndTags,
  11035. SourceLineInfo const& _lineInfo )
  11036. {
  11037. bool isHidden = false;
  11038. // Parse out tags
  11039. std::vector<std::string> tags;
  11040. std::string desc, tag;
  11041. bool inTag = false;
  11042. std::string _descOrTags = nameAndTags.tags;
  11043. for (char c : _descOrTags) {
  11044. if( !inTag ) {
  11045. if( c == '[' )
  11046. inTag = true;
  11047. else
  11048. desc += c;
  11049. }
  11050. else {
  11051. if( c == ']' ) {
  11052. TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag );
  11053. if( ( prop & TestCaseInfo::IsHidden ) != 0 )
  11054. isHidden = true;
  11055. else if( prop == TestCaseInfo::None )
  11056. enforceNotReservedTag( tag, _lineInfo );
  11057. // Merged hide tags like `[.approvals]` should be added as
  11058. // `[.][approvals]`. The `[.]` is added at later point, so
  11059. // we only strip the prefix
  11060. if (startsWith(tag, '.') && tag.size() > 1) {
  11061. tag.erase(0, 1);
  11062. }
  11063. tags.push_back( tag );
  11064. tag.clear();
  11065. inTag = false;
  11066. }
  11067. else
  11068. tag += c;
  11069. }
  11070. }
  11071. if( isHidden ) {
  11072. tags.push_back( "." );
  11073. }
  11074. TestCaseInfo info( nameAndTags.name, _className, desc, tags, _lineInfo );
  11075. return TestCase( _testCase, std::move(info) );
  11076. }
  11077. void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags ) {
  11078. std::sort(begin(tags), end(tags));
  11079. tags.erase(std::unique(begin(tags), end(tags)), end(tags));
  11080. testCaseInfo.lcaseTags.clear();
  11081. for( auto const& tag : tags ) {
  11082. std::string lcaseTag = toLower( tag );
  11083. testCaseInfo.properties = static_cast<TestCaseInfo::SpecialProperties>( testCaseInfo.properties | parseSpecialTag( lcaseTag ) );
  11084. testCaseInfo.lcaseTags.push_back( lcaseTag );
  11085. }
  11086. testCaseInfo.tags = std::move(tags);
  11087. }
  11088. TestCaseInfo::TestCaseInfo( std::string const& _name,
  11089. std::string const& _className,
  11090. std::string const& _description,
  11091. std::vector<std::string> const& _tags,
  11092. SourceLineInfo const& _lineInfo )
  11093. : name( _name ),
  11094. className( _className ),
  11095. description( _description ),
  11096. lineInfo( _lineInfo ),
  11097. properties( None )
  11098. {
  11099. setTags( *this, _tags );
  11100. }
  11101. bool TestCaseInfo::isHidden() const {
  11102. return ( properties & IsHidden ) != 0;
  11103. }
  11104. bool TestCaseInfo::throws() const {
  11105. return ( properties & Throws ) != 0;
  11106. }
  11107. bool TestCaseInfo::okToFail() const {
  11108. return ( properties & (ShouldFail | MayFail ) ) != 0;
  11109. }
  11110. bool TestCaseInfo::expectedToFail() const {
  11111. return ( properties & (ShouldFail ) ) != 0;
  11112. }
  11113. std::string TestCaseInfo::tagsAsString() const {
  11114. std::string ret;
  11115. // '[' and ']' per tag
  11116. std::size_t full_size = 2 * tags.size();
  11117. for (const auto& tag : tags) {
  11118. full_size += tag.size();
  11119. }
  11120. ret.reserve(full_size);
  11121. for (const auto& tag : tags) {
  11122. ret.push_back('[');
  11123. ret.append(tag);
  11124. ret.push_back(']');
  11125. }
  11126. return ret;
  11127. }
  11128. TestCase::TestCase( ITestInvoker* testCase, TestCaseInfo&& info ) : TestCaseInfo( std::move(info) ), test( testCase ) {}
  11129. TestCase TestCase::withName( std::string const& _newName ) const {
  11130. TestCase other( *this );
  11131. other.name = _newName;
  11132. return other;
  11133. }
  11134. void TestCase::invoke() const {
  11135. test->invoke();
  11136. }
  11137. bool TestCase::operator == ( TestCase const& other ) const {
  11138. return test.get() == other.test.get() &&
  11139. name == other.name &&
  11140. className == other.className;
  11141. }
  11142. bool TestCase::operator < ( TestCase const& other ) const {
  11143. return name < other.name;
  11144. }
  11145. TestCaseInfo const& TestCase::getTestCaseInfo() const
  11146. {
  11147. return *this;
  11148. }
  11149. } // end namespace Catch
  11150. // end catch_test_case_info.cpp
  11151. // start catch_test_case_registry_impl.cpp
  11152. #include <sstream>
  11153. namespace Catch {
  11154. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases ) {
  11155. std::vector<TestCase> sorted = unsortedTestCases;
  11156. switch( config.runOrder() ) {
  11157. case RunTests::InLexicographicalOrder:
  11158. std::sort( sorted.begin(), sorted.end() );
  11159. break;
  11160. case RunTests::InRandomOrder:
  11161. seedRng( config );
  11162. std::shuffle( sorted.begin(), sorted.end(), rng() );
  11163. break;
  11164. case RunTests::InDeclarationOrder:
  11165. // already in declaration order
  11166. break;
  11167. }
  11168. return sorted;
  11169. }
  11170. bool isThrowSafe( TestCase const& testCase, IConfig const& config ) {
  11171. return !testCase.throws() || config.allowThrows();
  11172. }
  11173. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ) {
  11174. return testSpec.matches( testCase ) && isThrowSafe( testCase, config );
  11175. }
  11176. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions ) {
  11177. std::set<TestCase> seenFunctions;
  11178. for( auto const& function : functions ) {
  11179. auto prev = seenFunctions.insert( function );
  11180. CATCH_ENFORCE( prev.second,
  11181. "error: TEST_CASE( \"" << function.name << "\" ) already defined.\n"
  11182. << "\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo << "\n"
  11183. << "\tRedefined at " << function.getTestCaseInfo().lineInfo );
  11184. }
  11185. }
  11186. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config ) {
  11187. std::vector<TestCase> filtered;
  11188. filtered.reserve( testCases.size() );
  11189. for (auto const& testCase : testCases) {
  11190. if ((!testSpec.hasFilters() && !testCase.isHidden()) ||
  11191. (testSpec.hasFilters() && matchTest(testCase, testSpec, config))) {
  11192. filtered.push_back(testCase);
  11193. }
  11194. }
  11195. return filtered;
  11196. }
  11197. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config ) {
  11198. return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config );
  11199. }
  11200. void TestRegistry::registerTest( TestCase const& testCase ) {
  11201. std::string name = testCase.getTestCaseInfo().name;
  11202. if( name.empty() ) {
  11203. ReusableStringStream rss;
  11204. rss << "Anonymous test case " << ++m_unnamedCount;
  11205. return registerTest( testCase.withName( rss.str() ) );
  11206. }
  11207. m_functions.push_back( testCase );
  11208. }
  11209. std::vector<TestCase> const& TestRegistry::getAllTests() const {
  11210. return m_functions;
  11211. }
  11212. std::vector<TestCase> const& TestRegistry::getAllTestsSorted( IConfig const& config ) const {
  11213. if( m_sortedFunctions.empty() )
  11214. enforceNoDuplicateTestCases( m_functions );
  11215. if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) {
  11216. m_sortedFunctions = sortTests( config, m_functions );
  11217. m_currentSortOrder = config.runOrder();
  11218. }
  11219. return m_sortedFunctions;
  11220. }
  11221. ///////////////////////////////////////////////////////////////////////////
  11222. TestInvokerAsFunction::TestInvokerAsFunction( void(*testAsFunction)() ) noexcept : m_testAsFunction( testAsFunction ) {}
  11223. void TestInvokerAsFunction::invoke() const {
  11224. m_testAsFunction();
  11225. }
  11226. std::string extractClassName( StringRef const& classOrQualifiedMethodName ) {
  11227. std::string className = classOrQualifiedMethodName;
  11228. if( startsWith( className, '&' ) )
  11229. {
  11230. std::size_t lastColons = className.rfind( "::" );
  11231. std::size_t penultimateColons = className.rfind( "::", lastColons-1 );
  11232. if( penultimateColons == std::string::npos )
  11233. penultimateColons = 1;
  11234. className = className.substr( penultimateColons, lastColons-penultimateColons );
  11235. }
  11236. return className;
  11237. }
  11238. } // end namespace Catch
  11239. // end catch_test_case_registry_impl.cpp
  11240. // start catch_test_case_tracker.cpp
  11241. #include <algorithm>
  11242. #include <cassert>
  11243. #include <stdexcept>
  11244. #include <memory>
  11245. #include <sstream>
  11246. #if defined(__clang__)
  11247. # pragma clang diagnostic push
  11248. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  11249. #endif
  11250. namespace Catch {
  11251. namespace TestCaseTracking {
  11252. NameAndLocation::NameAndLocation( std::string const& _name, SourceLineInfo const& _location )
  11253. : name( _name ),
  11254. location( _location )
  11255. {}
  11256. ITracker::~ITracker() = default;
  11257. ITracker& TrackerContext::startRun() {
  11258. m_rootTracker = std::make_shared<SectionTracker>( NameAndLocation( "{root}", CATCH_INTERNAL_LINEINFO ), *this, nullptr );
  11259. m_currentTracker = nullptr;
  11260. m_runState = Executing;
  11261. return *m_rootTracker;
  11262. }
  11263. void TrackerContext::endRun() {
  11264. m_rootTracker.reset();
  11265. m_currentTracker = nullptr;
  11266. m_runState = NotStarted;
  11267. }
  11268. void TrackerContext::startCycle() {
  11269. m_currentTracker = m_rootTracker.get();
  11270. m_runState = Executing;
  11271. }
  11272. void TrackerContext::completeCycle() {
  11273. m_runState = CompletedCycle;
  11274. }
  11275. bool TrackerContext::completedCycle() const {
  11276. return m_runState == CompletedCycle;
  11277. }
  11278. ITracker& TrackerContext::currentTracker() {
  11279. return *m_currentTracker;
  11280. }
  11281. void TrackerContext::setCurrentTracker( ITracker* tracker ) {
  11282. m_currentTracker = tracker;
  11283. }
  11284. TrackerBase::TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  11285. : m_nameAndLocation( nameAndLocation ),
  11286. m_ctx( ctx ),
  11287. m_parent( parent )
  11288. {}
  11289. NameAndLocation const& TrackerBase::nameAndLocation() const {
  11290. return m_nameAndLocation;
  11291. }
  11292. bool TrackerBase::isComplete() const {
  11293. return m_runState == CompletedSuccessfully || m_runState == Failed;
  11294. }
  11295. bool TrackerBase::isSuccessfullyCompleted() const {
  11296. return m_runState == CompletedSuccessfully;
  11297. }
  11298. bool TrackerBase::isOpen() const {
  11299. return m_runState != NotStarted && !isComplete();
  11300. }
  11301. bool TrackerBase::hasChildren() const {
  11302. return !m_children.empty();
  11303. }
  11304. void TrackerBase::addChild( ITrackerPtr const& child ) {
  11305. m_children.push_back( child );
  11306. }
  11307. ITrackerPtr TrackerBase::findChild( NameAndLocation const& nameAndLocation ) {
  11308. auto it = std::find_if( m_children.begin(), m_children.end(),
  11309. [&nameAndLocation]( ITrackerPtr const& tracker ){
  11310. return
  11311. tracker->nameAndLocation().location == nameAndLocation.location &&
  11312. tracker->nameAndLocation().name == nameAndLocation.name;
  11313. } );
  11314. return( it != m_children.end() )
  11315. ? *it
  11316. : nullptr;
  11317. }
  11318. ITracker& TrackerBase::parent() {
  11319. assert( m_parent ); // Should always be non-null except for root
  11320. return *m_parent;
  11321. }
  11322. void TrackerBase::openChild() {
  11323. if( m_runState != ExecutingChildren ) {
  11324. m_runState = ExecutingChildren;
  11325. if( m_parent )
  11326. m_parent->openChild();
  11327. }
  11328. }
  11329. bool TrackerBase::isSectionTracker() const { return false; }
  11330. bool TrackerBase::isGeneratorTracker() const { return false; }
  11331. void TrackerBase::open() {
  11332. m_runState = Executing;
  11333. moveToThis();
  11334. if( m_parent )
  11335. m_parent->openChild();
  11336. }
  11337. void TrackerBase::close() {
  11338. // Close any still open children (e.g. generators)
  11339. while( &m_ctx.currentTracker() != this )
  11340. m_ctx.currentTracker().close();
  11341. switch( m_runState ) {
  11342. case NeedsAnotherRun:
  11343. break;
  11344. case Executing:
  11345. m_runState = CompletedSuccessfully;
  11346. break;
  11347. case ExecutingChildren:
  11348. if( std::all_of(m_children.begin(), m_children.end(), [](ITrackerPtr const& t){ return t->isComplete(); }) )
  11349. m_runState = CompletedSuccessfully;
  11350. break;
  11351. case NotStarted:
  11352. case CompletedSuccessfully:
  11353. case Failed:
  11354. CATCH_INTERNAL_ERROR( "Illogical state: " << m_runState );
  11355. default:
  11356. CATCH_INTERNAL_ERROR( "Unknown state: " << m_runState );
  11357. }
  11358. moveToParent();
  11359. m_ctx.completeCycle();
  11360. }
  11361. void TrackerBase::fail() {
  11362. m_runState = Failed;
  11363. if( m_parent )
  11364. m_parent->markAsNeedingAnotherRun();
  11365. moveToParent();
  11366. m_ctx.completeCycle();
  11367. }
  11368. void TrackerBase::markAsNeedingAnotherRun() {
  11369. m_runState = NeedsAnotherRun;
  11370. }
  11371. void TrackerBase::moveToParent() {
  11372. assert( m_parent );
  11373. m_ctx.setCurrentTracker( m_parent );
  11374. }
  11375. void TrackerBase::moveToThis() {
  11376. m_ctx.setCurrentTracker( this );
  11377. }
  11378. SectionTracker::SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  11379. : TrackerBase( nameAndLocation, ctx, parent )
  11380. {
  11381. if( parent ) {
  11382. while( !parent->isSectionTracker() )
  11383. parent = &parent->parent();
  11384. SectionTracker& parentSection = static_cast<SectionTracker&>( *parent );
  11385. addNextFilters( parentSection.m_filters );
  11386. }
  11387. }
  11388. bool SectionTracker::isComplete() const {
  11389. bool complete = true;
  11390. if ((m_filters.empty() || m_filters[0] == "") ||
  11391. std::find(m_filters.begin(), m_filters.end(),
  11392. m_nameAndLocation.name) != m_filters.end())
  11393. complete = TrackerBase::isComplete();
  11394. return complete;
  11395. }
  11396. bool SectionTracker::isSectionTracker() const { return true; }
  11397. SectionTracker& SectionTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ) {
  11398. std::shared_ptr<SectionTracker> section;
  11399. ITracker& currentTracker = ctx.currentTracker();
  11400. if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  11401. assert( childTracker );
  11402. assert( childTracker->isSectionTracker() );
  11403. section = std::static_pointer_cast<SectionTracker>( childTracker );
  11404. }
  11405. else {
  11406. section = std::make_shared<SectionTracker>( nameAndLocation, ctx, &currentTracker );
  11407. currentTracker.addChild( section );
  11408. }
  11409. if( !ctx.completedCycle() )
  11410. section->tryOpen();
  11411. return *section;
  11412. }
  11413. void SectionTracker::tryOpen() {
  11414. if( !isComplete() && (m_filters.empty() || m_filters[0].empty() || m_filters[0] == m_nameAndLocation.name ) )
  11415. open();
  11416. }
  11417. void SectionTracker::addInitialFilters( std::vector<std::string> const& filters ) {
  11418. if( !filters.empty() ) {
  11419. m_filters.push_back(""); // Root - should never be consulted
  11420. m_filters.push_back(""); // Test Case - not a section filter
  11421. m_filters.insert( m_filters.end(), filters.begin(), filters.end() );
  11422. }
  11423. }
  11424. void SectionTracker::addNextFilters( std::vector<std::string> const& filters ) {
  11425. if( filters.size() > 1 )
  11426. m_filters.insert( m_filters.end(), ++filters.begin(), filters.end() );
  11427. }
  11428. } // namespace TestCaseTracking
  11429. using TestCaseTracking::ITracker;
  11430. using TestCaseTracking::TrackerContext;
  11431. using TestCaseTracking::SectionTracker;
  11432. } // namespace Catch
  11433. #if defined(__clang__)
  11434. # pragma clang diagnostic pop
  11435. #endif
  11436. // end catch_test_case_tracker.cpp
  11437. // start catch_test_registry.cpp
  11438. namespace Catch {
  11439. auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker* {
  11440. return new(std::nothrow) TestInvokerAsFunction( testAsFunction );
  11441. }
  11442. NameAndTags::NameAndTags( StringRef const& name_ , StringRef const& tags_ ) noexcept : name( name_ ), tags( tags_ ) {}
  11443. AutoReg::AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept {
  11444. CATCH_TRY {
  11445. getMutableRegistryHub()
  11446. .registerTest(
  11447. makeTestCase(
  11448. invoker,
  11449. extractClassName( classOrMethod ),
  11450. nameAndTags,
  11451. lineInfo));
  11452. } CATCH_CATCH_ALL {
  11453. // Do not throw when constructing global objects, instead register the exception to be processed later
  11454. getMutableRegistryHub().registerStartupException();
  11455. }
  11456. }
  11457. AutoReg::~AutoReg() = default;
  11458. }
  11459. // end catch_test_registry.cpp
  11460. // start catch_test_spec.cpp
  11461. #include <algorithm>
  11462. #include <string>
  11463. #include <vector>
  11464. #include <memory>
  11465. namespace Catch {
  11466. TestSpec::Pattern::Pattern( std::string const& name )
  11467. : m_name( name )
  11468. {}
  11469. TestSpec::Pattern::~Pattern() = default;
  11470. std::string const& TestSpec::Pattern::name() const {
  11471. return m_name;
  11472. }
  11473. TestSpec::NamePattern::NamePattern( std::string const& name, std::string const& filterString )
  11474. : Pattern( filterString )
  11475. , m_wildcardPattern( toLower( name ), CaseSensitive::No )
  11476. {}
  11477. bool TestSpec::NamePattern::matches( TestCaseInfo const& testCase ) const {
  11478. return m_wildcardPattern.matches( toLower( testCase.name ) );
  11479. }
  11480. TestSpec::TagPattern::TagPattern( std::string const& tag, std::string const& filterString )
  11481. : Pattern( filterString )
  11482. , m_tag( toLower( tag ) )
  11483. {}
  11484. bool TestSpec::TagPattern::matches( TestCaseInfo const& testCase ) const {
  11485. return std::find(begin(testCase.lcaseTags),
  11486. end(testCase.lcaseTags),
  11487. m_tag) != end(testCase.lcaseTags);
  11488. }
  11489. TestSpec::ExcludedPattern::ExcludedPattern( PatternPtr const& underlyingPattern )
  11490. : Pattern( underlyingPattern->name() )
  11491. , m_underlyingPattern( underlyingPattern )
  11492. {}
  11493. bool TestSpec::ExcludedPattern::matches( TestCaseInfo const& testCase ) const {
  11494. return !m_underlyingPattern->matches( testCase );
  11495. }
  11496. bool TestSpec::Filter::matches( TestCaseInfo const& testCase ) const {
  11497. return std::all_of( m_patterns.begin(), m_patterns.end(), [&]( PatternPtr const& p ){ return p->matches( testCase ); } );
  11498. }
  11499. std::string TestSpec::Filter::name() const {
  11500. std::string name;
  11501. for( auto const& p : m_patterns )
  11502. name += p->name();
  11503. return name;
  11504. }
  11505. bool TestSpec::hasFilters() const {
  11506. return !m_filters.empty();
  11507. }
  11508. bool TestSpec::matches( TestCaseInfo const& testCase ) const {
  11509. return std::any_of( m_filters.begin(), m_filters.end(), [&]( Filter const& f ){ return f.matches( testCase ); } );
  11510. }
  11511. TestSpec::Matches TestSpec::matchesByFilter( std::vector<TestCase> const& testCases, IConfig const& config ) const
  11512. {
  11513. Matches matches( m_filters.size() );
  11514. std::transform( m_filters.begin(), m_filters.end(), matches.begin(), [&]( Filter const& filter ){
  11515. std::vector<TestCase const*> currentMatches;
  11516. for( auto const& test : testCases )
  11517. if( isThrowSafe( test, config ) && filter.matches( test ) )
  11518. currentMatches.emplace_back( &test );
  11519. return FilterMatch{ filter.name(), currentMatches };
  11520. } );
  11521. return matches;
  11522. }
  11523. }
  11524. // end catch_test_spec.cpp
  11525. // start catch_test_spec_parser.cpp
  11526. namespace Catch {
  11527. TestSpecParser::TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {}
  11528. TestSpecParser& TestSpecParser::parse( std::string const& arg ) {
  11529. m_mode = None;
  11530. m_exclusion = false;
  11531. m_arg = m_tagAliases->expandAliases( arg );
  11532. m_escapeChars.clear();
  11533. m_substring.reserve(m_arg.size());
  11534. m_patternName.reserve(m_arg.size());
  11535. for( m_pos = 0; m_pos < m_arg.size(); ++m_pos )
  11536. visitChar( m_arg[m_pos] );
  11537. endMode();
  11538. return *this;
  11539. }
  11540. TestSpec TestSpecParser::testSpec() {
  11541. addFilter();
  11542. return m_testSpec;
  11543. }
  11544. void TestSpecParser::visitChar( char c ) {
  11545. if( c == ',' ) {
  11546. endMode();
  11547. addFilter();
  11548. return;
  11549. }
  11550. switch( m_mode ) {
  11551. case None:
  11552. if( processNoneChar( c ) )
  11553. return;
  11554. break;
  11555. case Name:
  11556. processNameChar( c );
  11557. break;
  11558. case EscapedName:
  11559. endMode();
  11560. break;
  11561. default:
  11562. case Tag:
  11563. case QuotedName:
  11564. if( processOtherChar( c ) )
  11565. return;
  11566. break;
  11567. }
  11568. m_substring += c;
  11569. if( !isControlChar( c ) )
  11570. m_patternName += c;
  11571. }
  11572. // Two of the processing methods return true to signal the caller to return
  11573. // without adding the given character to the current pattern strings
  11574. bool TestSpecParser::processNoneChar( char c ) {
  11575. switch( c ) {
  11576. case ' ':
  11577. return true;
  11578. case '~':
  11579. m_exclusion = true;
  11580. return false;
  11581. case '[':
  11582. startNewMode( Tag );
  11583. return false;
  11584. case '"':
  11585. startNewMode( QuotedName );
  11586. return false;
  11587. case '\\':
  11588. escape();
  11589. return true;
  11590. default:
  11591. startNewMode( Name );
  11592. return false;
  11593. }
  11594. }
  11595. void TestSpecParser::processNameChar( char c ) {
  11596. if( c == '[' ) {
  11597. if( m_substring == "exclude:" )
  11598. m_exclusion = true;
  11599. else
  11600. endMode();
  11601. startNewMode( Tag );
  11602. }
  11603. }
  11604. bool TestSpecParser::processOtherChar( char c ) {
  11605. if( !isControlChar( c ) )
  11606. return false;
  11607. m_substring += c;
  11608. endMode();
  11609. return true;
  11610. }
  11611. void TestSpecParser::startNewMode( Mode mode ) {
  11612. m_mode = mode;
  11613. }
  11614. void TestSpecParser::endMode() {
  11615. switch( m_mode ) {
  11616. case Name:
  11617. case QuotedName:
  11618. return addPattern<TestSpec::NamePattern>();
  11619. case Tag:
  11620. return addPattern<TestSpec::TagPattern>();
  11621. case EscapedName:
  11622. return startNewMode( Name );
  11623. case None:
  11624. default:
  11625. return startNewMode( None );
  11626. }
  11627. }
  11628. void TestSpecParser::escape() {
  11629. m_mode = EscapedName;
  11630. m_escapeChars.push_back( m_pos );
  11631. }
  11632. bool TestSpecParser::isControlChar( char c ) const {
  11633. switch( m_mode ) {
  11634. default:
  11635. return false;
  11636. case None:
  11637. return c == '~';
  11638. case Name:
  11639. return c == '[';
  11640. case EscapedName:
  11641. return true;
  11642. case QuotedName:
  11643. return c == '"';
  11644. case Tag:
  11645. return c == '[' || c == ']';
  11646. }
  11647. }
  11648. void TestSpecParser::addFilter() {
  11649. if( !m_currentFilter.m_patterns.empty() ) {
  11650. m_testSpec.m_filters.push_back( m_currentFilter );
  11651. m_currentFilter = TestSpec::Filter();
  11652. }
  11653. }
  11654. TestSpec parseTestSpec( std::string const& arg ) {
  11655. return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec();
  11656. }
  11657. } // namespace Catch
  11658. // end catch_test_spec_parser.cpp
  11659. // start catch_timer.cpp
  11660. #include <chrono>
  11661. static const uint64_t nanosecondsInSecond = 1000000000;
  11662. namespace Catch {
  11663. auto getCurrentNanosecondsSinceEpoch() -> uint64_t {
  11664. return std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::high_resolution_clock::now().time_since_epoch() ).count();
  11665. }
  11666. namespace {
  11667. auto estimateClockResolution() -> uint64_t {
  11668. uint64_t sum = 0;
  11669. static const uint64_t iterations = 1000000;
  11670. auto startTime = getCurrentNanosecondsSinceEpoch();
  11671. for( std::size_t i = 0; i < iterations; ++i ) {
  11672. uint64_t ticks;
  11673. uint64_t baseTicks = getCurrentNanosecondsSinceEpoch();
  11674. do {
  11675. ticks = getCurrentNanosecondsSinceEpoch();
  11676. } while( ticks == baseTicks );
  11677. auto delta = ticks - baseTicks;
  11678. sum += delta;
  11679. // If we have been calibrating for over 3 seconds -- the clock
  11680. // is terrible and we should move on.
  11681. // TBD: How to signal that the measured resolution is probably wrong?
  11682. if (ticks > startTime + 3 * nanosecondsInSecond) {
  11683. return sum / ( i + 1u );
  11684. }
  11685. }
  11686. // We're just taking the mean, here. To do better we could take the std. dev and exclude outliers
  11687. // - and potentially do more iterations if there's a high variance.
  11688. return sum/iterations;
  11689. }
  11690. }
  11691. auto getEstimatedClockResolution() -> uint64_t {
  11692. static auto s_resolution = estimateClockResolution();
  11693. return s_resolution;
  11694. }
  11695. void Timer::start() {
  11696. m_nanoseconds = getCurrentNanosecondsSinceEpoch();
  11697. }
  11698. auto Timer::getElapsedNanoseconds() const -> uint64_t {
  11699. return getCurrentNanosecondsSinceEpoch() - m_nanoseconds;
  11700. }
  11701. auto Timer::getElapsedMicroseconds() const -> uint64_t {
  11702. return getElapsedNanoseconds()/1000;
  11703. }
  11704. auto Timer::getElapsedMilliseconds() const -> unsigned int {
  11705. return static_cast<unsigned int>(getElapsedMicroseconds()/1000);
  11706. }
  11707. auto Timer::getElapsedSeconds() const -> double {
  11708. return getElapsedMicroseconds()/1000000.0;
  11709. }
  11710. } // namespace Catch
  11711. // end catch_timer.cpp
  11712. // start catch_tostring.cpp
  11713. #if defined(__clang__)
  11714. # pragma clang diagnostic push
  11715. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  11716. # pragma clang diagnostic ignored "-Wglobal-constructors"
  11717. #endif
  11718. // Enable specific decls locally
  11719. #if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  11720. #define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  11721. #endif
  11722. #include <cmath>
  11723. #include <iomanip>
  11724. namespace Catch {
  11725. namespace Detail {
  11726. const std::string unprintableString = "{?}";
  11727. namespace {
  11728. const int hexThreshold = 255;
  11729. struct Endianness {
  11730. enum Arch { Big, Little };
  11731. static Arch which() {
  11732. union _{
  11733. int asInt;
  11734. char asChar[sizeof (int)];
  11735. } u;
  11736. u.asInt = 1;
  11737. return ( u.asChar[sizeof(int)-1] == 1 ) ? Big : Little;
  11738. }
  11739. };
  11740. }
  11741. std::string rawMemoryToString( const void *object, std::size_t size ) {
  11742. // Reverse order for little endian architectures
  11743. int i = 0, end = static_cast<int>( size ), inc = 1;
  11744. if( Endianness::which() == Endianness::Little ) {
  11745. i = end-1;
  11746. end = inc = -1;
  11747. }
  11748. unsigned char const *bytes = static_cast<unsigned char const *>(object);
  11749. ReusableStringStream rss;
  11750. rss << "0x" << std::setfill('0') << std::hex;
  11751. for( ; i != end; i += inc )
  11752. rss << std::setw(2) << static_cast<unsigned>(bytes[i]);
  11753. return rss.str();
  11754. }
  11755. }
  11756. template<typename T>
  11757. std::string fpToString( T value, int precision ) {
  11758. if (Catch::isnan(value)) {
  11759. return "nan";
  11760. }
  11761. ReusableStringStream rss;
  11762. rss << std::setprecision( precision )
  11763. << std::fixed
  11764. << value;
  11765. std::string d = rss.str();
  11766. std::size_t i = d.find_last_not_of( '0' );
  11767. if( i != std::string::npos && i != d.size()-1 ) {
  11768. if( d[i] == '.' )
  11769. i++;
  11770. d = d.substr( 0, i+1 );
  11771. }
  11772. return d;
  11773. }
  11774. //// ======================================================= ////
  11775. //
  11776. // Out-of-line defs for full specialization of StringMaker
  11777. //
  11778. //// ======================================================= ////
  11779. std::string StringMaker<std::string>::convert(const std::string& str) {
  11780. if (!getCurrentContext().getConfig()->showInvisibles()) {
  11781. return '"' + str + '"';
  11782. }
  11783. std::string s("\"");
  11784. for (char c : str) {
  11785. switch (c) {
  11786. case '\n':
  11787. s.append("\\n");
  11788. break;
  11789. case '\t':
  11790. s.append("\\t");
  11791. break;
  11792. default:
  11793. s.push_back(c);
  11794. break;
  11795. }
  11796. }
  11797. s.append("\"");
  11798. return s;
  11799. }
  11800. #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  11801. std::string StringMaker<std::string_view>::convert(std::string_view str) {
  11802. return ::Catch::Detail::stringify(std::string{ str });
  11803. }
  11804. #endif
  11805. std::string StringMaker<char const*>::convert(char const* str) {
  11806. if (str) {
  11807. return ::Catch::Detail::stringify(std::string{ str });
  11808. } else {
  11809. return{ "{null string}" };
  11810. }
  11811. }
  11812. std::string StringMaker<char*>::convert(char* str) {
  11813. if (str) {
  11814. return ::Catch::Detail::stringify(std::string{ str });
  11815. } else {
  11816. return{ "{null string}" };
  11817. }
  11818. }
  11819. #ifdef CATCH_CONFIG_WCHAR
  11820. std::string StringMaker<std::wstring>::convert(const std::wstring& wstr) {
  11821. std::string s;
  11822. s.reserve(wstr.size());
  11823. for (auto c : wstr) {
  11824. s += (c <= 0xff) ? static_cast<char>(c) : '?';
  11825. }
  11826. return ::Catch::Detail::stringify(s);
  11827. }
  11828. # ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  11829. std::string StringMaker<std::wstring_view>::convert(std::wstring_view str) {
  11830. return StringMaker<std::wstring>::convert(std::wstring(str));
  11831. }
  11832. # endif
  11833. std::string StringMaker<wchar_t const*>::convert(wchar_t const * str) {
  11834. if (str) {
  11835. return ::Catch::Detail::stringify(std::wstring{ str });
  11836. } else {
  11837. return{ "{null string}" };
  11838. }
  11839. }
  11840. std::string StringMaker<wchar_t *>::convert(wchar_t * str) {
  11841. if (str) {
  11842. return ::Catch::Detail::stringify(std::wstring{ str });
  11843. } else {
  11844. return{ "{null string}" };
  11845. }
  11846. }
  11847. #endif
  11848. #if defined(CATCH_CONFIG_CPP17_BYTE)
  11849. #include <cstddef>
  11850. std::string StringMaker<std::byte>::convert(std::byte value) {
  11851. return ::Catch::Detail::stringify(std::to_integer<unsigned long long>(value));
  11852. }
  11853. #endif // defined(CATCH_CONFIG_CPP17_BYTE)
  11854. std::string StringMaker<int>::convert(int value) {
  11855. return ::Catch::Detail::stringify(static_cast<long long>(value));
  11856. }
  11857. std::string StringMaker<long>::convert(long value) {
  11858. return ::Catch::Detail::stringify(static_cast<long long>(value));
  11859. }
  11860. std::string StringMaker<long long>::convert(long long value) {
  11861. ReusableStringStream rss;
  11862. rss << value;
  11863. if (value > Detail::hexThreshold) {
  11864. rss << " (0x" << std::hex << value << ')';
  11865. }
  11866. return rss.str();
  11867. }
  11868. std::string StringMaker<unsigned int>::convert(unsigned int value) {
  11869. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  11870. }
  11871. std::string StringMaker<unsigned long>::convert(unsigned long value) {
  11872. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  11873. }
  11874. std::string StringMaker<unsigned long long>::convert(unsigned long long value) {
  11875. ReusableStringStream rss;
  11876. rss << value;
  11877. if (value > Detail::hexThreshold) {
  11878. rss << " (0x" << std::hex << value << ')';
  11879. }
  11880. return rss.str();
  11881. }
  11882. std::string StringMaker<bool>::convert(bool b) {
  11883. return b ? "true" : "false";
  11884. }
  11885. std::string StringMaker<signed char>::convert(signed char value) {
  11886. if (value == '\r') {
  11887. return "'\\r'";
  11888. } else if (value == '\f') {
  11889. return "'\\f'";
  11890. } else if (value == '\n') {
  11891. return "'\\n'";
  11892. } else if (value == '\t') {
  11893. return "'\\t'";
  11894. } else if ('\0' <= value && value < ' ') {
  11895. return ::Catch::Detail::stringify(static_cast<unsigned int>(value));
  11896. } else {
  11897. char chstr[] = "' '";
  11898. chstr[1] = value;
  11899. return chstr;
  11900. }
  11901. }
  11902. std::string StringMaker<char>::convert(char c) {
  11903. return ::Catch::Detail::stringify(static_cast<signed char>(c));
  11904. }
  11905. std::string StringMaker<unsigned char>::convert(unsigned char c) {
  11906. return ::Catch::Detail::stringify(static_cast<char>(c));
  11907. }
  11908. std::string StringMaker<std::nullptr_t>::convert(std::nullptr_t) {
  11909. return "nullptr";
  11910. }
  11911. int StringMaker<float>::precision = 5;
  11912. std::string StringMaker<float>::convert(float value) {
  11913. return fpToString(value, precision) + 'f';
  11914. }
  11915. int StringMaker<double>::precision = 10;
  11916. std::string StringMaker<double>::convert(double value) {
  11917. return fpToString(value, precision);
  11918. }
  11919. std::string ratio_string<std::atto>::symbol() { return "a"; }
  11920. std::string ratio_string<std::femto>::symbol() { return "f"; }
  11921. std::string ratio_string<std::pico>::symbol() { return "p"; }
  11922. std::string ratio_string<std::nano>::symbol() { return "n"; }
  11923. std::string ratio_string<std::micro>::symbol() { return "u"; }
  11924. std::string ratio_string<std::milli>::symbol() { return "m"; }
  11925. } // end namespace Catch
  11926. #if defined(__clang__)
  11927. # pragma clang diagnostic pop
  11928. #endif
  11929. // end catch_tostring.cpp
  11930. // start catch_totals.cpp
  11931. namespace Catch {
  11932. Counts Counts::operator - ( Counts const& other ) const {
  11933. Counts diff;
  11934. diff.passed = passed - other.passed;
  11935. diff.failed = failed - other.failed;
  11936. diff.failedButOk = failedButOk - other.failedButOk;
  11937. return diff;
  11938. }
  11939. Counts& Counts::operator += ( Counts const& other ) {
  11940. passed += other.passed;
  11941. failed += other.failed;
  11942. failedButOk += other.failedButOk;
  11943. return *this;
  11944. }
  11945. std::size_t Counts::total() const {
  11946. return passed + failed + failedButOk;
  11947. }
  11948. bool Counts::allPassed() const {
  11949. return failed == 0 && failedButOk == 0;
  11950. }
  11951. bool Counts::allOk() const {
  11952. return failed == 0;
  11953. }
  11954. Totals Totals::operator - ( Totals const& other ) const {
  11955. Totals diff;
  11956. diff.assertions = assertions - other.assertions;
  11957. diff.testCases = testCases - other.testCases;
  11958. return diff;
  11959. }
  11960. Totals& Totals::operator += ( Totals const& other ) {
  11961. assertions += other.assertions;
  11962. testCases += other.testCases;
  11963. return *this;
  11964. }
  11965. Totals Totals::delta( Totals const& prevTotals ) const {
  11966. Totals diff = *this - prevTotals;
  11967. if( diff.assertions.failed > 0 )
  11968. ++diff.testCases.failed;
  11969. else if( diff.assertions.failedButOk > 0 )
  11970. ++diff.testCases.failedButOk;
  11971. else
  11972. ++diff.testCases.passed;
  11973. return diff;
  11974. }
  11975. }
  11976. // end catch_totals.cpp
  11977. // start catch_uncaught_exceptions.cpp
  11978. #include <exception>
  11979. namespace Catch {
  11980. bool uncaught_exceptions() {
  11981. #if defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
  11982. return std::uncaught_exceptions() > 0;
  11983. #else
  11984. return std::uncaught_exception();
  11985. #endif
  11986. }
  11987. } // end namespace Catch
  11988. // end catch_uncaught_exceptions.cpp
  11989. // start catch_version.cpp
  11990. #include <ostream>
  11991. namespace Catch {
  11992. Version::Version
  11993. ( unsigned int _majorVersion,
  11994. unsigned int _minorVersion,
  11995. unsigned int _patchNumber,
  11996. char const * const _branchName,
  11997. unsigned int _buildNumber )
  11998. : majorVersion( _majorVersion ),
  11999. minorVersion( _minorVersion ),
  12000. patchNumber( _patchNumber ),
  12001. branchName( _branchName ),
  12002. buildNumber( _buildNumber )
  12003. {}
  12004. std::ostream& operator << ( std::ostream& os, Version const& version ) {
  12005. os << version.majorVersion << '.'
  12006. << version.minorVersion << '.'
  12007. << version.patchNumber;
  12008. // branchName is never null -> 0th char is \0 if it is empty
  12009. if (version.branchName[0]) {
  12010. os << '-' << version.branchName
  12011. << '.' << version.buildNumber;
  12012. }
  12013. return os;
  12014. }
  12015. Version const& libraryVersion() {
  12016. static Version version( 2, 9, 2, "", 0 );
  12017. return version;
  12018. }
  12019. }
  12020. // end catch_version.cpp
  12021. // start catch_wildcard_pattern.cpp
  12022. #include <sstream>
  12023. namespace Catch {
  12024. WildcardPattern::WildcardPattern( std::string const& pattern,
  12025. CaseSensitive::Choice caseSensitivity )
  12026. : m_caseSensitivity( caseSensitivity ),
  12027. m_pattern( adjustCase( pattern ) )
  12028. {
  12029. if( startsWith( m_pattern, '*' ) ) {
  12030. m_pattern = m_pattern.substr( 1 );
  12031. m_wildcard = WildcardAtStart;
  12032. }
  12033. if( endsWith( m_pattern, '*' ) ) {
  12034. m_pattern = m_pattern.substr( 0, m_pattern.size()-1 );
  12035. m_wildcard = static_cast<WildcardPosition>( m_wildcard | WildcardAtEnd );
  12036. }
  12037. }
  12038. bool WildcardPattern::matches( std::string const& str ) const {
  12039. switch( m_wildcard ) {
  12040. case NoWildcard:
  12041. return m_pattern == adjustCase( str );
  12042. case WildcardAtStart:
  12043. return endsWith( adjustCase( str ), m_pattern );
  12044. case WildcardAtEnd:
  12045. return startsWith( adjustCase( str ), m_pattern );
  12046. case WildcardAtBothEnds:
  12047. return contains( adjustCase( str ), m_pattern );
  12048. default:
  12049. CATCH_INTERNAL_ERROR( "Unknown enum" );
  12050. }
  12051. }
  12052. std::string WildcardPattern::adjustCase( std::string const& str ) const {
  12053. return m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str;
  12054. }
  12055. }
  12056. // end catch_wildcard_pattern.cpp
  12057. // start catch_xmlwriter.cpp
  12058. #include <iomanip>
  12059. using uchar = unsigned char;
  12060. namespace Catch {
  12061. namespace {
  12062. size_t trailingBytes(unsigned char c) {
  12063. if ((c & 0xE0) == 0xC0) {
  12064. return 2;
  12065. }
  12066. if ((c & 0xF0) == 0xE0) {
  12067. return 3;
  12068. }
  12069. if ((c & 0xF8) == 0xF0) {
  12070. return 4;
  12071. }
  12072. CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
  12073. }
  12074. uint32_t headerValue(unsigned char c) {
  12075. if ((c & 0xE0) == 0xC0) {
  12076. return c & 0x1F;
  12077. }
  12078. if ((c & 0xF0) == 0xE0) {
  12079. return c & 0x0F;
  12080. }
  12081. if ((c & 0xF8) == 0xF0) {
  12082. return c & 0x07;
  12083. }
  12084. CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
  12085. }
  12086. void hexEscapeChar(std::ostream& os, unsigned char c) {
  12087. std::ios_base::fmtflags f(os.flags());
  12088. os << "\\x"
  12089. << std::uppercase << std::hex << std::setfill('0') << std::setw(2)
  12090. << static_cast<int>(c);
  12091. os.flags(f);
  12092. }
  12093. } // anonymous namespace
  12094. XmlEncode::XmlEncode( std::string const& str, ForWhat forWhat )
  12095. : m_str( str ),
  12096. m_forWhat( forWhat )
  12097. {}
  12098. void XmlEncode::encodeTo( std::ostream& os ) const {
  12099. // Apostrophe escaping not necessary if we always use " to write attributes
  12100. // (see: http://www.w3.org/TR/xml/#syntax)
  12101. for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) {
  12102. uchar c = m_str[idx];
  12103. switch (c) {
  12104. case '<': os << "&lt;"; break;
  12105. case '&': os << "&amp;"; break;
  12106. case '>':
  12107. // See: http://www.w3.org/TR/xml/#syntax
  12108. if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']')
  12109. os << "&gt;";
  12110. else
  12111. os << c;
  12112. break;
  12113. case '\"':
  12114. if (m_forWhat == ForAttributes)
  12115. os << "&quot;";
  12116. else
  12117. os << c;
  12118. break;
  12119. default:
  12120. // Check for control characters and invalid utf-8
  12121. // Escape control characters in standard ascii
  12122. // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0
  12123. if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) {
  12124. hexEscapeChar(os, c);
  12125. break;
  12126. }
  12127. // Plain ASCII: Write it to stream
  12128. if (c < 0x7F) {
  12129. os << c;
  12130. break;
  12131. }
  12132. // UTF-8 territory
  12133. // Check if the encoding is valid and if it is not, hex escape bytes.
  12134. // Important: We do not check the exact decoded values for validity, only the encoding format
  12135. // First check that this bytes is a valid lead byte:
  12136. // This means that it is not encoded as 1111 1XXX
  12137. // Or as 10XX XXXX
  12138. if (c < 0xC0 ||
  12139. c >= 0xF8) {
  12140. hexEscapeChar(os, c);
  12141. break;
  12142. }
  12143. auto encBytes = trailingBytes(c);
  12144. // Are there enough bytes left to avoid accessing out-of-bounds memory?
  12145. if (idx + encBytes - 1 >= m_str.size()) {
  12146. hexEscapeChar(os, c);
  12147. break;
  12148. }
  12149. // The header is valid, check data
  12150. // The next encBytes bytes must together be a valid utf-8
  12151. // This means: bitpattern 10XX XXXX and the extracted value is sane (ish)
  12152. bool valid = true;
  12153. uint32_t value = headerValue(c);
  12154. for (std::size_t n = 1; n < encBytes; ++n) {
  12155. uchar nc = m_str[idx + n];
  12156. valid &= ((nc & 0xC0) == 0x80);
  12157. value = (value << 6) | (nc & 0x3F);
  12158. }
  12159. if (
  12160. // Wrong bit pattern of following bytes
  12161. (!valid) ||
  12162. // Overlong encodings
  12163. (value < 0x80) ||
  12164. (0x80 <= value && value < 0x800 && encBytes > 2) ||
  12165. (0x800 < value && value < 0x10000 && encBytes > 3) ||
  12166. // Encoded value out of range
  12167. (value >= 0x110000)
  12168. ) {
  12169. hexEscapeChar(os, c);
  12170. break;
  12171. }
  12172. // If we got here, this is in fact a valid(ish) utf-8 sequence
  12173. for (std::size_t n = 0; n < encBytes; ++n) {
  12174. os << m_str[idx + n];
  12175. }
  12176. idx += encBytes - 1;
  12177. break;
  12178. }
  12179. }
  12180. }
  12181. std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) {
  12182. xmlEncode.encodeTo( os );
  12183. return os;
  12184. }
  12185. XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer )
  12186. : m_writer( writer )
  12187. {}
  12188. XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept
  12189. : m_writer( other.m_writer ){
  12190. other.m_writer = nullptr;
  12191. }
  12192. XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) noexcept {
  12193. if ( m_writer ) {
  12194. m_writer->endElement();
  12195. }
  12196. m_writer = other.m_writer;
  12197. other.m_writer = nullptr;
  12198. return *this;
  12199. }
  12200. XmlWriter::ScopedElement::~ScopedElement() {
  12201. if( m_writer )
  12202. m_writer->endElement();
  12203. }
  12204. XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string const& text, bool indent ) {
  12205. m_writer->writeText( text, indent );
  12206. return *this;
  12207. }
  12208. XmlWriter::XmlWriter( std::ostream& os ) : m_os( os )
  12209. {
  12210. writeDeclaration();
  12211. }
  12212. XmlWriter::~XmlWriter() {
  12213. while( !m_tags.empty() )
  12214. endElement();
  12215. }
  12216. XmlWriter& XmlWriter::startElement( std::string const& name ) {
  12217. ensureTagClosed();
  12218. newlineIfNecessary();
  12219. m_os << m_indent << '<' << name;
  12220. m_tags.push_back( name );
  12221. m_indent += " ";
  12222. m_tagIsOpen = true;
  12223. return *this;
  12224. }
  12225. XmlWriter::ScopedElement XmlWriter::scopedElement( std::string const& name ) {
  12226. ScopedElement scoped( this );
  12227. startElement( name );
  12228. return scoped;
  12229. }
  12230. XmlWriter& XmlWriter::endElement() {
  12231. newlineIfNecessary();
  12232. m_indent = m_indent.substr( 0, m_indent.size()-2 );
  12233. if( m_tagIsOpen ) {
  12234. m_os << "/>";
  12235. m_tagIsOpen = false;
  12236. }
  12237. else {
  12238. m_os << m_indent << "</" << m_tags.back() << ">";
  12239. }
  12240. m_os << std::endl;
  12241. m_tags.pop_back();
  12242. return *this;
  12243. }
  12244. XmlWriter& XmlWriter::writeAttribute( std::string const& name, std::string const& attribute ) {
  12245. if( !name.empty() && !attribute.empty() )
  12246. m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"';
  12247. return *this;
  12248. }
  12249. XmlWriter& XmlWriter::writeAttribute( std::string const& name, bool attribute ) {
  12250. m_os << ' ' << name << "=\"" << ( attribute ? "true" : "false" ) << '"';
  12251. return *this;
  12252. }
  12253. XmlWriter& XmlWriter::writeText( std::string const& text, bool indent ) {
  12254. if( !text.empty() ){
  12255. bool tagWasOpen = m_tagIsOpen;
  12256. ensureTagClosed();
  12257. if( tagWasOpen && indent )
  12258. m_os << m_indent;
  12259. m_os << XmlEncode( text );
  12260. m_needsNewline = true;
  12261. }
  12262. return *this;
  12263. }
  12264. XmlWriter& XmlWriter::writeComment( std::string const& text ) {
  12265. ensureTagClosed();
  12266. m_os << m_indent << "<!--" << text << "-->";
  12267. m_needsNewline = true;
  12268. return *this;
  12269. }
  12270. void XmlWriter::writeStylesheetRef( std::string const& url ) {
  12271. m_os << "<?xml-stylesheet type=\"text/xsl\" href=\"" << url << "\"?>\n";
  12272. }
  12273. XmlWriter& XmlWriter::writeBlankLine() {
  12274. ensureTagClosed();
  12275. m_os << '\n';
  12276. return *this;
  12277. }
  12278. void XmlWriter::ensureTagClosed() {
  12279. if( m_tagIsOpen ) {
  12280. m_os << ">" << std::endl;
  12281. m_tagIsOpen = false;
  12282. }
  12283. }
  12284. void XmlWriter::writeDeclaration() {
  12285. m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
  12286. }
  12287. void XmlWriter::newlineIfNecessary() {
  12288. if( m_needsNewline ) {
  12289. m_os << std::endl;
  12290. m_needsNewline = false;
  12291. }
  12292. }
  12293. }
  12294. // end catch_xmlwriter.cpp
  12295. // start catch_reporter_bases.cpp
  12296. #include <cstring>
  12297. #include <cfloat>
  12298. #include <cstdio>
  12299. #include <cassert>
  12300. #include <memory>
  12301. namespace Catch {
  12302. void prepareExpandedExpression(AssertionResult& result) {
  12303. result.getExpandedExpression();
  12304. }
  12305. // Because formatting using c++ streams is stateful, drop down to C is required
  12306. // Alternatively we could use stringstream, but its performance is... not good.
  12307. std::string getFormattedDuration( double duration ) {
  12308. // Max exponent + 1 is required to represent the whole part
  12309. // + 1 for decimal point
  12310. // + 3 for the 3 decimal places
  12311. // + 1 for null terminator
  12312. const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1;
  12313. char buffer[maxDoubleSize];
  12314. // Save previous errno, to prevent sprintf from overwriting it
  12315. ErrnoGuard guard;
  12316. #ifdef _MSC_VER
  12317. sprintf_s(buffer, "%.3f", duration);
  12318. #else
  12319. std::sprintf(buffer, "%.3f", duration);
  12320. #endif
  12321. return std::string(buffer);
  12322. }
  12323. std::string serializeFilters( std::vector<std::string> const& container ) {
  12324. ReusableStringStream oss;
  12325. bool first = true;
  12326. for (auto&& filter : container)
  12327. {
  12328. if (!first)
  12329. oss << ' ';
  12330. else
  12331. first = false;
  12332. oss << filter;
  12333. }
  12334. return oss.str();
  12335. }
  12336. TestEventListenerBase::TestEventListenerBase(ReporterConfig const & _config)
  12337. :StreamingReporterBase(_config) {}
  12338. std::set<Verbosity> TestEventListenerBase::getSupportedVerbosities() {
  12339. return { Verbosity::Quiet, Verbosity::Normal, Verbosity::High };
  12340. }
  12341. void TestEventListenerBase::assertionStarting(AssertionInfo const &) {}
  12342. bool TestEventListenerBase::assertionEnded(AssertionStats const &) {
  12343. return false;
  12344. }
  12345. } // end namespace Catch
  12346. // end catch_reporter_bases.cpp
  12347. // start catch_reporter_compact.cpp
  12348. namespace {
  12349. #ifdef CATCH_PLATFORM_MAC
  12350. const char* failedString() { return "FAILED"; }
  12351. const char* passedString() { return "PASSED"; }
  12352. #else
  12353. const char* failedString() { return "failed"; }
  12354. const char* passedString() { return "passed"; }
  12355. #endif
  12356. // Colour::LightGrey
  12357. Catch::Colour::Code dimColour() { return Catch::Colour::FileName; }
  12358. std::string bothOrAll( std::size_t count ) {
  12359. return count == 1 ? std::string() :
  12360. count == 2 ? "both " : "all " ;
  12361. }
  12362. } // anon namespace
  12363. namespace Catch {
  12364. namespace {
  12365. // Colour, message variants:
  12366. // - white: No tests ran.
  12367. // - red: Failed [both/all] N test cases, failed [both/all] M assertions.
  12368. // - white: Passed [both/all] N test cases (no assertions).
  12369. // - red: Failed N tests cases, failed M assertions.
  12370. // - green: Passed [both/all] N tests cases with M assertions.
  12371. void printTotals(std::ostream& out, const Totals& totals) {
  12372. if (totals.testCases.total() == 0) {
  12373. out << "No tests ran.";
  12374. } else if (totals.testCases.failed == totals.testCases.total()) {
  12375. Colour colour(Colour::ResultError);
  12376. const std::string qualify_assertions_failed =
  12377. totals.assertions.failed == totals.assertions.total() ?
  12378. bothOrAll(totals.assertions.failed) : std::string();
  12379. out <<
  12380. "Failed " << bothOrAll(totals.testCases.failed)
  12381. << pluralise(totals.testCases.failed, "test case") << ", "
  12382. "failed " << qualify_assertions_failed <<
  12383. pluralise(totals.assertions.failed, "assertion") << '.';
  12384. } else if (totals.assertions.total() == 0) {
  12385. out <<
  12386. "Passed " << bothOrAll(totals.testCases.total())
  12387. << pluralise(totals.testCases.total(), "test case")
  12388. << " (no assertions).";
  12389. } else if (totals.assertions.failed) {
  12390. Colour colour(Colour::ResultError);
  12391. out <<
  12392. "Failed " << pluralise(totals.testCases.failed, "test case") << ", "
  12393. "failed " << pluralise(totals.assertions.failed, "assertion") << '.';
  12394. } else {
  12395. Colour colour(Colour::ResultSuccess);
  12396. out <<
  12397. "Passed " << bothOrAll(totals.testCases.passed)
  12398. << pluralise(totals.testCases.passed, "test case") <<
  12399. " with " << pluralise(totals.assertions.passed, "assertion") << '.';
  12400. }
  12401. }
  12402. // Implementation of CompactReporter formatting
  12403. class AssertionPrinter {
  12404. public:
  12405. AssertionPrinter& operator= (AssertionPrinter const&) = delete;
  12406. AssertionPrinter(AssertionPrinter const&) = delete;
  12407. AssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
  12408. : stream(_stream)
  12409. , result(_stats.assertionResult)
  12410. , messages(_stats.infoMessages)
  12411. , itMessage(_stats.infoMessages.begin())
  12412. , printInfoMessages(_printInfoMessages) {}
  12413. void print() {
  12414. printSourceInfo();
  12415. itMessage = messages.begin();
  12416. switch (result.getResultType()) {
  12417. case ResultWas::Ok:
  12418. printResultType(Colour::ResultSuccess, passedString());
  12419. printOriginalExpression();
  12420. printReconstructedExpression();
  12421. if (!result.hasExpression())
  12422. printRemainingMessages(Colour::None);
  12423. else
  12424. printRemainingMessages();
  12425. break;
  12426. case ResultWas::ExpressionFailed:
  12427. if (result.isOk())
  12428. printResultType(Colour::ResultSuccess, failedString() + std::string(" - but was ok"));
  12429. else
  12430. printResultType(Colour::Error, failedString());
  12431. printOriginalExpression();
  12432. printReconstructedExpression();
  12433. printRemainingMessages();
  12434. break;
  12435. case ResultWas::ThrewException:
  12436. printResultType(Colour::Error, failedString());
  12437. printIssue("unexpected exception with message:");
  12438. printMessage();
  12439. printExpressionWas();
  12440. printRemainingMessages();
  12441. break;
  12442. case ResultWas::FatalErrorCondition:
  12443. printResultType(Colour::Error, failedString());
  12444. printIssue("fatal error condition with message:");
  12445. printMessage();
  12446. printExpressionWas();
  12447. printRemainingMessages();
  12448. break;
  12449. case ResultWas::DidntThrowException:
  12450. printResultType(Colour::Error, failedString());
  12451. printIssue("expected exception, got none");
  12452. printExpressionWas();
  12453. printRemainingMessages();
  12454. break;
  12455. case ResultWas::Info:
  12456. printResultType(Colour::None, "info");
  12457. printMessage();
  12458. printRemainingMessages();
  12459. break;
  12460. case ResultWas::Warning:
  12461. printResultType(Colour::None, "warning");
  12462. printMessage();
  12463. printRemainingMessages();
  12464. break;
  12465. case ResultWas::ExplicitFailure:
  12466. printResultType(Colour::Error, failedString());
  12467. printIssue("explicitly");
  12468. printRemainingMessages(Colour::None);
  12469. break;
  12470. // These cases are here to prevent compiler warnings
  12471. case ResultWas::Unknown:
  12472. case ResultWas::FailureBit:
  12473. case ResultWas::Exception:
  12474. printResultType(Colour::Error, "** internal error **");
  12475. break;
  12476. }
  12477. }
  12478. private:
  12479. void printSourceInfo() const {
  12480. Colour colourGuard(Colour::FileName);
  12481. stream << result.getSourceInfo() << ':';
  12482. }
  12483. void printResultType(Colour::Code colour, std::string const& passOrFail) const {
  12484. if (!passOrFail.empty()) {
  12485. {
  12486. Colour colourGuard(colour);
  12487. stream << ' ' << passOrFail;
  12488. }
  12489. stream << ':';
  12490. }
  12491. }
  12492. void printIssue(std::string const& issue) const {
  12493. stream << ' ' << issue;
  12494. }
  12495. void printExpressionWas() {
  12496. if (result.hasExpression()) {
  12497. stream << ';';
  12498. {
  12499. Colour colour(dimColour());
  12500. stream << " expression was:";
  12501. }
  12502. printOriginalExpression();
  12503. }
  12504. }
  12505. void printOriginalExpression() const {
  12506. if (result.hasExpression()) {
  12507. stream << ' ' << result.getExpression();
  12508. }
  12509. }
  12510. void printReconstructedExpression() const {
  12511. if (result.hasExpandedExpression()) {
  12512. {
  12513. Colour colour(dimColour());
  12514. stream << " for: ";
  12515. }
  12516. stream << result.getExpandedExpression();
  12517. }
  12518. }
  12519. void printMessage() {
  12520. if (itMessage != messages.end()) {
  12521. stream << " '" << itMessage->message << '\'';
  12522. ++itMessage;
  12523. }
  12524. }
  12525. void printRemainingMessages(Colour::Code colour = dimColour()) {
  12526. if (itMessage == messages.end())
  12527. return;
  12528. const auto itEnd = messages.cend();
  12529. const auto N = static_cast<std::size_t>(std::distance(itMessage, itEnd));
  12530. {
  12531. Colour colourGuard(colour);
  12532. stream << " with " << pluralise(N, "message") << ':';
  12533. }
  12534. while (itMessage != itEnd) {
  12535. // If this assertion is a warning ignore any INFO messages
  12536. if (printInfoMessages || itMessage->type != ResultWas::Info) {
  12537. printMessage();
  12538. if (itMessage != itEnd) {
  12539. Colour colourGuard(dimColour());
  12540. stream << " and";
  12541. }
  12542. continue;
  12543. }
  12544. ++itMessage;
  12545. }
  12546. }
  12547. private:
  12548. std::ostream& stream;
  12549. AssertionResult const& result;
  12550. std::vector<MessageInfo> messages;
  12551. std::vector<MessageInfo>::const_iterator itMessage;
  12552. bool printInfoMessages;
  12553. };
  12554. } // anon namespace
  12555. std::string CompactReporter::getDescription() {
  12556. return "Reports test results on a single line, suitable for IDEs";
  12557. }
  12558. ReporterPreferences CompactReporter::getPreferences() const {
  12559. return m_reporterPrefs;
  12560. }
  12561. void CompactReporter::noMatchingTestCases( std::string const& spec ) {
  12562. stream << "No test cases matched '" << spec << '\'' << std::endl;
  12563. }
  12564. void CompactReporter::assertionStarting( AssertionInfo const& ) {}
  12565. bool CompactReporter::assertionEnded( AssertionStats const& _assertionStats ) {
  12566. AssertionResult const& result = _assertionStats.assertionResult;
  12567. bool printInfoMessages = true;
  12568. // Drop out if result was successful and we're not printing those
  12569. if( !m_config->includeSuccessfulResults() && result.isOk() ) {
  12570. if( result.getResultType() != ResultWas::Warning )
  12571. return false;
  12572. printInfoMessages = false;
  12573. }
  12574. AssertionPrinter printer( stream, _assertionStats, printInfoMessages );
  12575. printer.print();
  12576. stream << std::endl;
  12577. return true;
  12578. }
  12579. void CompactReporter::sectionEnded(SectionStats const& _sectionStats) {
  12580. if (m_config->showDurations() == ShowDurations::Always) {
  12581. stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  12582. }
  12583. }
  12584. void CompactReporter::testRunEnded( TestRunStats const& _testRunStats ) {
  12585. printTotals( stream, _testRunStats.totals );
  12586. stream << '\n' << std::endl;
  12587. StreamingReporterBase::testRunEnded( _testRunStats );
  12588. }
  12589. CompactReporter::~CompactReporter() {}
  12590. CATCH_REGISTER_REPORTER( "compact", CompactReporter )
  12591. } // end namespace Catch
  12592. // end catch_reporter_compact.cpp
  12593. // start catch_reporter_console.cpp
  12594. #include <cfloat>
  12595. #include <cstdio>
  12596. #if defined(_MSC_VER)
  12597. #pragma warning(push)
  12598. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  12599. // Note that 4062 (not all labels are handled and default is missing) is enabled
  12600. #endif
  12601. #if defined(__clang__)
  12602. # pragma clang diagnostic push
  12603. // For simplicity, benchmarking-only helpers are always enabled
  12604. # pragma clang diagnostic ignored "-Wunused-function"
  12605. #endif
  12606. namespace Catch {
  12607. namespace {
  12608. // Formatter impl for ConsoleReporter
  12609. class ConsoleAssertionPrinter {
  12610. public:
  12611. ConsoleAssertionPrinter& operator= (ConsoleAssertionPrinter const&) = delete;
  12612. ConsoleAssertionPrinter(ConsoleAssertionPrinter const&) = delete;
  12613. ConsoleAssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
  12614. : stream(_stream),
  12615. stats(_stats),
  12616. result(_stats.assertionResult),
  12617. colour(Colour::None),
  12618. message(result.getMessage()),
  12619. messages(_stats.infoMessages),
  12620. printInfoMessages(_printInfoMessages) {
  12621. switch (result.getResultType()) {
  12622. case ResultWas::Ok:
  12623. colour = Colour::Success;
  12624. passOrFail = "PASSED";
  12625. //if( result.hasMessage() )
  12626. if (_stats.infoMessages.size() == 1)
  12627. messageLabel = "with message";
  12628. if (_stats.infoMessages.size() > 1)
  12629. messageLabel = "with messages";
  12630. break;
  12631. case ResultWas::ExpressionFailed:
  12632. if (result.isOk()) {
  12633. colour = Colour::Success;
  12634. passOrFail = "FAILED - but was ok";
  12635. } else {
  12636. colour = Colour::Error;
  12637. passOrFail = "FAILED";
  12638. }
  12639. if (_stats.infoMessages.size() == 1)
  12640. messageLabel = "with message";
  12641. if (_stats.infoMessages.size() > 1)
  12642. messageLabel = "with messages";
  12643. break;
  12644. case ResultWas::ThrewException:
  12645. colour = Colour::Error;
  12646. passOrFail = "FAILED";
  12647. messageLabel = "due to unexpected exception with ";
  12648. if (_stats.infoMessages.size() == 1)
  12649. messageLabel += "message";
  12650. if (_stats.infoMessages.size() > 1)
  12651. messageLabel += "messages";
  12652. break;
  12653. case ResultWas::FatalErrorCondition:
  12654. colour = Colour::Error;
  12655. passOrFail = "FAILED";
  12656. messageLabel = "due to a fatal error condition";
  12657. break;
  12658. case ResultWas::DidntThrowException:
  12659. colour = Colour::Error;
  12660. passOrFail = "FAILED";
  12661. messageLabel = "because no exception was thrown where one was expected";
  12662. break;
  12663. case ResultWas::Info:
  12664. messageLabel = "info";
  12665. break;
  12666. case ResultWas::Warning:
  12667. messageLabel = "warning";
  12668. break;
  12669. case ResultWas::ExplicitFailure:
  12670. passOrFail = "FAILED";
  12671. colour = Colour::Error;
  12672. if (_stats.infoMessages.size() == 1)
  12673. messageLabel = "explicitly with message";
  12674. if (_stats.infoMessages.size() > 1)
  12675. messageLabel = "explicitly with messages";
  12676. break;
  12677. // These cases are here to prevent compiler warnings
  12678. case ResultWas::Unknown:
  12679. case ResultWas::FailureBit:
  12680. case ResultWas::Exception:
  12681. passOrFail = "** internal error **";
  12682. colour = Colour::Error;
  12683. break;
  12684. }
  12685. }
  12686. void print() const {
  12687. printSourceInfo();
  12688. if (stats.totals.assertions.total() > 0) {
  12689. printResultType();
  12690. printOriginalExpression();
  12691. printReconstructedExpression();
  12692. } else {
  12693. stream << '\n';
  12694. }
  12695. printMessage();
  12696. }
  12697. private:
  12698. void printResultType() const {
  12699. if (!passOrFail.empty()) {
  12700. Colour colourGuard(colour);
  12701. stream << passOrFail << ":\n";
  12702. }
  12703. }
  12704. void printOriginalExpression() const {
  12705. if (result.hasExpression()) {
  12706. Colour colourGuard(Colour::OriginalExpression);
  12707. stream << " ";
  12708. stream << result.getExpressionInMacro();
  12709. stream << '\n';
  12710. }
  12711. }
  12712. void printReconstructedExpression() const {
  12713. if (result.hasExpandedExpression()) {
  12714. stream << "with expansion:\n";
  12715. Colour colourGuard(Colour::ReconstructedExpression);
  12716. stream << Column(result.getExpandedExpression()).indent(2) << '\n';
  12717. }
  12718. }
  12719. void printMessage() const {
  12720. if (!messageLabel.empty())
  12721. stream << messageLabel << ':' << '\n';
  12722. for (auto const& msg : messages) {
  12723. // If this assertion is a warning ignore any INFO messages
  12724. if (printInfoMessages || msg.type != ResultWas::Info)
  12725. stream << Column(msg.message).indent(2) << '\n';
  12726. }
  12727. }
  12728. void printSourceInfo() const {
  12729. Colour colourGuard(Colour::FileName);
  12730. stream << result.getSourceInfo() << ": ";
  12731. }
  12732. std::ostream& stream;
  12733. AssertionStats const& stats;
  12734. AssertionResult const& result;
  12735. Colour::Code colour;
  12736. std::string passOrFail;
  12737. std::string messageLabel;
  12738. std::string message;
  12739. std::vector<MessageInfo> messages;
  12740. bool printInfoMessages;
  12741. };
  12742. std::size_t makeRatio(std::size_t number, std::size_t total) {
  12743. std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0;
  12744. return (ratio == 0 && number > 0) ? 1 : ratio;
  12745. }
  12746. std::size_t& findMax(std::size_t& i, std::size_t& j, std::size_t& k) {
  12747. if (i > j && i > k)
  12748. return i;
  12749. else if (j > k)
  12750. return j;
  12751. else
  12752. return k;
  12753. }
  12754. struct ColumnInfo {
  12755. enum Justification { Left, Right };
  12756. std::string name;
  12757. int width;
  12758. Justification justification;
  12759. };
  12760. struct ColumnBreak {};
  12761. struct RowBreak {};
  12762. class Duration {
  12763. enum class Unit {
  12764. Auto,
  12765. Nanoseconds,
  12766. Microseconds,
  12767. Milliseconds,
  12768. Seconds,
  12769. Minutes
  12770. };
  12771. static const uint64_t s_nanosecondsInAMicrosecond = 1000;
  12772. static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond;
  12773. static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond;
  12774. static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond;
  12775. uint64_t m_inNanoseconds;
  12776. Unit m_units;
  12777. public:
  12778. explicit Duration(double inNanoseconds, Unit units = Unit::Auto)
  12779. : Duration(static_cast<uint64_t>(inNanoseconds), units) {
  12780. }
  12781. explicit Duration(uint64_t inNanoseconds, Unit units = Unit::Auto)
  12782. : m_inNanoseconds(inNanoseconds),
  12783. m_units(units) {
  12784. if (m_units == Unit::Auto) {
  12785. if (m_inNanoseconds < s_nanosecondsInAMicrosecond)
  12786. m_units = Unit::Nanoseconds;
  12787. else if (m_inNanoseconds < s_nanosecondsInAMillisecond)
  12788. m_units = Unit::Microseconds;
  12789. else if (m_inNanoseconds < s_nanosecondsInASecond)
  12790. m_units = Unit::Milliseconds;
  12791. else if (m_inNanoseconds < s_nanosecondsInAMinute)
  12792. m_units = Unit::Seconds;
  12793. else
  12794. m_units = Unit::Minutes;
  12795. }
  12796. }
  12797. auto value() const -> double {
  12798. switch (m_units) {
  12799. case Unit::Microseconds:
  12800. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMicrosecond);
  12801. case Unit::Milliseconds:
  12802. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMillisecond);
  12803. case Unit::Seconds:
  12804. return m_inNanoseconds / static_cast<double>(s_nanosecondsInASecond);
  12805. case Unit::Minutes:
  12806. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMinute);
  12807. default:
  12808. return static_cast<double>(m_inNanoseconds);
  12809. }
  12810. }
  12811. auto unitsAsString() const -> std::string {
  12812. switch (m_units) {
  12813. case Unit::Nanoseconds:
  12814. return "ns";
  12815. case Unit::Microseconds:
  12816. return "us";
  12817. case Unit::Milliseconds:
  12818. return "ms";
  12819. case Unit::Seconds:
  12820. return "s";
  12821. case Unit::Minutes:
  12822. return "m";
  12823. default:
  12824. return "** internal error **";
  12825. }
  12826. }
  12827. friend auto operator << (std::ostream& os, Duration const& duration) -> std::ostream& {
  12828. return os << duration.value() << " " << duration.unitsAsString();
  12829. }
  12830. };
  12831. } // end anon namespace
  12832. class TablePrinter {
  12833. std::ostream& m_os;
  12834. std::vector<ColumnInfo> m_columnInfos;
  12835. std::ostringstream m_oss;
  12836. int m_currentColumn = -1;
  12837. bool m_isOpen = false;
  12838. public:
  12839. TablePrinter( std::ostream& os, std::vector<ColumnInfo> columnInfos )
  12840. : m_os( os ),
  12841. m_columnInfos( std::move( columnInfos ) ) {}
  12842. auto columnInfos() const -> std::vector<ColumnInfo> const& {
  12843. return m_columnInfos;
  12844. }
  12845. void open() {
  12846. if (!m_isOpen) {
  12847. m_isOpen = true;
  12848. *this << RowBreak();
  12849. Columns headerCols;
  12850. Spacer spacer(2);
  12851. for (auto const& info : m_columnInfos) {
  12852. headerCols += Column(info.name).width(static_cast<std::size_t>(info.width - 2));
  12853. headerCols += spacer;
  12854. }
  12855. m_os << headerCols << "\n";
  12856. m_os << Catch::getLineOfChars<'-'>() << "\n";
  12857. }
  12858. }
  12859. void close() {
  12860. if (m_isOpen) {
  12861. *this << RowBreak();
  12862. m_os << std::endl;
  12863. m_isOpen = false;
  12864. }
  12865. }
  12866. template<typename T>
  12867. friend TablePrinter& operator << (TablePrinter& tp, T const& value) {
  12868. tp.m_oss << value;
  12869. return tp;
  12870. }
  12871. friend TablePrinter& operator << (TablePrinter& tp, ColumnBreak) {
  12872. auto colStr = tp.m_oss.str();
  12873. // This takes account of utf8 encodings
  12874. auto strSize = Catch::StringRef(colStr).numberOfCharacters();
  12875. tp.m_oss.str("");
  12876. tp.open();
  12877. if (tp.m_currentColumn == static_cast<int>(tp.m_columnInfos.size() - 1)) {
  12878. tp.m_currentColumn = -1;
  12879. tp.m_os << "\n";
  12880. }
  12881. tp.m_currentColumn++;
  12882. auto colInfo = tp.m_columnInfos[tp.m_currentColumn];
  12883. auto padding = (strSize + 2 < static_cast<std::size_t>(colInfo.width))
  12884. ? std::string(colInfo.width - (strSize + 2), ' ')
  12885. : std::string();
  12886. if (colInfo.justification == ColumnInfo::Left)
  12887. tp.m_os << colStr << padding << " ";
  12888. else
  12889. tp.m_os << padding << colStr << " ";
  12890. return tp;
  12891. }
  12892. friend TablePrinter& operator << (TablePrinter& tp, RowBreak) {
  12893. if (tp.m_currentColumn > 0) {
  12894. tp.m_os << "\n";
  12895. tp.m_currentColumn = -1;
  12896. }
  12897. return tp;
  12898. }
  12899. };
  12900. ConsoleReporter::ConsoleReporter(ReporterConfig const& config)
  12901. : StreamingReporterBase(config),
  12902. m_tablePrinter(new TablePrinter(config.stream(),
  12903. {
  12904. { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 32, ColumnInfo::Left },
  12905. { "samples mean std dev", 14, ColumnInfo::Right },
  12906. { "iterations low mean low std dev", 14, ColumnInfo::Right },
  12907. { "estimated high mean high std dev", 14, ColumnInfo::Right }
  12908. })) {}
  12909. ConsoleReporter::~ConsoleReporter() = default;
  12910. std::string ConsoleReporter::getDescription() {
  12911. return "Reports test results as plain lines of text";
  12912. }
  12913. void ConsoleReporter::noMatchingTestCases(std::string const& spec) {
  12914. stream << "No test cases matched '" << spec << '\'' << std::endl;
  12915. }
  12916. void ConsoleReporter::assertionStarting(AssertionInfo const&) {}
  12917. bool ConsoleReporter::assertionEnded(AssertionStats const& _assertionStats) {
  12918. AssertionResult const& result = _assertionStats.assertionResult;
  12919. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  12920. // Drop out if result was successful but we're not printing them.
  12921. if (!includeResults && result.getResultType() != ResultWas::Warning)
  12922. return false;
  12923. lazyPrint();
  12924. ConsoleAssertionPrinter printer(stream, _assertionStats, includeResults);
  12925. printer.print();
  12926. stream << std::endl;
  12927. return true;
  12928. }
  12929. void ConsoleReporter::sectionStarting(SectionInfo const& _sectionInfo) {
  12930. m_tablePrinter->close();
  12931. m_headerPrinted = false;
  12932. StreamingReporterBase::sectionStarting(_sectionInfo);
  12933. }
  12934. void ConsoleReporter::sectionEnded(SectionStats const& _sectionStats) {
  12935. m_tablePrinter->close();
  12936. if (_sectionStats.missingAssertions) {
  12937. lazyPrint();
  12938. Colour colour(Colour::ResultError);
  12939. if (m_sectionStack.size() > 1)
  12940. stream << "\nNo assertions in section";
  12941. else
  12942. stream << "\nNo assertions in test case";
  12943. stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl;
  12944. }
  12945. if (m_config->showDurations() == ShowDurations::Always) {
  12946. stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  12947. }
  12948. if (m_headerPrinted) {
  12949. m_headerPrinted = false;
  12950. }
  12951. StreamingReporterBase::sectionEnded(_sectionStats);
  12952. }
  12953. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  12954. void ConsoleReporter::benchmarkPreparing(std::string const& name) {
  12955. lazyPrintWithoutClosingBenchmarkTable();
  12956. auto nameCol = Column(name).width(static_cast<std::size_t>(m_tablePrinter->columnInfos()[0].width - 2));
  12957. bool firstLine = true;
  12958. for (auto line : nameCol) {
  12959. if (!firstLine)
  12960. (*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak();
  12961. else
  12962. firstLine = false;
  12963. (*m_tablePrinter) << line << ColumnBreak();
  12964. }
  12965. }
  12966. void ConsoleReporter::benchmarkStarting(BenchmarkInfo const& info) {
  12967. (*m_tablePrinter) << info.samples << ColumnBreak()
  12968. << info.iterations << ColumnBreak()
  12969. << Duration(info.estimatedDuration) << ColumnBreak();
  12970. }
  12971. void ConsoleReporter::benchmarkEnded(BenchmarkStats<> const& stats) {
  12972. (*m_tablePrinter) << ColumnBreak()
  12973. << Duration(stats.mean.point.count()) << ColumnBreak()
  12974. << Duration(stats.mean.lower_bound.count()) << ColumnBreak()
  12975. << Duration(stats.mean.upper_bound.count()) << ColumnBreak() << ColumnBreak()
  12976. << Duration(stats.standardDeviation.point.count()) << ColumnBreak()
  12977. << Duration(stats.standardDeviation.lower_bound.count()) << ColumnBreak()
  12978. << Duration(stats.standardDeviation.upper_bound.count()) << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak();
  12979. }
  12980. void ConsoleReporter::benchmarkFailed(std::string const& error) {
  12981. Colour colour(Colour::Red);
  12982. (*m_tablePrinter)
  12983. << "Benchmark failed (" << error << ")"
  12984. << ColumnBreak() << RowBreak();
  12985. }
  12986. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  12987. void ConsoleReporter::testCaseEnded(TestCaseStats const& _testCaseStats) {
  12988. m_tablePrinter->close();
  12989. StreamingReporterBase::testCaseEnded(_testCaseStats);
  12990. m_headerPrinted = false;
  12991. }
  12992. void ConsoleReporter::testGroupEnded(TestGroupStats const& _testGroupStats) {
  12993. if (currentGroupInfo.used) {
  12994. printSummaryDivider();
  12995. stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n";
  12996. printTotals(_testGroupStats.totals);
  12997. stream << '\n' << std::endl;
  12998. }
  12999. StreamingReporterBase::testGroupEnded(_testGroupStats);
  13000. }
  13001. void ConsoleReporter::testRunEnded(TestRunStats const& _testRunStats) {
  13002. printTotalsDivider(_testRunStats.totals);
  13003. printTotals(_testRunStats.totals);
  13004. stream << std::endl;
  13005. StreamingReporterBase::testRunEnded(_testRunStats);
  13006. }
  13007. void ConsoleReporter::testRunStarting(TestRunInfo const& _testInfo) {
  13008. StreamingReporterBase::testRunStarting(_testInfo);
  13009. printTestFilters();
  13010. }
  13011. void ConsoleReporter::lazyPrint() {
  13012. m_tablePrinter->close();
  13013. lazyPrintWithoutClosingBenchmarkTable();
  13014. }
  13015. void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() {
  13016. if (!currentTestRunInfo.used)
  13017. lazyPrintRunInfo();
  13018. if (!currentGroupInfo.used)
  13019. lazyPrintGroupInfo();
  13020. if (!m_headerPrinted) {
  13021. printTestCaseAndSectionHeader();
  13022. m_headerPrinted = true;
  13023. }
  13024. }
  13025. void ConsoleReporter::lazyPrintRunInfo() {
  13026. stream << '\n' << getLineOfChars<'~'>() << '\n';
  13027. Colour colour(Colour::SecondaryText);
  13028. stream << currentTestRunInfo->name
  13029. << " is a Catch v" << libraryVersion() << " host application.\n"
  13030. << "Run with -? for options\n\n";
  13031. if (m_config->rngSeed() != 0)
  13032. stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n";
  13033. currentTestRunInfo.used = true;
  13034. }
  13035. void ConsoleReporter::lazyPrintGroupInfo() {
  13036. if (!currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1) {
  13037. printClosedHeader("Group: " + currentGroupInfo->name);
  13038. currentGroupInfo.used = true;
  13039. }
  13040. }
  13041. void ConsoleReporter::printTestCaseAndSectionHeader() {
  13042. assert(!m_sectionStack.empty());
  13043. printOpenHeader(currentTestCaseInfo->name);
  13044. if (m_sectionStack.size() > 1) {
  13045. Colour colourGuard(Colour::Headers);
  13046. auto
  13047. it = m_sectionStack.begin() + 1, // Skip first section (test case)
  13048. itEnd = m_sectionStack.end();
  13049. for (; it != itEnd; ++it)
  13050. printHeaderString(it->name, 2);
  13051. }
  13052. SourceLineInfo lineInfo = m_sectionStack.back().lineInfo;
  13053. if (!lineInfo.empty()) {
  13054. stream << getLineOfChars<'-'>() << '\n';
  13055. Colour colourGuard(Colour::FileName);
  13056. stream << lineInfo << '\n';
  13057. }
  13058. stream << getLineOfChars<'.'>() << '\n' << std::endl;
  13059. }
  13060. void ConsoleReporter::printClosedHeader(std::string const& _name) {
  13061. printOpenHeader(_name);
  13062. stream << getLineOfChars<'.'>() << '\n';
  13063. }
  13064. void ConsoleReporter::printOpenHeader(std::string const& _name) {
  13065. stream << getLineOfChars<'-'>() << '\n';
  13066. {
  13067. Colour colourGuard(Colour::Headers);
  13068. printHeaderString(_name);
  13069. }
  13070. }
  13071. // if string has a : in first line will set indent to follow it on
  13072. // subsequent lines
  13073. void ConsoleReporter::printHeaderString(std::string const& _string, std::size_t indent) {
  13074. std::size_t i = _string.find(": ");
  13075. if (i != std::string::npos)
  13076. i += 2;
  13077. else
  13078. i = 0;
  13079. stream << Column(_string).indent(indent + i).initialIndent(indent) << '\n';
  13080. }
  13081. struct SummaryColumn {
  13082. SummaryColumn( std::string _label, Colour::Code _colour )
  13083. : label( std::move( _label ) ),
  13084. colour( _colour ) {}
  13085. SummaryColumn addRow( std::size_t count ) {
  13086. ReusableStringStream rss;
  13087. rss << count;
  13088. std::string row = rss.str();
  13089. for (auto& oldRow : rows) {
  13090. while (oldRow.size() < row.size())
  13091. oldRow = ' ' + oldRow;
  13092. while (oldRow.size() > row.size())
  13093. row = ' ' + row;
  13094. }
  13095. rows.push_back(row);
  13096. return *this;
  13097. }
  13098. std::string label;
  13099. Colour::Code colour;
  13100. std::vector<std::string> rows;
  13101. };
  13102. void ConsoleReporter::printTotals( Totals const& totals ) {
  13103. if (totals.testCases.total() == 0) {
  13104. stream << Colour(Colour::Warning) << "No tests ran\n";
  13105. } else if (totals.assertions.total() > 0 && totals.testCases.allPassed()) {
  13106. stream << Colour(Colour::ResultSuccess) << "All tests passed";
  13107. stream << " ("
  13108. << pluralise(totals.assertions.passed, "assertion") << " in "
  13109. << pluralise(totals.testCases.passed, "test case") << ')'
  13110. << '\n';
  13111. } else {
  13112. std::vector<SummaryColumn> columns;
  13113. columns.push_back(SummaryColumn("", Colour::None)
  13114. .addRow(totals.testCases.total())
  13115. .addRow(totals.assertions.total()));
  13116. columns.push_back(SummaryColumn("passed", Colour::Success)
  13117. .addRow(totals.testCases.passed)
  13118. .addRow(totals.assertions.passed));
  13119. columns.push_back(SummaryColumn("failed", Colour::ResultError)
  13120. .addRow(totals.testCases.failed)
  13121. .addRow(totals.assertions.failed));
  13122. columns.push_back(SummaryColumn("failed as expected", Colour::ResultExpectedFailure)
  13123. .addRow(totals.testCases.failedButOk)
  13124. .addRow(totals.assertions.failedButOk));
  13125. printSummaryRow("test cases", columns, 0);
  13126. printSummaryRow("assertions", columns, 1);
  13127. }
  13128. }
  13129. void ConsoleReporter::printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row) {
  13130. for (auto col : cols) {
  13131. std::string value = col.rows[row];
  13132. if (col.label.empty()) {
  13133. stream << label << ": ";
  13134. if (value != "0")
  13135. stream << value;
  13136. else
  13137. stream << Colour(Colour::Warning) << "- none -";
  13138. } else if (value != "0") {
  13139. stream << Colour(Colour::LightGrey) << " | ";
  13140. stream << Colour(col.colour)
  13141. << value << ' ' << col.label;
  13142. }
  13143. }
  13144. stream << '\n';
  13145. }
  13146. void ConsoleReporter::printTotalsDivider(Totals const& totals) {
  13147. if (totals.testCases.total() > 0) {
  13148. std::size_t failedRatio = makeRatio(totals.testCases.failed, totals.testCases.total());
  13149. std::size_t failedButOkRatio = makeRatio(totals.testCases.failedButOk, totals.testCases.total());
  13150. std::size_t passedRatio = makeRatio(totals.testCases.passed, totals.testCases.total());
  13151. while (failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1)
  13152. findMax(failedRatio, failedButOkRatio, passedRatio)++;
  13153. while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1)
  13154. findMax(failedRatio, failedButOkRatio, passedRatio)--;
  13155. stream << Colour(Colour::Error) << std::string(failedRatio, '=');
  13156. stream << Colour(Colour::ResultExpectedFailure) << std::string(failedButOkRatio, '=');
  13157. if (totals.testCases.allPassed())
  13158. stream << Colour(Colour::ResultSuccess) << std::string(passedRatio, '=');
  13159. else
  13160. stream << Colour(Colour::Success) << std::string(passedRatio, '=');
  13161. } else {
  13162. stream << Colour(Colour::Warning) << std::string(CATCH_CONFIG_CONSOLE_WIDTH - 1, '=');
  13163. }
  13164. stream << '\n';
  13165. }
  13166. void ConsoleReporter::printSummaryDivider() {
  13167. stream << getLineOfChars<'-'>() << '\n';
  13168. }
  13169. void ConsoleReporter::printTestFilters() {
  13170. if (m_config->testSpec().hasFilters())
  13171. stream << Colour(Colour::BrightYellow) << "Filters: " << serializeFilters( m_config->getTestsOrTags() ) << '\n';
  13172. }
  13173. CATCH_REGISTER_REPORTER("console", ConsoleReporter)
  13174. } // end namespace Catch
  13175. #if defined(_MSC_VER)
  13176. #pragma warning(pop)
  13177. #endif
  13178. #if defined(__clang__)
  13179. # pragma clang diagnostic pop
  13180. #endif
  13181. // end catch_reporter_console.cpp
  13182. // start catch_reporter_junit.cpp
  13183. #include <cassert>
  13184. #include <sstream>
  13185. #include <ctime>
  13186. #include <algorithm>
  13187. namespace Catch {
  13188. namespace {
  13189. std::string getCurrentTimestamp() {
  13190. // Beware, this is not reentrant because of backward compatibility issues
  13191. // Also, UTC only, again because of backward compatibility (%z is C++11)
  13192. time_t rawtime;
  13193. std::time(&rawtime);
  13194. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  13195. #ifdef _MSC_VER
  13196. std::tm timeInfo = {};
  13197. gmtime_s(&timeInfo, &rawtime);
  13198. #else
  13199. std::tm* timeInfo;
  13200. timeInfo = std::gmtime(&rawtime);
  13201. #endif
  13202. char timeStamp[timeStampSize];
  13203. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  13204. #ifdef _MSC_VER
  13205. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  13206. #else
  13207. std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
  13208. #endif
  13209. return std::string(timeStamp);
  13210. }
  13211. std::string fileNameTag(const std::vector<std::string> &tags) {
  13212. auto it = std::find_if(begin(tags),
  13213. end(tags),
  13214. [] (std::string const& tag) {return tag.front() == '#'; });
  13215. if (it != tags.end())
  13216. return it->substr(1);
  13217. return std::string();
  13218. }
  13219. } // anonymous namespace
  13220. JunitReporter::JunitReporter( ReporterConfig const& _config )
  13221. : CumulativeReporterBase( _config ),
  13222. xml( _config.stream() )
  13223. {
  13224. m_reporterPrefs.shouldRedirectStdOut = true;
  13225. m_reporterPrefs.shouldReportAllAssertions = true;
  13226. }
  13227. JunitReporter::~JunitReporter() {}
  13228. std::string JunitReporter::getDescription() {
  13229. return "Reports test results in an XML format that looks like Ant's junitreport target";
  13230. }
  13231. void JunitReporter::noMatchingTestCases( std::string const& /*spec*/ ) {}
  13232. void JunitReporter::testRunStarting( TestRunInfo const& runInfo ) {
  13233. CumulativeReporterBase::testRunStarting( runInfo );
  13234. xml.startElement( "testsuites" );
  13235. }
  13236. void JunitReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  13237. suiteTimer.start();
  13238. stdOutForSuite.clear();
  13239. stdErrForSuite.clear();
  13240. unexpectedExceptions = 0;
  13241. CumulativeReporterBase::testGroupStarting( groupInfo );
  13242. }
  13243. void JunitReporter::testCaseStarting( TestCaseInfo const& testCaseInfo ) {
  13244. m_okToFail = testCaseInfo.okToFail();
  13245. }
  13246. bool JunitReporter::assertionEnded( AssertionStats const& assertionStats ) {
  13247. if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail )
  13248. unexpectedExceptions++;
  13249. return CumulativeReporterBase::assertionEnded( assertionStats );
  13250. }
  13251. void JunitReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  13252. stdOutForSuite += testCaseStats.stdOut;
  13253. stdErrForSuite += testCaseStats.stdErr;
  13254. CumulativeReporterBase::testCaseEnded( testCaseStats );
  13255. }
  13256. void JunitReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  13257. double suiteTime = suiteTimer.getElapsedSeconds();
  13258. CumulativeReporterBase::testGroupEnded( testGroupStats );
  13259. writeGroup( *m_testGroups.back(), suiteTime );
  13260. }
  13261. void JunitReporter::testRunEndedCumulative() {
  13262. xml.endElement();
  13263. }
  13264. void JunitReporter::writeGroup( TestGroupNode const& groupNode, double suiteTime ) {
  13265. XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" );
  13266. TestGroupStats const& stats = groupNode.value;
  13267. xml.writeAttribute( "name", stats.groupInfo.name );
  13268. xml.writeAttribute( "errors", unexpectedExceptions );
  13269. xml.writeAttribute( "failures", stats.totals.assertions.failed-unexpectedExceptions );
  13270. xml.writeAttribute( "tests", stats.totals.assertions.total() );
  13271. xml.writeAttribute( "hostname", "tbd" ); // !TBD
  13272. if( m_config->showDurations() == ShowDurations::Never )
  13273. xml.writeAttribute( "time", "" );
  13274. else
  13275. xml.writeAttribute( "time", suiteTime );
  13276. xml.writeAttribute( "timestamp", getCurrentTimestamp() );
  13277. // Write properties if there are any
  13278. if (m_config->hasTestFilters() || m_config->rngSeed() != 0) {
  13279. auto properties = xml.scopedElement("properties");
  13280. if (m_config->hasTestFilters()) {
  13281. xml.scopedElement("property")
  13282. .writeAttribute("name", "filters")
  13283. .writeAttribute("value", serializeFilters(m_config->getTestsOrTags()));
  13284. }
  13285. if (m_config->rngSeed() != 0) {
  13286. xml.scopedElement("property")
  13287. .writeAttribute("name", "random-seed")
  13288. .writeAttribute("value", m_config->rngSeed());
  13289. }
  13290. }
  13291. // Write test cases
  13292. for( auto const& child : groupNode.children )
  13293. writeTestCase( *child );
  13294. xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite ), false );
  13295. xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite ), false );
  13296. }
  13297. void JunitReporter::writeTestCase( TestCaseNode const& testCaseNode ) {
  13298. TestCaseStats const& stats = testCaseNode.value;
  13299. // All test cases have exactly one section - which represents the
  13300. // test case itself. That section may have 0-n nested sections
  13301. assert( testCaseNode.children.size() == 1 );
  13302. SectionNode const& rootSection = *testCaseNode.children.front();
  13303. std::string className = stats.testInfo.className;
  13304. if( className.empty() ) {
  13305. className = fileNameTag(stats.testInfo.tags);
  13306. if ( className.empty() )
  13307. className = "global";
  13308. }
  13309. if ( !m_config->name().empty() )
  13310. className = m_config->name() + "." + className;
  13311. writeSection( className, "", rootSection );
  13312. }
  13313. void JunitReporter::writeSection( std::string const& className,
  13314. std::string const& rootName,
  13315. SectionNode const& sectionNode ) {
  13316. std::string name = trim( sectionNode.stats.sectionInfo.name );
  13317. if( !rootName.empty() )
  13318. name = rootName + '/' + name;
  13319. if( !sectionNode.assertions.empty() ||
  13320. !sectionNode.stdOut.empty() ||
  13321. !sectionNode.stdErr.empty() ) {
  13322. XmlWriter::ScopedElement e = xml.scopedElement( "testcase" );
  13323. if( className.empty() ) {
  13324. xml.writeAttribute( "classname", name );
  13325. xml.writeAttribute( "name", "root" );
  13326. }
  13327. else {
  13328. xml.writeAttribute( "classname", className );
  13329. xml.writeAttribute( "name", name );
  13330. }
  13331. xml.writeAttribute( "time", ::Catch::Detail::stringify( sectionNode.stats.durationInSeconds ) );
  13332. writeAssertions( sectionNode );
  13333. if( !sectionNode.stdOut.empty() )
  13334. xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), false );
  13335. if( !sectionNode.stdErr.empty() )
  13336. xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), false );
  13337. }
  13338. for( auto const& childNode : sectionNode.childSections )
  13339. if( className.empty() )
  13340. writeSection( name, "", *childNode );
  13341. else
  13342. writeSection( className, name, *childNode );
  13343. }
  13344. void JunitReporter::writeAssertions( SectionNode const& sectionNode ) {
  13345. for( auto const& assertion : sectionNode.assertions )
  13346. writeAssertion( assertion );
  13347. }
  13348. void JunitReporter::writeAssertion( AssertionStats const& stats ) {
  13349. AssertionResult const& result = stats.assertionResult;
  13350. if( !result.isOk() ) {
  13351. std::string elementName;
  13352. switch( result.getResultType() ) {
  13353. case ResultWas::ThrewException:
  13354. case ResultWas::FatalErrorCondition:
  13355. elementName = "error";
  13356. break;
  13357. case ResultWas::ExplicitFailure:
  13358. elementName = "failure";
  13359. break;
  13360. case ResultWas::ExpressionFailed:
  13361. elementName = "failure";
  13362. break;
  13363. case ResultWas::DidntThrowException:
  13364. elementName = "failure";
  13365. break;
  13366. // We should never see these here:
  13367. case ResultWas::Info:
  13368. case ResultWas::Warning:
  13369. case ResultWas::Ok:
  13370. case ResultWas::Unknown:
  13371. case ResultWas::FailureBit:
  13372. case ResultWas::Exception:
  13373. elementName = "internalError";
  13374. break;
  13375. }
  13376. XmlWriter::ScopedElement e = xml.scopedElement( elementName );
  13377. xml.writeAttribute( "message", result.getExpandedExpression() );
  13378. xml.writeAttribute( "type", result.getTestMacroName() );
  13379. ReusableStringStream rss;
  13380. if( !result.getMessage().empty() )
  13381. rss << result.getMessage() << '\n';
  13382. for( auto const& msg : stats.infoMessages )
  13383. if( msg.type == ResultWas::Info )
  13384. rss << msg.message << '\n';
  13385. rss << "at " << result.getSourceInfo();
  13386. xml.writeText( rss.str(), false );
  13387. }
  13388. }
  13389. CATCH_REGISTER_REPORTER( "junit", JunitReporter )
  13390. } // end namespace Catch
  13391. // end catch_reporter_junit.cpp
  13392. // start catch_reporter_listening.cpp
  13393. #include <cassert>
  13394. namespace Catch {
  13395. ListeningReporter::ListeningReporter() {
  13396. // We will assume that listeners will always want all assertions
  13397. m_preferences.shouldReportAllAssertions = true;
  13398. }
  13399. void ListeningReporter::addListener( IStreamingReporterPtr&& listener ) {
  13400. m_listeners.push_back( std::move( listener ) );
  13401. }
  13402. void ListeningReporter::addReporter(IStreamingReporterPtr&& reporter) {
  13403. assert(!m_reporter && "Listening reporter can wrap only 1 real reporter");
  13404. m_reporter = std::move( reporter );
  13405. m_preferences.shouldRedirectStdOut = m_reporter->getPreferences().shouldRedirectStdOut;
  13406. }
  13407. ReporterPreferences ListeningReporter::getPreferences() const {
  13408. return m_preferences;
  13409. }
  13410. std::set<Verbosity> ListeningReporter::getSupportedVerbosities() {
  13411. return std::set<Verbosity>{ };
  13412. }
  13413. void ListeningReporter::noMatchingTestCases( std::string const& spec ) {
  13414. for ( auto const& listener : m_listeners ) {
  13415. listener->noMatchingTestCases( spec );
  13416. }
  13417. m_reporter->noMatchingTestCases( spec );
  13418. }
  13419. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  13420. void ListeningReporter::benchmarkPreparing( std::string const& name ) {
  13421. for (auto const& listener : m_listeners) {
  13422. listener->benchmarkPreparing(name);
  13423. }
  13424. m_reporter->benchmarkPreparing(name);
  13425. }
  13426. void ListeningReporter::benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) {
  13427. for ( auto const& listener : m_listeners ) {
  13428. listener->benchmarkStarting( benchmarkInfo );
  13429. }
  13430. m_reporter->benchmarkStarting( benchmarkInfo );
  13431. }
  13432. void ListeningReporter::benchmarkEnded( BenchmarkStats<> const& benchmarkStats ) {
  13433. for ( auto const& listener : m_listeners ) {
  13434. listener->benchmarkEnded( benchmarkStats );
  13435. }
  13436. m_reporter->benchmarkEnded( benchmarkStats );
  13437. }
  13438. void ListeningReporter::benchmarkFailed( std::string const& error ) {
  13439. for (auto const& listener : m_listeners) {
  13440. listener->benchmarkFailed(error);
  13441. }
  13442. m_reporter->benchmarkFailed(error);
  13443. }
  13444. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  13445. void ListeningReporter::testRunStarting( TestRunInfo const& testRunInfo ) {
  13446. for ( auto const& listener : m_listeners ) {
  13447. listener->testRunStarting( testRunInfo );
  13448. }
  13449. m_reporter->testRunStarting( testRunInfo );
  13450. }
  13451. void ListeningReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  13452. for ( auto const& listener : m_listeners ) {
  13453. listener->testGroupStarting( groupInfo );
  13454. }
  13455. m_reporter->testGroupStarting( groupInfo );
  13456. }
  13457. void ListeningReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
  13458. for ( auto const& listener : m_listeners ) {
  13459. listener->testCaseStarting( testInfo );
  13460. }
  13461. m_reporter->testCaseStarting( testInfo );
  13462. }
  13463. void ListeningReporter::sectionStarting( SectionInfo const& sectionInfo ) {
  13464. for ( auto const& listener : m_listeners ) {
  13465. listener->sectionStarting( sectionInfo );
  13466. }
  13467. m_reporter->sectionStarting( sectionInfo );
  13468. }
  13469. void ListeningReporter::assertionStarting( AssertionInfo const& assertionInfo ) {
  13470. for ( auto const& listener : m_listeners ) {
  13471. listener->assertionStarting( assertionInfo );
  13472. }
  13473. m_reporter->assertionStarting( assertionInfo );
  13474. }
  13475. // The return value indicates if the messages buffer should be cleared:
  13476. bool ListeningReporter::assertionEnded( AssertionStats const& assertionStats ) {
  13477. for( auto const& listener : m_listeners ) {
  13478. static_cast<void>( listener->assertionEnded( assertionStats ) );
  13479. }
  13480. return m_reporter->assertionEnded( assertionStats );
  13481. }
  13482. void ListeningReporter::sectionEnded( SectionStats const& sectionStats ) {
  13483. for ( auto const& listener : m_listeners ) {
  13484. listener->sectionEnded( sectionStats );
  13485. }
  13486. m_reporter->sectionEnded( sectionStats );
  13487. }
  13488. void ListeningReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  13489. for ( auto const& listener : m_listeners ) {
  13490. listener->testCaseEnded( testCaseStats );
  13491. }
  13492. m_reporter->testCaseEnded( testCaseStats );
  13493. }
  13494. void ListeningReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  13495. for ( auto const& listener : m_listeners ) {
  13496. listener->testGroupEnded( testGroupStats );
  13497. }
  13498. m_reporter->testGroupEnded( testGroupStats );
  13499. }
  13500. void ListeningReporter::testRunEnded( TestRunStats const& testRunStats ) {
  13501. for ( auto const& listener : m_listeners ) {
  13502. listener->testRunEnded( testRunStats );
  13503. }
  13504. m_reporter->testRunEnded( testRunStats );
  13505. }
  13506. void ListeningReporter::skipTest( TestCaseInfo const& testInfo ) {
  13507. for ( auto const& listener : m_listeners ) {
  13508. listener->skipTest( testInfo );
  13509. }
  13510. m_reporter->skipTest( testInfo );
  13511. }
  13512. bool ListeningReporter::isMulti() const {
  13513. return true;
  13514. }
  13515. } // end namespace Catch
  13516. // end catch_reporter_listening.cpp
  13517. // start catch_reporter_xml.cpp
  13518. #if defined(_MSC_VER)
  13519. #pragma warning(push)
  13520. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  13521. // Note that 4062 (not all labels are handled
  13522. // and default is missing) is enabled
  13523. #endif
  13524. namespace Catch {
  13525. XmlReporter::XmlReporter( ReporterConfig const& _config )
  13526. : StreamingReporterBase( _config ),
  13527. m_xml(_config.stream())
  13528. {
  13529. m_reporterPrefs.shouldRedirectStdOut = true;
  13530. m_reporterPrefs.shouldReportAllAssertions = true;
  13531. }
  13532. XmlReporter::~XmlReporter() = default;
  13533. std::string XmlReporter::getDescription() {
  13534. return "Reports test results as an XML document";
  13535. }
  13536. std::string XmlReporter::getStylesheetRef() const {
  13537. return std::string();
  13538. }
  13539. void XmlReporter::writeSourceInfo( SourceLineInfo const& sourceInfo ) {
  13540. m_xml
  13541. .writeAttribute( "filename", sourceInfo.file )
  13542. .writeAttribute( "line", sourceInfo.line );
  13543. }
  13544. void XmlReporter::noMatchingTestCases( std::string const& s ) {
  13545. StreamingReporterBase::noMatchingTestCases( s );
  13546. }
  13547. void XmlReporter::testRunStarting( TestRunInfo const& testInfo ) {
  13548. StreamingReporterBase::testRunStarting( testInfo );
  13549. std::string stylesheetRef = getStylesheetRef();
  13550. if( !stylesheetRef.empty() )
  13551. m_xml.writeStylesheetRef( stylesheetRef );
  13552. m_xml.startElement( "Catch" );
  13553. if( !m_config->name().empty() )
  13554. m_xml.writeAttribute( "name", m_config->name() );
  13555. if (m_config->testSpec().hasFilters())
  13556. m_xml.writeAttribute( "filters", serializeFilters( m_config->getTestsOrTags() ) );
  13557. if( m_config->rngSeed() != 0 )
  13558. m_xml.scopedElement( "Randomness" )
  13559. .writeAttribute( "seed", m_config->rngSeed() );
  13560. }
  13561. void XmlReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  13562. StreamingReporterBase::testGroupStarting( groupInfo );
  13563. m_xml.startElement( "Group" )
  13564. .writeAttribute( "name", groupInfo.name );
  13565. }
  13566. void XmlReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
  13567. StreamingReporterBase::testCaseStarting(testInfo);
  13568. m_xml.startElement( "TestCase" )
  13569. .writeAttribute( "name", trim( testInfo.name ) )
  13570. .writeAttribute( "description", testInfo.description )
  13571. .writeAttribute( "tags", testInfo.tagsAsString() );
  13572. writeSourceInfo( testInfo.lineInfo );
  13573. if ( m_config->showDurations() == ShowDurations::Always )
  13574. m_testCaseTimer.start();
  13575. m_xml.ensureTagClosed();
  13576. }
  13577. void XmlReporter::sectionStarting( SectionInfo const& sectionInfo ) {
  13578. StreamingReporterBase::sectionStarting( sectionInfo );
  13579. if( m_sectionDepth++ > 0 ) {
  13580. m_xml.startElement( "Section" )
  13581. .writeAttribute( "name", trim( sectionInfo.name ) );
  13582. writeSourceInfo( sectionInfo.lineInfo );
  13583. m_xml.ensureTagClosed();
  13584. }
  13585. }
  13586. void XmlReporter::assertionStarting( AssertionInfo const& ) { }
  13587. bool XmlReporter::assertionEnded( AssertionStats const& assertionStats ) {
  13588. AssertionResult const& result = assertionStats.assertionResult;
  13589. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  13590. if( includeResults || result.getResultType() == ResultWas::Warning ) {
  13591. // Print any info messages in <Info> tags.
  13592. for( auto const& msg : assertionStats.infoMessages ) {
  13593. if( msg.type == ResultWas::Info && includeResults ) {
  13594. m_xml.scopedElement( "Info" )
  13595. .writeText( msg.message );
  13596. } else if ( msg.type == ResultWas::Warning ) {
  13597. m_xml.scopedElement( "Warning" )
  13598. .writeText( msg.message );
  13599. }
  13600. }
  13601. }
  13602. // Drop out if result was successful but we're not printing them.
  13603. if( !includeResults && result.getResultType() != ResultWas::Warning )
  13604. return true;
  13605. // Print the expression if there is one.
  13606. if( result.hasExpression() ) {
  13607. m_xml.startElement( "Expression" )
  13608. .writeAttribute( "success", result.succeeded() )
  13609. .writeAttribute( "type", result.getTestMacroName() );
  13610. writeSourceInfo( result.getSourceInfo() );
  13611. m_xml.scopedElement( "Original" )
  13612. .writeText( result.getExpression() );
  13613. m_xml.scopedElement( "Expanded" )
  13614. .writeText( result.getExpandedExpression() );
  13615. }
  13616. // And... Print a result applicable to each result type.
  13617. switch( result.getResultType() ) {
  13618. case ResultWas::ThrewException:
  13619. m_xml.startElement( "Exception" );
  13620. writeSourceInfo( result.getSourceInfo() );
  13621. m_xml.writeText( result.getMessage() );
  13622. m_xml.endElement();
  13623. break;
  13624. case ResultWas::FatalErrorCondition:
  13625. m_xml.startElement( "FatalErrorCondition" );
  13626. writeSourceInfo( result.getSourceInfo() );
  13627. m_xml.writeText( result.getMessage() );
  13628. m_xml.endElement();
  13629. break;
  13630. case ResultWas::Info:
  13631. m_xml.scopedElement( "Info" )
  13632. .writeText( result.getMessage() );
  13633. break;
  13634. case ResultWas::Warning:
  13635. // Warning will already have been written
  13636. break;
  13637. case ResultWas::ExplicitFailure:
  13638. m_xml.startElement( "Failure" );
  13639. writeSourceInfo( result.getSourceInfo() );
  13640. m_xml.writeText( result.getMessage() );
  13641. m_xml.endElement();
  13642. break;
  13643. default:
  13644. break;
  13645. }
  13646. if( result.hasExpression() )
  13647. m_xml.endElement();
  13648. return true;
  13649. }
  13650. void XmlReporter::sectionEnded( SectionStats const& sectionStats ) {
  13651. StreamingReporterBase::sectionEnded( sectionStats );
  13652. if( --m_sectionDepth > 0 ) {
  13653. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResults" );
  13654. e.writeAttribute( "successes", sectionStats.assertions.passed );
  13655. e.writeAttribute( "failures", sectionStats.assertions.failed );
  13656. e.writeAttribute( "expectedFailures", sectionStats.assertions.failedButOk );
  13657. if ( m_config->showDurations() == ShowDurations::Always )
  13658. e.writeAttribute( "durationInSeconds", sectionStats.durationInSeconds );
  13659. m_xml.endElement();
  13660. }
  13661. }
  13662. void XmlReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  13663. StreamingReporterBase::testCaseEnded( testCaseStats );
  13664. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResult" );
  13665. e.writeAttribute( "success", testCaseStats.totals.assertions.allOk() );
  13666. if ( m_config->showDurations() == ShowDurations::Always )
  13667. e.writeAttribute( "durationInSeconds", m_testCaseTimer.getElapsedSeconds() );
  13668. if( !testCaseStats.stdOut.empty() )
  13669. m_xml.scopedElement( "StdOut" ).writeText( trim( testCaseStats.stdOut ), false );
  13670. if( !testCaseStats.stdErr.empty() )
  13671. m_xml.scopedElement( "StdErr" ).writeText( trim( testCaseStats.stdErr ), false );
  13672. m_xml.endElement();
  13673. }
  13674. void XmlReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  13675. StreamingReporterBase::testGroupEnded( testGroupStats );
  13676. // TODO: Check testGroupStats.aborting and act accordingly.
  13677. m_xml.scopedElement( "OverallResults" )
  13678. .writeAttribute( "successes", testGroupStats.totals.assertions.passed )
  13679. .writeAttribute( "failures", testGroupStats.totals.assertions.failed )
  13680. .writeAttribute( "expectedFailures", testGroupStats.totals.assertions.failedButOk );
  13681. m_xml.endElement();
  13682. }
  13683. void XmlReporter::testRunEnded( TestRunStats const& testRunStats ) {
  13684. StreamingReporterBase::testRunEnded( testRunStats );
  13685. m_xml.scopedElement( "OverallResults" )
  13686. .writeAttribute( "successes", testRunStats.totals.assertions.passed )
  13687. .writeAttribute( "failures", testRunStats.totals.assertions.failed )
  13688. .writeAttribute( "expectedFailures", testRunStats.totals.assertions.failedButOk );
  13689. m_xml.endElement();
  13690. }
  13691. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  13692. void XmlReporter::benchmarkPreparing(std::string const& name) {
  13693. m_xml.startElement("BenchmarkResults")
  13694. .writeAttribute("name", name);
  13695. }
  13696. void XmlReporter::benchmarkStarting(BenchmarkInfo const &info) {
  13697. m_xml.writeAttribute("samples", info.samples)
  13698. .writeAttribute("resamples", info.resamples)
  13699. .writeAttribute("iterations", info.iterations)
  13700. .writeAttribute("clockResolution", static_cast<uint64_t>(info.clockResolution))
  13701. .writeAttribute("estimatedDuration", static_cast<uint64_t>(info.estimatedDuration))
  13702. .writeComment("All values in nano seconds");
  13703. }
  13704. void XmlReporter::benchmarkEnded(BenchmarkStats<> const& benchmarkStats) {
  13705. m_xml.startElement("mean")
  13706. .writeAttribute("value", static_cast<uint64_t>(benchmarkStats.mean.point.count()))
  13707. .writeAttribute("lowerBound", static_cast<uint64_t>(benchmarkStats.mean.lower_bound.count()))
  13708. .writeAttribute("upperBound", static_cast<uint64_t>(benchmarkStats.mean.upper_bound.count()))
  13709. .writeAttribute("ci", benchmarkStats.mean.confidence_interval);
  13710. m_xml.endElement();
  13711. m_xml.startElement("standardDeviation")
  13712. .writeAttribute("value", benchmarkStats.standardDeviation.point.count())
  13713. .writeAttribute("lowerBound", benchmarkStats.standardDeviation.lower_bound.count())
  13714. .writeAttribute("upperBound", benchmarkStats.standardDeviation.upper_bound.count())
  13715. .writeAttribute("ci", benchmarkStats.standardDeviation.confidence_interval);
  13716. m_xml.endElement();
  13717. m_xml.startElement("outliers")
  13718. .writeAttribute("variance", benchmarkStats.outlierVariance)
  13719. .writeAttribute("lowMild", benchmarkStats.outliers.low_mild)
  13720. .writeAttribute("lowSevere", benchmarkStats.outliers.low_severe)
  13721. .writeAttribute("highMild", benchmarkStats.outliers.high_mild)
  13722. .writeAttribute("highSevere", benchmarkStats.outliers.high_severe);
  13723. m_xml.endElement();
  13724. m_xml.endElement();
  13725. }
  13726. void XmlReporter::benchmarkFailed(std::string const &error) {
  13727. m_xml.scopedElement("failed").
  13728. writeAttribute("message", error);
  13729. m_xml.endElement();
  13730. }
  13731. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  13732. CATCH_REGISTER_REPORTER( "xml", XmlReporter )
  13733. } // end namespace Catch
  13734. #if defined(_MSC_VER)
  13735. #pragma warning(pop)
  13736. #endif
  13737. // end catch_reporter_xml.cpp
  13738. namespace Catch {
  13739. LeakDetector leakDetector;
  13740. }
  13741. #ifdef __clang__
  13742. #pragma clang diagnostic pop
  13743. #endif
  13744. // end catch_impl.hpp
  13745. #endif
  13746. #ifdef CATCH_CONFIG_MAIN
  13747. // start catch_default_main.hpp
  13748. #ifndef __OBJC__
  13749. #if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN)
  13750. // Standard C/C++ Win32 Unicode wmain entry point
  13751. extern "C" int wmain (int argc, wchar_t * argv[], wchar_t * []) {
  13752. #else
  13753. // Standard C/C++ main entry point
  13754. int main (int argc, char * argv[]) {
  13755. #endif
  13756. return Catch::Session().run( argc, argv );
  13757. }
  13758. #else // __OBJC__
  13759. // Objective-C entry point
  13760. int main (int argc, char * const argv[]) {
  13761. #if !CATCH_ARC_ENABLED
  13762. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  13763. #endif
  13764. Catch::registerTestMethods();
  13765. int result = Catch::Session().run( argc, (char**)argv );
  13766. #if !CATCH_ARC_ENABLED
  13767. [pool drain];
  13768. #endif
  13769. return result;
  13770. }
  13771. #endif // __OBJC__
  13772. // end catch_default_main.hpp
  13773. #endif
  13774. #if !defined(CATCH_CONFIG_IMPL_ONLY)
  13775. #ifdef CLARA_CONFIG_MAIN_NOT_DEFINED
  13776. # undef CLARA_CONFIG_MAIN
  13777. #endif
  13778. #if !defined(CATCH_CONFIG_DISABLE)
  13779. //////
  13780. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  13781. #ifdef CATCH_CONFIG_PREFIX_ALL
  13782. #define CATCH_REQUIRE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  13783. #define CATCH_REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  13784. #define CATCH_REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  13785. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  13786. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  13787. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13788. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  13789. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  13790. #define CATCH_REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  13791. #define CATCH_CHECK( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13792. #define CATCH_CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  13793. #define CATCH_CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13794. #define CATCH_CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13795. #define CATCH_CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  13796. #define CATCH_CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13797. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  13798. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  13799. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13800. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  13801. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  13802. #define CATCH_CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13803. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13804. #define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  13805. #define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  13806. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  13807. #define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg )
  13808. #define CATCH_UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "CATCH_UNSCOPED_INFO", msg )
  13809. #define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  13810. #define CATCH_CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CATCH_CAPTURE",__VA_ARGS__ )
  13811. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  13812. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13813. #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  13814. #define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  13815. #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  13816. #define CATCH_DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
  13817. #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  13818. #define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13819. #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13820. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  13821. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  13822. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  13823. #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ )
  13824. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13825. #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
  13826. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )
  13827. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ )
  13828. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13829. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
  13830. #else
  13831. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
  13832. #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) )
  13833. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  13834. #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
  13835. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )
  13836. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) )
  13837. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  13838. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
  13839. #endif
  13840. #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
  13841. #define CATCH_STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__ , #__VA_ARGS__ ); CATCH_SUCCEED( #__VA_ARGS__ )
  13842. #define CATCH_STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); CATCH_SUCCEED( #__VA_ARGS__ )
  13843. #else
  13844. #define CATCH_STATIC_REQUIRE( ... ) CATCH_REQUIRE( __VA_ARGS__ )
  13845. #define CATCH_STATIC_REQUIRE_FALSE( ... ) CATCH_REQUIRE_FALSE( __VA_ARGS__ )
  13846. #endif
  13847. // "BDD-style" convenience wrappers
  13848. #define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ )
  13849. #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  13850. #define CATCH_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
  13851. #define CATCH_AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
  13852. #define CATCH_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
  13853. #define CATCH_AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
  13854. #define CATCH_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
  13855. #define CATCH_AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
  13856. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  13857. #define CATCH_BENCHMARK(...) \
  13858. 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__,,))
  13859. #define CATCH_BENCHMARK_ADVANCED(name) \
  13860. INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), name)
  13861. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  13862. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  13863. #else
  13864. #define REQUIRE(...) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  13865. #define REQUIRE_FALSE(...) INTERNAL_CATCH_TEST( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  13866. #define REQUIRE_THROWS(...) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  13867. #define REQUIRE_THROWS_AS(expr, exceptionType) INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  13868. #define REQUIRE_THROWS_WITH(expr, matcher) INTERNAL_CATCH_THROWS_STR_MATCHES( "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  13869. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13870. #define REQUIRE_THROWS_MATCHES(expr, exceptionType, matcher) INTERNAL_CATCH_THROWS_MATCHES( "REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  13871. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  13872. #define REQUIRE_NOTHROW(...) INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  13873. #define CHECK(...) INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13874. #define CHECK_FALSE(...) INTERNAL_CATCH_TEST( "CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  13875. #define CHECKED_IF(...) INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13876. #define CHECKED_ELSE(...) INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13877. #define CHECK_NOFAIL(...) INTERNAL_CATCH_TEST( "CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  13878. #define CHECK_THROWS(...) INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13879. #define CHECK_THROWS_AS(expr, exceptionType) INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  13880. #define CHECK_THROWS_WITH(expr, matcher) INTERNAL_CATCH_THROWS_STR_MATCHES( "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  13881. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13882. #define CHECK_THROWS_MATCHES(expr, exceptionType, matcher) INTERNAL_CATCH_THROWS_MATCHES( "CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  13883. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  13884. #define CHECK_NOTHROW(...) INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13885. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13886. #define CHECK_THAT(arg, matcher) INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  13887. #define REQUIRE_THAT(arg, matcher) INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  13888. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  13889. #define INFO(msg) INTERNAL_CATCH_INFO( "INFO", msg )
  13890. #define UNSCOPED_INFO(msg) INTERNAL_CATCH_UNSCOPED_INFO( "UNSCOPED_INFO", msg )
  13891. #define WARN(msg) INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  13892. #define CAPTURE(...) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CAPTURE",__VA_ARGS__ )
  13893. #define TEST_CASE(...) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  13894. #define TEST_CASE_METHOD(className, ...) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13895. #define METHOD_AS_TEST_CASE(method, ...) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  13896. #define REGISTER_TEST_CASE(Function, ...) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  13897. #define SECTION(...) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  13898. #define DYNAMIC_SECTION(...) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
  13899. #define FAIL(...) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  13900. #define FAIL_CHECK(...) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13901. #define SUCCEED(...) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13902. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  13903. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  13904. #define TEMPLATE_TEST_CASE(...) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  13905. #define TEMPLATE_TEST_CASE_SIG(...) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ )
  13906. #define TEMPLATE_TEST_CASE_METHOD(className, ...) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13907. #define TEMPLATE_TEST_CASE_METHOD_SIG(className, ...) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
  13908. #define TEMPLATE_PRODUCT_TEST_CASE(...) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )
  13909. #define TEMPLATE_PRODUCT_TEST_CASE_SIG(...) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ )
  13910. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, ...) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13911. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, ...) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
  13912. #define TEMPLATE_LIST_TEST_CASE(...) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(__VA_ARGS__)
  13913. #define TEMPLATE_LIST_TEST_CASE_METHOD(className, ...) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13914. #else
  13915. #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
  13916. #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) )
  13917. #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  13918. #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
  13919. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )
  13920. #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) )
  13921. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  13922. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
  13923. #define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE( __VA_ARGS__ ) )
  13924. #define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  13925. #endif
  13926. #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
  13927. #define STATIC_REQUIRE(...) static_assert( __VA_ARGS__, #__VA_ARGS__ ); SUCCEED( #__VA_ARGS__ )
  13928. #define STATIC_REQUIRE_FALSE(...) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); SUCCEED( "!(" #__VA_ARGS__ ")" )
  13929. #else
  13930. #define STATIC_REQUIRE( ... ) REQUIRE( __VA_ARGS__ )
  13931. #define STATIC_REQUIRE_FALSE( ... ) REQUIRE_FALSE( __VA_ARGS__ )
  13932. #endif
  13933. #endif
  13934. #define CATCH_TRANSLATE_EXCEPTION(signature) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature )
  13935. // "BDD-style" convenience wrappers
  13936. #define SCENARIO(...) TEST_CASE( "Scenario: " __VA_ARGS__ )
  13937. #define SCENARIO_METHOD(className, ...) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  13938. #define GIVEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
  13939. #define AND_GIVEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
  13940. #define WHEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
  13941. #define AND_WHEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
  13942. #define THEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
  13943. #define AND_THEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
  13944. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  13945. #define BENCHMARK(...) \
  13946. 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__,,))
  13947. #define BENCHMARK_ADVANCED(name) \
  13948. INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), name)
  13949. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  13950. using Catch::Detail::Approx;
  13951. #else // CATCH_CONFIG_DISABLE
  13952. //////
  13953. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  13954. #ifdef CATCH_CONFIG_PREFIX_ALL
  13955. #define CATCH_REQUIRE( ... ) (void)(0)
  13956. #define CATCH_REQUIRE_FALSE( ... ) (void)(0)
  13957. #define CATCH_REQUIRE_THROWS( ... ) (void)(0)
  13958. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  13959. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  13960. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13961. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  13962. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  13963. #define CATCH_REQUIRE_NOTHROW( ... ) (void)(0)
  13964. #define CATCH_CHECK( ... ) (void)(0)
  13965. #define CATCH_CHECK_FALSE( ... ) (void)(0)
  13966. #define CATCH_CHECKED_IF( ... ) if (__VA_ARGS__)
  13967. #define CATCH_CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  13968. #define CATCH_CHECK_NOFAIL( ... ) (void)(0)
  13969. #define CATCH_CHECK_THROWS( ... ) (void)(0)
  13970. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  13971. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  13972. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13973. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  13974. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  13975. #define CATCH_CHECK_NOTHROW( ... ) (void)(0)
  13976. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13977. #define CATCH_CHECK_THAT( arg, matcher ) (void)(0)
  13978. #define CATCH_REQUIRE_THAT( arg, matcher ) (void)(0)
  13979. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  13980. #define CATCH_INFO( msg ) (void)(0)
  13981. #define CATCH_UNSCOPED_INFO( msg ) (void)(0)
  13982. #define CATCH_WARN( msg ) (void)(0)
  13983. #define CATCH_CAPTURE( msg ) (void)(0)
  13984. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  13985. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  13986. #define CATCH_METHOD_AS_TEST_CASE( method, ... )
  13987. #define CATCH_REGISTER_TEST_CASE( Function, ... ) (void)(0)
  13988. #define CATCH_SECTION( ... )
  13989. #define CATCH_DYNAMIC_SECTION( ... )
  13990. #define CATCH_FAIL( ... ) (void)(0)
  13991. #define CATCH_FAIL_CHECK( ... ) (void)(0)
  13992. #define CATCH_SUCCEED( ... ) (void)(0)
  13993. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  13994. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  13995. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
  13996. #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
  13997. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
  13998. #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ )
  13999. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14000. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14001. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14002. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14003. #else
  14004. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) )
  14005. #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) )
  14006. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) )
  14007. #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) )
  14008. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14009. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14010. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14011. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14012. #endif
  14013. // "BDD-style" convenience wrappers
  14014. #define CATCH_SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  14015. #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 )
  14016. #define CATCH_GIVEN( desc )
  14017. #define CATCH_AND_GIVEN( desc )
  14018. #define CATCH_WHEN( desc )
  14019. #define CATCH_AND_WHEN( desc )
  14020. #define CATCH_THEN( desc )
  14021. #define CATCH_AND_THEN( desc )
  14022. #define CATCH_STATIC_REQUIRE( ... ) (void)(0)
  14023. #define CATCH_STATIC_REQUIRE_FALSE( ... ) (void)(0)
  14024. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  14025. #else
  14026. #define REQUIRE( ... ) (void)(0)
  14027. #define REQUIRE_FALSE( ... ) (void)(0)
  14028. #define REQUIRE_THROWS( ... ) (void)(0)
  14029. #define REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  14030. #define REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  14031. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14032. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  14033. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14034. #define REQUIRE_NOTHROW( ... ) (void)(0)
  14035. #define CHECK( ... ) (void)(0)
  14036. #define CHECK_FALSE( ... ) (void)(0)
  14037. #define CHECKED_IF( ... ) if (__VA_ARGS__)
  14038. #define CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  14039. #define CHECK_NOFAIL( ... ) (void)(0)
  14040. #define CHECK_THROWS( ... ) (void)(0)
  14041. #define CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  14042. #define CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  14043. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14044. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  14045. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14046. #define CHECK_NOTHROW( ... ) (void)(0)
  14047. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14048. #define CHECK_THAT( arg, matcher ) (void)(0)
  14049. #define REQUIRE_THAT( arg, matcher ) (void)(0)
  14050. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14051. #define INFO( msg ) (void)(0)
  14052. #define UNSCOPED_INFO( msg ) (void)(0)
  14053. #define WARN( msg ) (void)(0)
  14054. #define CAPTURE( msg ) (void)(0)
  14055. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  14056. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  14057. #define METHOD_AS_TEST_CASE( method, ... )
  14058. #define REGISTER_TEST_CASE( Function, ... ) (void)(0)
  14059. #define SECTION( ... )
  14060. #define DYNAMIC_SECTION( ... )
  14061. #define FAIL( ... ) (void)(0)
  14062. #define FAIL_CHECK( ... ) (void)(0)
  14063. #define SUCCEED( ... ) (void)(0)
  14064. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  14065. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  14066. #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
  14067. #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
  14068. #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
  14069. #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ )
  14070. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14071. #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14072. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14073. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14074. #else
  14075. #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) )
  14076. #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) )
  14077. #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) )
  14078. #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) )
  14079. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14080. #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14081. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14082. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14083. #endif
  14084. #define STATIC_REQUIRE( ... ) (void)(0)
  14085. #define STATIC_REQUIRE_FALSE( ... ) (void)(0)
  14086. #endif
  14087. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
  14088. // "BDD-style" convenience wrappers
  14089. #define SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) )
  14090. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className )
  14091. #define GIVEN( desc )
  14092. #define AND_GIVEN( desc )
  14093. #define WHEN( desc )
  14094. #define AND_WHEN( desc )
  14095. #define THEN( desc )
  14096. #define AND_THEN( desc )
  14097. using Catch::Detail::Approx;
  14098. #endif
  14099. #endif // ! CATCH_CONFIG_IMPL_ONLY
  14100. // start catch_reenable_warnings.h
  14101. #ifdef __clang__
  14102. # ifdef __ICC // icpc defines the __clang__ macro
  14103. # pragma warning(pop)
  14104. # else
  14105. # pragma clang diagnostic pop
  14106. # endif
  14107. #elif defined __GNUC__
  14108. # pragma GCC diagnostic pop
  14109. #endif
  14110. // end catch_reenable_warnings.h
  14111. // end catch.hpp
  14112. #endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED