catch.hpp 598 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864
  1. /*
  2. * Catch v2.9.0
  3. * Generated: 2019-06-16 10:41:32.122746
  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 0
  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. // Check if string_view is available and usable
  228. // The check is split apart to work around v140 (VS2015) preprocessor issue...
  229. #if defined(__has_include)
  230. #if __has_include(<string_view>) && defined(CATCH_CPP17_OR_GREATER)
  231. # define CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW
  232. #endif
  233. #endif
  234. ////////////////////////////////////////////////////////////////////////////////
  235. // Check if optional is available and usable
  236. #if defined(__has_include)
  237. # if __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
  238. # define CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL
  239. # endif // __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
  240. #endif // __has_include
  241. ////////////////////////////////////////////////////////////////////////////////
  242. // Check if variant is available and usable
  243. #if defined(__has_include)
  244. # if __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
  245. # if defined(__clang__) && (__clang_major__ < 8)
  246. // work around clang bug with libstdc++ https://bugs.llvm.org/show_bug.cgi?id=31852
  247. // fix should be in clang 8, workaround in libstdc++ 8.2
  248. # include <ciso646>
  249. # if defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
  250. # define CATCH_CONFIG_NO_CPP17_VARIANT
  251. # else
  252. # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
  253. # endif // defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
  254. # else
  255. # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
  256. # endif // defined(__clang__) && (__clang_major__ < 8)
  257. # endif // __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
  258. #endif // __has_include
  259. #if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER)
  260. # define CATCH_CONFIG_COUNTER
  261. #endif
  262. #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)
  263. # define CATCH_CONFIG_WINDOWS_SEH
  264. #endif
  265. // This is set by default, because we assume that unix compilers are posix-signal-compatible by default.
  266. #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)
  267. # define CATCH_CONFIG_POSIX_SIGNALS
  268. #endif
  269. // This is set by default, because we assume that compilers with no wchar_t support are just rare exceptions.
  270. #if !defined(CATCH_INTERNAL_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_WCHAR)
  271. # define CATCH_CONFIG_WCHAR
  272. #endif
  273. #if !defined(CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_CPP11_TO_STRING)
  274. # define CATCH_CONFIG_CPP11_TO_STRING
  275. #endif
  276. #if defined(CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_NO_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_CPP17_OPTIONAL)
  277. # define CATCH_CONFIG_CPP17_OPTIONAL
  278. #endif
  279. #if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
  280. # define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
  281. #endif
  282. #if defined(CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_NO_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_CPP17_STRING_VIEW)
  283. # define CATCH_CONFIG_CPP17_STRING_VIEW
  284. #endif
  285. #if defined(CATCH_INTERNAL_CONFIG_CPP17_VARIANT) && !defined(CATCH_CONFIG_NO_CPP17_VARIANT) && !defined(CATCH_CONFIG_CPP17_VARIANT)
  286. # define CATCH_CONFIG_CPP17_VARIANT
  287. #endif
  288. #if defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
  289. # define CATCH_INTERNAL_CONFIG_NEW_CAPTURE
  290. #endif
  291. #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)
  292. # define CATCH_CONFIG_NEW_CAPTURE
  293. #endif
  294. #if !defined(CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  295. # define CATCH_CONFIG_DISABLE_EXCEPTIONS
  296. #endif
  297. #if defined(CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_NO_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_POLYFILL_ISNAN)
  298. # define CATCH_CONFIG_POLYFILL_ISNAN
  299. #endif
  300. #if defined(CATCH_INTERNAL_CONFIG_USE_ASYNC) && !defined(CATCH_CONFIG_NO_USE_ASYNC) && !defined(CATCH_CONFIG_USE_ASYNC)
  301. # define CATCH_CONFIG_USE_ASYNC
  302. #endif
  303. #if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS)
  304. # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS
  305. # define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS
  306. #endif
  307. #if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS)
  308. # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  309. # define CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  310. #endif
  311. #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS)
  312. # define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS
  313. # define CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS
  314. #endif
  315. #if !defined(CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS)
  316. # define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS
  317. # define CATCH_INTERNAL_UNSUPPRESS_ZERO_VARIADIC_WARNINGS
  318. #endif
  319. #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  320. #define CATCH_TRY if ((true))
  321. #define CATCH_CATCH_ALL if ((false))
  322. #define CATCH_CATCH_ANON(type) if ((false))
  323. #else
  324. #define CATCH_TRY try
  325. #define CATCH_CATCH_ALL catch (...)
  326. #define CATCH_CATCH_ANON(type) catch (type)
  327. #endif
  328. #if defined(CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_NO_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR)
  329. #define CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  330. #endif
  331. // end catch_compiler_capabilities.h
  332. #define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line
  333. #define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line )
  334. #ifdef CATCH_CONFIG_COUNTER
  335. # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ )
  336. #else
  337. # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ )
  338. #endif
  339. #include <iosfwd>
  340. #include <string>
  341. #include <cstdint>
  342. // We need a dummy global operator<< so we can bring it into Catch namespace later
  343. struct Catch_global_namespace_dummy {};
  344. std::ostream& operator<<(std::ostream&, Catch_global_namespace_dummy);
  345. namespace Catch {
  346. struct CaseSensitive { enum Choice {
  347. Yes,
  348. No
  349. }; };
  350. class NonCopyable {
  351. NonCopyable( NonCopyable const& ) = delete;
  352. NonCopyable( NonCopyable && ) = delete;
  353. NonCopyable& operator = ( NonCopyable const& ) = delete;
  354. NonCopyable& operator = ( NonCopyable && ) = delete;
  355. protected:
  356. NonCopyable();
  357. virtual ~NonCopyable();
  358. };
  359. struct SourceLineInfo {
  360. SourceLineInfo() = delete;
  361. SourceLineInfo( char const* _file, std::size_t _line ) noexcept
  362. : file( _file ),
  363. line( _line )
  364. {}
  365. SourceLineInfo( SourceLineInfo const& other ) = default;
  366. SourceLineInfo& operator = ( SourceLineInfo const& ) = default;
  367. SourceLineInfo( SourceLineInfo&& ) noexcept = default;
  368. SourceLineInfo& operator = ( SourceLineInfo&& ) noexcept = default;
  369. bool empty() const noexcept;
  370. bool operator == ( SourceLineInfo const& other ) const noexcept;
  371. bool operator < ( SourceLineInfo const& other ) const noexcept;
  372. char const* file;
  373. std::size_t line;
  374. };
  375. std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info );
  376. // Bring in operator<< from global namespace into Catch namespace
  377. // This is necessary because the overload of operator<< above makes
  378. // lookup stop at namespace Catch
  379. using ::operator<<;
  380. // Use this in variadic streaming macros to allow
  381. // >> +StreamEndStop
  382. // as well as
  383. // >> stuff +StreamEndStop
  384. struct StreamEndStop {
  385. std::string operator+() const;
  386. };
  387. template<typename T>
  388. T const& operator + ( T const& value, StreamEndStop ) {
  389. return value;
  390. }
  391. }
  392. #define CATCH_INTERNAL_LINEINFO \
  393. ::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) )
  394. // end catch_common.h
  395. namespace Catch {
  396. struct RegistrarForTagAliases {
  397. RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo );
  398. };
  399. } // end namespace Catch
  400. #define CATCH_REGISTER_TAG_ALIAS( alias, spec ) \
  401. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  402. namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } \
  403. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  404. // end catch_tag_alias_autoregistrar.h
  405. // start catch_test_registry.h
  406. // start catch_interfaces_testcase.h
  407. #include <vector>
  408. namespace Catch {
  409. class TestSpec;
  410. struct ITestInvoker {
  411. virtual void invoke () const = 0;
  412. virtual ~ITestInvoker();
  413. };
  414. class TestCase;
  415. struct IConfig;
  416. struct ITestCaseRegistry {
  417. virtual ~ITestCaseRegistry();
  418. virtual std::vector<TestCase> const& getAllTests() const = 0;
  419. virtual std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const = 0;
  420. };
  421. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
  422. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
  423. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
  424. }
  425. // end catch_interfaces_testcase.h
  426. // start catch_stringref.h
  427. #include <cstddef>
  428. #include <string>
  429. #include <iosfwd>
  430. namespace Catch {
  431. /// A non-owning string class (similar to the forthcoming std::string_view)
  432. /// Note that, because a StringRef may be a substring of another string,
  433. /// it may not be null terminated. c_str() must return a null terminated
  434. /// string, however, and so the StringRef will internally take ownership
  435. /// (taking a copy), if necessary. In theory this ownership is not externally
  436. /// visible - but it does mean (substring) StringRefs should not be shared between
  437. /// threads.
  438. class StringRef {
  439. public:
  440. using size_type = std::size_t;
  441. private:
  442. friend struct StringRefTestAccess;
  443. char const* m_start;
  444. size_type m_size;
  445. char* m_data = nullptr;
  446. void takeOwnership();
  447. static constexpr char const* const s_empty = "";
  448. public: // construction/ assignment
  449. StringRef() noexcept
  450. : StringRef( s_empty, 0 )
  451. {}
  452. StringRef( StringRef const& other ) noexcept
  453. : m_start( other.m_start ),
  454. m_size( other.m_size )
  455. {}
  456. StringRef( StringRef&& other ) noexcept
  457. : m_start( other.m_start ),
  458. m_size( other.m_size ),
  459. m_data( other.m_data )
  460. {
  461. other.m_data = nullptr;
  462. }
  463. StringRef( char const* rawChars ) noexcept;
  464. StringRef( char const* rawChars, size_type size ) noexcept
  465. : m_start( rawChars ),
  466. m_size( size )
  467. {}
  468. StringRef( std::string const& stdString ) noexcept
  469. : m_start( stdString.c_str() ),
  470. m_size( stdString.size() )
  471. {}
  472. ~StringRef() noexcept {
  473. delete[] m_data;
  474. }
  475. auto operator = ( StringRef const &other ) noexcept -> StringRef& {
  476. delete[] m_data;
  477. m_data = nullptr;
  478. m_start = other.m_start;
  479. m_size = other.m_size;
  480. return *this;
  481. }
  482. operator std::string() const;
  483. void swap( StringRef& other ) noexcept;
  484. public: // operators
  485. auto operator == ( StringRef const& other ) const noexcept -> bool;
  486. auto operator != ( StringRef const& other ) const noexcept -> bool;
  487. auto operator[] ( size_type index ) const noexcept -> char;
  488. public: // named queries
  489. auto empty() const noexcept -> bool {
  490. return m_size == 0;
  491. }
  492. auto size() const noexcept -> size_type {
  493. return m_size;
  494. }
  495. auto numberOfCharacters() const noexcept -> size_type;
  496. auto c_str() const -> char const*;
  497. public: // substrings and searches
  498. auto substr( size_type start, size_type size ) const noexcept -> StringRef;
  499. // Returns the current start pointer.
  500. // Note that the pointer can change when if the StringRef is a substring
  501. auto currentData() const noexcept -> char const*;
  502. private: // ownership queries - may not be consistent between calls
  503. auto isOwned() const noexcept -> bool;
  504. auto isSubstring() const noexcept -> bool;
  505. };
  506. auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string;
  507. auto operator + ( StringRef const& lhs, char const* rhs ) -> std::string;
  508. auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string;
  509. auto operator += ( std::string& lhs, StringRef const& sr ) -> std::string&;
  510. auto operator << ( std::ostream& os, StringRef const& sr ) -> std::ostream&;
  511. inline auto operator "" _sr( char const* rawChars, std::size_t size ) noexcept -> StringRef {
  512. return StringRef( rawChars, size );
  513. }
  514. } // namespace Catch
  515. inline auto operator "" _catch_sr( char const* rawChars, std::size_t size ) noexcept -> Catch::StringRef {
  516. return Catch::StringRef( rawChars, size );
  517. }
  518. // end catch_stringref.h
  519. // start catch_type_traits.hpp
  520. #include <type_traits>
  521. namespace Catch{
  522. #ifdef CATCH_CPP17_OR_GREATER
  523. template <typename...>
  524. inline constexpr auto is_unique = std::true_type{};
  525. template <typename T, typename... Rest>
  526. inline constexpr auto is_unique<T, Rest...> = std::bool_constant<
  527. (!std::is_same_v<T, Rest> && ...) && is_unique<Rest...>
  528. >{};
  529. #else
  530. template <typename...>
  531. struct is_unique : std::true_type{};
  532. template <typename T0, typename T1, typename... Rest>
  533. struct is_unique<T0, T1, Rest...> : std::integral_constant
  534. <bool,
  535. !std::is_same<T0, T1>::value
  536. && is_unique<T0, Rest...>::value
  537. && is_unique<T1, Rest...>::value
  538. >{};
  539. #endif
  540. }
  541. // end catch_type_traits.hpp
  542. // start catch_preprocessor.hpp
  543. #define CATCH_RECURSION_LEVEL0(...) __VA_ARGS__
  544. #define CATCH_RECURSION_LEVEL1(...) CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(__VA_ARGS__)))
  545. #define CATCH_RECURSION_LEVEL2(...) CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(__VA_ARGS__)))
  546. #define CATCH_RECURSION_LEVEL3(...) CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(__VA_ARGS__)))
  547. #define CATCH_RECURSION_LEVEL4(...) CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(__VA_ARGS__)))
  548. #define CATCH_RECURSION_LEVEL5(...) CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(__VA_ARGS__)))
  549. #ifdef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  550. #define INTERNAL_CATCH_EXPAND_VARGS(...) __VA_ARGS__
  551. // MSVC needs more evaluations
  552. #define CATCH_RECURSION_LEVEL6(...) CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(__VA_ARGS__)))
  553. #define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL6(CATCH_RECURSION_LEVEL6(__VA_ARGS__))
  554. #else
  555. #define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL5(__VA_ARGS__)
  556. #endif
  557. #define CATCH_REC_END(...)
  558. #define CATCH_REC_OUT
  559. #define CATCH_EMPTY()
  560. #define CATCH_DEFER(id) id CATCH_EMPTY()
  561. #define CATCH_REC_GET_END2() 0, CATCH_REC_END
  562. #define CATCH_REC_GET_END1(...) CATCH_REC_GET_END2
  563. #define CATCH_REC_GET_END(...) CATCH_REC_GET_END1
  564. #define CATCH_REC_NEXT0(test, next, ...) next CATCH_REC_OUT
  565. #define CATCH_REC_NEXT1(test, next) CATCH_DEFER ( CATCH_REC_NEXT0 ) ( test, next, 0)
  566. #define CATCH_REC_NEXT(test, next) CATCH_REC_NEXT1(CATCH_REC_GET_END test, next)
  567. #define CATCH_REC_LIST0(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ )
  568. #define CATCH_REC_LIST1(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0) ) ( f, peek, __VA_ARGS__ )
  569. #define CATCH_REC_LIST2(f, x, peek, ...) f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ )
  570. #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__ )
  571. #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__ )
  572. #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__ )
  573. // Applies the function macro `f` to each of the remaining parameters, inserts commas between the results,
  574. // and passes userdata as the first parameter to each invocation,
  575. // e.g. CATCH_REC_LIST_UD(f, x, a, b, c) evaluates to f(x, a), f(x, b), f(x, c)
  576. #define CATCH_REC_LIST_UD(f, userdata, ...) CATCH_RECURSE(CATCH_REC_LIST2_UD(f, userdata, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
  577. #define CATCH_REC_LIST(f, ...) CATCH_RECURSE(CATCH_REC_LIST2(f, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
  578. #define INTERNAL_CATCH_EXPAND1(param) INTERNAL_CATCH_EXPAND2(param)
  579. #define INTERNAL_CATCH_EXPAND2(...) INTERNAL_CATCH_NO## __VA_ARGS__
  580. #define INTERNAL_CATCH_DEF(...) INTERNAL_CATCH_DEF __VA_ARGS__
  581. #define INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
  582. #define INTERNAL_CATCH_STRINGIZE(...) INTERNAL_CATCH_STRINGIZE2(__VA_ARGS__)
  583. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  584. #define INTERNAL_CATCH_STRINGIZE2(...) #__VA_ARGS__
  585. #define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param))
  586. #else
  587. // MSVC is adding extra space and needs another indirection to expand INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
  588. #define INTERNAL_CATCH_STRINGIZE2(...) INTERNAL_CATCH_STRINGIZE3(__VA_ARGS__)
  589. #define INTERNAL_CATCH_STRINGIZE3(...) #__VA_ARGS__
  590. #define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) (INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) + 1)
  591. #endif
  592. #define INTERNAL_CATCH_MAKE_NAMESPACE2(...) ns_##__VA_ARGS__
  593. #define INTERNAL_CATCH_MAKE_NAMESPACE(name) INTERNAL_CATCH_MAKE_NAMESPACE2(name)
  594. #define INTERNAL_CATCH_REMOVE_PARENS(...) INTERNAL_CATCH_EXPAND1(INTERNAL_CATCH_DEF __VA_ARGS__)
  595. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  596. #define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>())
  597. #define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__))
  598. #else
  599. #define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) INTERNAL_CATCH_EXPAND_VARGS(decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>()))
  600. #define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__)))
  601. #endif
  602. #define INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(...)\
  603. CATCH_REC_LIST(INTERNAL_CATCH_MAKE_TYPE_LIST,__VA_ARGS__)
  604. #define INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_0) INTERNAL_CATCH_REMOVE_PARENS(_0)
  605. #define INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_0, _1) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_1)
  606. #define INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_0, _1, _2) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_1, _2)
  607. #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)
  608. #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)
  609. #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)
  610. #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)
  611. #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)
  612. #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)
  613. #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)
  614. #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)
  615. #define INTERNAL_CATCH_VA_NARGS_IMPL(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N
  616. #define INTERNAL_CATCH_TYPE_GEN\
  617. template<typename...> struct TypeList {};\
  618. template<typename...Ts>\
  619. constexpr auto get_wrapper() noexcept -> TypeList<Ts...> { return {}; }\
  620. \
  621. template<template<typename...> class L1, typename...E1, template<typename...> class L2, typename...E2> \
  622. constexpr auto append(L1<E1...>, L2<E2...>) noexcept -> L1<E1...,E2...> { return {}; }\
  623. template< template<typename...> class L1, typename...E1, template<typename...> class L2, typename...E2, typename...Rest>\
  624. constexpr auto append(L1<E1...>, L2<E2...>, Rest...) noexcept -> decltype(append(L1<E1...,E2...>{}, Rest{}...)) { return {}; }\
  625. template< template<typename...> class L1, typename...E1, typename...Rest>\
  626. constexpr auto append(L1<E1...>, TypeList<mpl_::na>, Rest...) noexcept -> L1<E1...> { return {}; }\
  627. \
  628. template< template<typename...> class Container, template<typename...> class List, typename...elems>\
  629. constexpr auto rewrap(List<elems...>) noexcept -> TypeList<Container<elems...>> { return {}; }\
  630. template< template<typename...> class Container, template<typename...> class List, class...Elems, typename...Elements>\
  631. constexpr auto rewrap(List<Elems...>,Elements...) noexcept -> decltype(append(TypeList<Container<Elems...>>{}, rewrap<Container>(Elements{}...))) { return {}; }\
  632. \
  633. template<template <typename...> class Final, template< typename...> class...Containers, typename...Types>\
  634. constexpr auto create(TypeList<Types...>) noexcept -> decltype(append(Final<>{}, rewrap<Containers>(Types{}...)...)) { return {}; }\
  635. template<template <typename...> class Final, template <typename...> class List, typename...Ts>\
  636. constexpr auto convert(List<Ts...>) noexcept -> decltype(append(Final<>{},TypeList<Ts>{}...)) { return {}; }
  637. #define INTERNAL_CATCH_NTTP_1(signature, ...)\
  638. template<INTERNAL_CATCH_REMOVE_PARENS(signature)> struct Nttp{};\
  639. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  640. constexpr auto get_wrapper() noexcept -> Nttp<__VA_ARGS__> { return {}; } \
  641. \
  642. template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  643. constexpr auto rewrap(List<__VA_ARGS__>) noexcept -> TypeList<Container<__VA_ARGS__>> { return {}; }\
  644. template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature), typename...Elements>\
  645. constexpr auto rewrap(List<__VA_ARGS__>,Elements...elems) noexcept -> decltype(append(TypeList<Container<__VA_ARGS__>>{}, rewrap<Container>(elems...))) { return {}; }\
  646. template<template <typename...> class Final, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...Containers, typename...Types>\
  647. constexpr auto create(TypeList<Types...>) noexcept -> decltype(append(Final<>{}, rewrap<Containers>(Types{}...)...)) { return {}; }
  648. #define INTERNAL_CATCH_DECLARE_SIG_TEST0(TestName)
  649. #define INTERNAL_CATCH_DECLARE_SIG_TEST1(TestName, signature)\
  650. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  651. static void TestName()
  652. #define INTERNAL_CATCH_DECLARE_SIG_TEST_X(TestName, signature, ...)\
  653. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  654. static void TestName()
  655. #define INTERNAL_CATCH_DEFINE_SIG_TEST0(TestName)
  656. #define INTERNAL_CATCH_DEFINE_SIG_TEST1(TestName, signature)\
  657. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  658. static void TestName()
  659. #define INTERNAL_CATCH_DEFINE_SIG_TEST_X(TestName, signature,...)\
  660. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  661. static void TestName()
  662. #define INTERNAL_CATCH_NTTP_REGISTER0(TestFunc, signature)\
  663. template<typename Type>\
  664. void reg_test(TypeList<Type>, Catch::NameAndTags nameAndTags)\
  665. {\
  666. Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<Type>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\
  667. }
  668. #define INTERNAL_CATCH_NTTP_REGISTER(TestFunc, signature, ...)\
  669. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  670. void reg_test(Nttp<__VA_ARGS__>, Catch::NameAndTags nameAndTags)\
  671. {\
  672. Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<__VA_ARGS__>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\
  673. }
  674. #define INTERNAL_CATCH_NTTP_REGISTER_METHOD0(TestName, signature, ...)\
  675. template<typename Type>\
  676. void reg_test(TypeList<Type>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\
  677. {\
  678. Catch::AutoReg( Catch::makeTestInvoker(&TestName<Type>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\
  679. }
  680. #define INTERNAL_CATCH_NTTP_REGISTER_METHOD(TestName, signature, ...)\
  681. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  682. void reg_test(Nttp<__VA_ARGS__>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\
  683. {\
  684. Catch::AutoReg( Catch::makeTestInvoker(&TestName<__VA_ARGS__>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\
  685. }
  686. #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0(TestName, ClassName)
  687. #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1(TestName, ClassName, signature)\
  688. template<typename TestType> \
  689. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<TestType> { \
  690. void test();\
  691. }
  692. #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X(TestName, ClassName, signature, ...)\
  693. template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \
  694. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<__VA_ARGS__> { \
  695. void test();\
  696. }
  697. #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0(TestName)
  698. #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1(TestName, signature)\
  699. template<typename TestType> \
  700. void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<TestType>::test()
  701. #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X(TestName, signature, ...)\
  702. template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \
  703. void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<__VA_ARGS__>::test()
  704. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  705. #define INTERNAL_CATCH_NTTP_0
  706. #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)
  707. #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__)
  708. #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__)
  709. #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__)
  710. #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__)
  711. #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__)
  712. #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__)
  713. #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__)
  714. #else
  715. #define INTERNAL_CATCH_NTTP_0(signature)
  716. #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__))
  717. #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__))
  718. #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__))
  719. #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__))
  720. #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__))
  721. #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__))
  722. #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__))
  723. #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__))
  724. #endif
  725. // end catch_preprocessor.hpp
  726. // start catch_meta.hpp
  727. #include <type_traits>
  728. namespace Catch {
  729. template<typename T>
  730. struct always_false : std::false_type {};
  731. template <typename> struct true_given : std::true_type {};
  732. struct is_callable_tester {
  733. template <typename Fun, typename... Args>
  734. true_given<decltype(std::declval<Fun>()(std::declval<Args>()...))> static test(int);
  735. template <typename...>
  736. std::false_type static test(...);
  737. };
  738. template <typename T>
  739. struct is_callable;
  740. template <typename Fun, typename... Args>
  741. struct is_callable<Fun(Args...)> : decltype(is_callable_tester::test<Fun, Args...>(0)) {};
  742. } // namespace Catch
  743. namespace mpl_{
  744. struct na;
  745. }
  746. // end catch_meta.hpp
  747. namespace Catch {
  748. template<typename C>
  749. class TestInvokerAsMethod : public ITestInvoker {
  750. void (C::*m_testAsMethod)();
  751. public:
  752. TestInvokerAsMethod( void (C::*testAsMethod)() ) noexcept : m_testAsMethod( testAsMethod ) {}
  753. void invoke() const override {
  754. C obj;
  755. (obj.*m_testAsMethod)();
  756. }
  757. };
  758. auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker*;
  759. template<typename C>
  760. auto makeTestInvoker( void (C::*testAsMethod)() ) noexcept -> ITestInvoker* {
  761. return new(std::nothrow) TestInvokerAsMethod<C>( testAsMethod );
  762. }
  763. struct NameAndTags {
  764. NameAndTags( StringRef const& name_ = StringRef(), StringRef const& tags_ = StringRef() ) noexcept;
  765. StringRef name;
  766. StringRef tags;
  767. };
  768. struct AutoReg : NonCopyable {
  769. AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept;
  770. ~AutoReg();
  771. };
  772. } // end namespace Catch
  773. #if defined(CATCH_CONFIG_DISABLE)
  774. #define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( TestName, ... ) \
  775. static void TestName()
  776. #define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( TestName, ClassName, ... ) \
  777. namespace{ \
  778. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
  779. void test(); \
  780. }; \
  781. } \
  782. void TestName::test()
  783. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( TestName, TestFunc, Name, Tags, Signature, ... ) \
  784. INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature))
  785. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... ) \
  786. namespace{ \
  787. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
  788. INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
  789. } \
  790. } \
  791. INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))
  792. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  793. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \
  794. 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__ )
  795. #else
  796. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \
  797. 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__ ) )
  798. #endif
  799. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  800. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \
  801. 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__ )
  802. #else
  803. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \
  804. 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__ ) )
  805. #endif
  806. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  807. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \
  808. 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__ )
  809. #else
  810. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \
  811. 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__ ) )
  812. #endif
  813. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  814. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \
  815. 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__ )
  816. #else
  817. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \
  818. 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__ ) )
  819. #endif
  820. #endif
  821. ///////////////////////////////////////////////////////////////////////////////
  822. #define INTERNAL_CATCH_TESTCASE2( TestName, ... ) \
  823. static void TestName(); \
  824. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  825. namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &TestName ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
  826. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  827. static void TestName()
  828. #define INTERNAL_CATCH_TESTCASE( ... ) \
  829. INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), __VA_ARGS__ )
  830. ///////////////////////////////////////////////////////////////////////////////
  831. #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \
  832. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  833. namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &QualifiedMethod ), CATCH_INTERNAL_LINEINFO, "&" #QualifiedMethod, Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
  834. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  835. ///////////////////////////////////////////////////////////////////////////////
  836. #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestName, ClassName, ... )\
  837. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  838. namespace{ \
  839. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
  840. void test(); \
  841. }; \
  842. Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( Catch::makeTestInvoker( &TestName::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
  843. } \
  844. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  845. void TestName::test()
  846. #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \
  847. INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, __VA_ARGS__ )
  848. ///////////////////////////////////////////////////////////////////////////////
  849. #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \
  850. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  851. Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( Function ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
  852. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  853. ///////////////////////////////////////////////////////////////////////////////
  854. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_2(TestName, TestFunc, Name, Tags, Signature, ... )\
  855. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  856. CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
  857. INTERNAL_CATCH_DECLARE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
  858. namespace {\
  859. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\
  860. INTERNAL_CATCH_TYPE_GEN\
  861. INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
  862. INTERNAL_CATCH_NTTP_REG_GEN(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature))\
  863. template<typename...Types> \
  864. struct TestName{\
  865. TestName(){\
  866. int index = 0; \
  867. constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\
  868. using expander = int[];\
  869. (void)expander{(reg_test(Types{}, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++, 0)... };/* NOLINT */ \
  870. }\
  871. };\
  872. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
  873. TestName<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\
  874. return 0;\
  875. }();\
  876. }\
  877. }\
  878. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  879. CATCH_INTERNAL_UNSUPPRESS_ZERO_VARIADIC_WARNINGS \
  880. INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature))
  881. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  882. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
  883. 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__ )
  884. #else
  885. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
  886. 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__ ) )
  887. #endif
  888. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  889. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \
  890. 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__ )
  891. #else
  892. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \
  893. 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__ ) )
  894. #endif
  895. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(TestName, TestFuncName, Name, Tags, Signature, TmplTypes, TypesList) \
  896. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  897. CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
  898. template<typename TestType> static void TestFuncName(); \
  899. namespace {\
  900. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
  901. INTERNAL_CATCH_TYPE_GEN \
  902. INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature)) \
  903. template<typename... Types> \
  904. struct TestName { \
  905. void reg_tests() { \
  906. int index = 0; \
  907. using expander = int[]; \
  908. constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\
  909. constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\
  910. constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\
  911. (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 */\
  912. } \
  913. }; \
  914. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \
  915. using TestInit = decltype(create<TestName, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>(TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(INTERNAL_CATCH_REMOVE_PARENS(TypesList))>{})); \
  916. TestInit t; \
  917. t.reg_tests(); \
  918. return 0; \
  919. }(); \
  920. } \
  921. } \
  922. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  923. CATCH_INTERNAL_UNSUPPRESS_ZERO_VARIADIC_WARNINGS \
  924. template<typename TestType> \
  925. static void TestFuncName()
  926. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  927. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\
  928. 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__)
  929. #else
  930. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\
  931. 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__ ) )
  932. #endif
  933. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  934. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\
  935. 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__)
  936. #else
  937. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\
  938. 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__ ) )
  939. #endif
  940. #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2(TestName, TestFunc, Name, Tags, TmplList)\
  941. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  942. template<typename TestType> static void TestFunc(); \
  943. namespace {\
  944. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\
  945. INTERNAL_CATCH_TYPE_GEN\
  946. template<typename... Types> \
  947. struct TestName { \
  948. void reg_tests() { \
  949. int index = 0; \
  950. using expander = int[]; \
  951. (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 */\
  952. } \
  953. };\
  954. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \
  955. using TestInit = decltype(convert<TestName>(TmplList {})); \
  956. TestInit t; \
  957. t.reg_tests(); \
  958. return 0; \
  959. }(); \
  960. }}\
  961. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  962. template<typename TestType> \
  963. static void TestFunc()
  964. #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(Name, Tags, TmplList) \
  965. 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 )
  966. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... ) \
  967. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  968. CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
  969. namespace {\
  970. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \
  971. INTERNAL_CATCH_TYPE_GEN\
  972. INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
  973. INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
  974. INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))\
  975. template<typename...Types> \
  976. struct TestNameClass{\
  977. TestNameClass(){\
  978. int index = 0; \
  979. constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\
  980. using expander = int[];\
  981. (void)expander{(reg_test(Types{}, #ClassName, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++, 0)... };/* NOLINT */ \
  982. }\
  983. };\
  984. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
  985. TestNameClass<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\
  986. return 0;\
  987. }();\
  988. }\
  989. }\
  990. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS\
  991. CATCH_INTERNAL_UNSUPPRESS_ZERO_VARIADIC_WARNINGS\
  992. INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))
  993. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  994. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \
  995. 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__ )
  996. #else
  997. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \
  998. 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__ ) )
  999. #endif
  1000. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  1001. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \
  1002. 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__ )
  1003. #else
  1004. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \
  1005. 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__ ) )
  1006. #endif
  1007. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2(TestNameClass, TestName, ClassName, Name, Tags, Signature, TmplTypes, TypesList)\
  1008. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  1009. CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
  1010. template<typename TestType> \
  1011. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \
  1012. void test();\
  1013. };\
  1014. namespace {\
  1015. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestNameClass) {\
  1016. INTERNAL_CATCH_TYPE_GEN \
  1017. INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
  1018. template<typename...Types>\
  1019. struct TestNameClass{\
  1020. void reg_tests(){\
  1021. int index = 0;\
  1022. using expander = int[];\
  1023. constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\
  1024. constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\
  1025. constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\
  1026. (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 */ \
  1027. }\
  1028. };\
  1029. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
  1030. using TestInit = decltype(create<TestNameClass, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>(TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(INTERNAL_CATCH_REMOVE_PARENS(TypesList))>{}));\
  1031. TestInit t;\
  1032. t.reg_tests();\
  1033. return 0;\
  1034. }(); \
  1035. }\
  1036. }\
  1037. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  1038. CATCH_INTERNAL_UNSUPPRESS_ZERO_VARIADIC_WARNINGS \
  1039. template<typename TestType> \
  1040. void TestName<TestType>::test()
  1041. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  1042. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\
  1043. 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__ )
  1044. #else
  1045. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\
  1046. 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__ ) )
  1047. #endif
  1048. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  1049. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\
  1050. 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__ )
  1051. #else
  1052. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\
  1053. 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__ ) )
  1054. #endif
  1055. #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, TmplList) \
  1056. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  1057. template<typename TestType> \
  1058. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \
  1059. void test();\
  1060. };\
  1061. namespace {\
  1062. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \
  1063. INTERNAL_CATCH_TYPE_GEN\
  1064. template<typename...Types>\
  1065. struct TestNameClass{\
  1066. void reg_tests(){\
  1067. int index = 0;\
  1068. using expander = int[];\
  1069. (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 */ \
  1070. }\
  1071. };\
  1072. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
  1073. using TestInit = decltype(convert<TestNameClass>(TmplList {}));\
  1074. TestInit t;\
  1075. t.reg_tests();\
  1076. return 0;\
  1077. }(); \
  1078. }}\
  1079. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  1080. template<typename TestType> \
  1081. void TestName<TestType>::test()
  1082. #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD(ClassName, Name, Tags, TmplList) \
  1083. 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 )
  1084. // end catch_test_registry.h
  1085. // start catch_capture.hpp
  1086. // start catch_assertionhandler.h
  1087. // start catch_assertioninfo.h
  1088. // start catch_result_type.h
  1089. namespace Catch {
  1090. // ResultWas::OfType enum
  1091. struct ResultWas { enum OfType {
  1092. Unknown = -1,
  1093. Ok = 0,
  1094. Info = 1,
  1095. Warning = 2,
  1096. FailureBit = 0x10,
  1097. ExpressionFailed = FailureBit | 1,
  1098. ExplicitFailure = FailureBit | 2,
  1099. Exception = 0x100 | FailureBit,
  1100. ThrewException = Exception | 1,
  1101. DidntThrowException = Exception | 2,
  1102. FatalErrorCondition = 0x200 | FailureBit
  1103. }; };
  1104. bool isOk( ResultWas::OfType resultType );
  1105. bool isJustInfo( int flags );
  1106. // ResultDisposition::Flags enum
  1107. struct ResultDisposition { enum Flags {
  1108. Normal = 0x01,
  1109. ContinueOnFailure = 0x02, // Failures fail test, but execution continues
  1110. FalseTest = 0x04, // Prefix expression with !
  1111. SuppressFail = 0x08 // Failures are reported but do not fail the test
  1112. }; };
  1113. ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs );
  1114. bool shouldContinueOnFailure( int flags );
  1115. inline bool isFalseTest( int flags ) { return ( flags & ResultDisposition::FalseTest ) != 0; }
  1116. bool shouldSuppressFailure( int flags );
  1117. } // end namespace Catch
  1118. // end catch_result_type.h
  1119. namespace Catch {
  1120. struct AssertionInfo
  1121. {
  1122. StringRef macroName;
  1123. SourceLineInfo lineInfo;
  1124. StringRef capturedExpression;
  1125. ResultDisposition::Flags resultDisposition;
  1126. // We want to delete this constructor but a compiler bug in 4.8 means
  1127. // the struct is then treated as non-aggregate
  1128. //AssertionInfo() = delete;
  1129. };
  1130. } // end namespace Catch
  1131. // end catch_assertioninfo.h
  1132. // start catch_decomposer.h
  1133. // start catch_tostring.h
  1134. #include <vector>
  1135. #include <cstddef>
  1136. #include <type_traits>
  1137. #include <string>
  1138. // start catch_stream.h
  1139. #include <iosfwd>
  1140. #include <cstddef>
  1141. #include <ostream>
  1142. namespace Catch {
  1143. std::ostream& cout();
  1144. std::ostream& cerr();
  1145. std::ostream& clog();
  1146. class StringRef;
  1147. struct IStream {
  1148. virtual ~IStream();
  1149. virtual std::ostream& stream() const = 0;
  1150. };
  1151. auto makeStream( StringRef const &filename ) -> IStream const*;
  1152. class ReusableStringStream {
  1153. std::size_t m_index;
  1154. std::ostream* m_oss;
  1155. public:
  1156. ReusableStringStream();
  1157. ~ReusableStringStream();
  1158. auto str() const -> std::string;
  1159. template<typename T>
  1160. auto operator << ( T const& value ) -> ReusableStringStream& {
  1161. *m_oss << value;
  1162. return *this;
  1163. }
  1164. auto get() -> std::ostream& { return *m_oss; }
  1165. };
  1166. }
  1167. // end catch_stream.h
  1168. // start catch_interfaces_enum_values_registry.h
  1169. #include <vector>
  1170. namespace Catch {
  1171. namespace Detail {
  1172. struct EnumInfo {
  1173. StringRef m_name;
  1174. std::vector<std::pair<int, std::string>> m_values;
  1175. ~EnumInfo();
  1176. StringRef lookup( int value ) const;
  1177. };
  1178. } // namespace Detail
  1179. struct IMutableEnumValuesRegistry {
  1180. virtual ~IMutableEnumValuesRegistry();
  1181. virtual Detail::EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::vector<int> const& values ) = 0;
  1182. template<typename E>
  1183. Detail::EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::initializer_list<E> values ) {
  1184. std::vector<int> intValues;
  1185. intValues.reserve( values.size() );
  1186. for( auto enumValue : values )
  1187. intValues.push_back( static_cast<int>( enumValue ) );
  1188. return registerEnum( enumName, allEnums, intValues );
  1189. }
  1190. };
  1191. } // Catch
  1192. // end catch_interfaces_enum_values_registry.h
  1193. #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  1194. #include <string_view>
  1195. #endif
  1196. #ifdef __OBJC__
  1197. // start catch_objc_arc.hpp
  1198. #import <Foundation/Foundation.h>
  1199. #ifdef __has_feature
  1200. #define CATCH_ARC_ENABLED __has_feature(objc_arc)
  1201. #else
  1202. #define CATCH_ARC_ENABLED 0
  1203. #endif
  1204. void arcSafeRelease( NSObject* obj );
  1205. id performOptionalSelector( id obj, SEL sel );
  1206. #if !CATCH_ARC_ENABLED
  1207. inline void arcSafeRelease( NSObject* obj ) {
  1208. [obj release];
  1209. }
  1210. inline id performOptionalSelector( id obj, SEL sel ) {
  1211. if( [obj respondsToSelector: sel] )
  1212. return [obj performSelector: sel];
  1213. return nil;
  1214. }
  1215. #define CATCH_UNSAFE_UNRETAINED
  1216. #define CATCH_ARC_STRONG
  1217. #else
  1218. inline void arcSafeRelease( NSObject* ){}
  1219. inline id performOptionalSelector( id obj, SEL sel ) {
  1220. #ifdef __clang__
  1221. #pragma clang diagnostic push
  1222. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  1223. #endif
  1224. if( [obj respondsToSelector: sel] )
  1225. return [obj performSelector: sel];
  1226. #ifdef __clang__
  1227. #pragma clang diagnostic pop
  1228. #endif
  1229. return nil;
  1230. }
  1231. #define CATCH_UNSAFE_UNRETAINED __unsafe_unretained
  1232. #define CATCH_ARC_STRONG __strong
  1233. #endif
  1234. // end catch_objc_arc.hpp
  1235. #endif
  1236. #ifdef _MSC_VER
  1237. #pragma warning(push)
  1238. #pragma warning(disable:4180) // We attempt to stream a function (address) by const&, which MSVC complains about but is harmless
  1239. #endif
  1240. namespace Catch {
  1241. namespace Detail {
  1242. extern const std::string unprintableString;
  1243. std::string rawMemoryToString( const void *object, std::size_t size );
  1244. template<typename T>
  1245. std::string rawMemoryToString( const T& object ) {
  1246. return rawMemoryToString( &object, sizeof(object) );
  1247. }
  1248. template<typename T>
  1249. class IsStreamInsertable {
  1250. template<typename SS, typename TT>
  1251. static auto test(int)
  1252. -> decltype(std::declval<SS&>() << std::declval<TT>(), std::true_type());
  1253. template<typename, typename>
  1254. static auto test(...)->std::false_type;
  1255. public:
  1256. static const bool value = decltype(test<std::ostream, const T&>(0))::value;
  1257. };
  1258. template<typename E>
  1259. std::string convertUnknownEnumToString( E e );
  1260. template<typename T>
  1261. typename std::enable_if<
  1262. !std::is_enum<T>::value && !std::is_base_of<std::exception, T>::value,
  1263. std::string>::type convertUnstreamable( T const& ) {
  1264. return Detail::unprintableString;
  1265. }
  1266. template<typename T>
  1267. typename std::enable_if<
  1268. !std::is_enum<T>::value && std::is_base_of<std::exception, T>::value,
  1269. std::string>::type convertUnstreamable(T const& ex) {
  1270. return ex.what();
  1271. }
  1272. template<typename T>
  1273. typename std::enable_if<
  1274. std::is_enum<T>::value
  1275. , std::string>::type convertUnstreamable( T const& value ) {
  1276. return convertUnknownEnumToString( value );
  1277. }
  1278. #if defined(_MANAGED)
  1279. //! Convert a CLR string to a utf8 std::string
  1280. template<typename T>
  1281. std::string clrReferenceToString( T^ ref ) {
  1282. if (ref == nullptr)
  1283. return std::string("null");
  1284. auto bytes = System::Text::Encoding::UTF8->GetBytes(ref->ToString());
  1285. cli::pin_ptr<System::Byte> p = &bytes[0];
  1286. return std::string(reinterpret_cast<char const *>(p), bytes->Length);
  1287. }
  1288. #endif
  1289. } // namespace Detail
  1290. // If we decide for C++14, change these to enable_if_ts
  1291. template <typename T, typename = void>
  1292. struct StringMaker {
  1293. template <typename Fake = T>
  1294. static
  1295. typename std::enable_if<::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
  1296. convert(const Fake& value) {
  1297. ReusableStringStream rss;
  1298. // NB: call using the function-like syntax to avoid ambiguity with
  1299. // user-defined templated operator<< under clang.
  1300. rss.operator<<(value);
  1301. return rss.str();
  1302. }
  1303. template <typename Fake = T>
  1304. static
  1305. typename std::enable_if<!::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
  1306. convert( const Fake& value ) {
  1307. #if !defined(CATCH_CONFIG_FALLBACK_STRINGIFIER)
  1308. return Detail::convertUnstreamable(value);
  1309. #else
  1310. return CATCH_CONFIG_FALLBACK_STRINGIFIER(value);
  1311. #endif
  1312. }
  1313. };
  1314. namespace Detail {
  1315. // This function dispatches all stringification requests inside of Catch.
  1316. // Should be preferably called fully qualified, like ::Catch::Detail::stringify
  1317. template <typename T>
  1318. std::string stringify(const T& e) {
  1319. return ::Catch::StringMaker<typename std::remove_cv<typename std::remove_reference<T>::type>::type>::convert(e);
  1320. }
  1321. template<typename E>
  1322. std::string convertUnknownEnumToString( E e ) {
  1323. return ::Catch::Detail::stringify(static_cast<typename std::underlying_type<E>::type>(e));
  1324. }
  1325. #if defined(_MANAGED)
  1326. template <typename T>
  1327. std::string stringify( T^ e ) {
  1328. return ::Catch::StringMaker<T^>::convert(e);
  1329. }
  1330. #endif
  1331. } // namespace Detail
  1332. // Some predefined specializations
  1333. template<>
  1334. struct StringMaker<std::string> {
  1335. static std::string convert(const std::string& str);
  1336. };
  1337. #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  1338. template<>
  1339. struct StringMaker<std::string_view> {
  1340. static std::string convert(std::string_view str);
  1341. };
  1342. #endif
  1343. template<>
  1344. struct StringMaker<char const *> {
  1345. static std::string convert(char const * str);
  1346. };
  1347. template<>
  1348. struct StringMaker<char *> {
  1349. static std::string convert(char * str);
  1350. };
  1351. #ifdef CATCH_CONFIG_WCHAR
  1352. template<>
  1353. struct StringMaker<std::wstring> {
  1354. static std::string convert(const std::wstring& wstr);
  1355. };
  1356. # ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  1357. template<>
  1358. struct StringMaker<std::wstring_view> {
  1359. static std::string convert(std::wstring_view str);
  1360. };
  1361. # endif
  1362. template<>
  1363. struct StringMaker<wchar_t const *> {
  1364. static std::string convert(wchar_t const * str);
  1365. };
  1366. template<>
  1367. struct StringMaker<wchar_t *> {
  1368. static std::string convert(wchar_t * str);
  1369. };
  1370. #endif
  1371. // TBD: Should we use `strnlen` to ensure that we don't go out of the buffer,
  1372. // while keeping string semantics?
  1373. template<int SZ>
  1374. struct StringMaker<char[SZ]> {
  1375. static std::string convert(char const* str) {
  1376. return ::Catch::Detail::stringify(std::string{ str });
  1377. }
  1378. };
  1379. template<int SZ>
  1380. struct StringMaker<signed char[SZ]> {
  1381. static std::string convert(signed char const* str) {
  1382. return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) });
  1383. }
  1384. };
  1385. template<int SZ>
  1386. struct StringMaker<unsigned char[SZ]> {
  1387. static std::string convert(unsigned char const* str) {
  1388. return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) });
  1389. }
  1390. };
  1391. template<>
  1392. struct StringMaker<int> {
  1393. static std::string convert(int value);
  1394. };
  1395. template<>
  1396. struct StringMaker<long> {
  1397. static std::string convert(long value);
  1398. };
  1399. template<>
  1400. struct StringMaker<long long> {
  1401. static std::string convert(long long value);
  1402. };
  1403. template<>
  1404. struct StringMaker<unsigned int> {
  1405. static std::string convert(unsigned int value);
  1406. };
  1407. template<>
  1408. struct StringMaker<unsigned long> {
  1409. static std::string convert(unsigned long value);
  1410. };
  1411. template<>
  1412. struct StringMaker<unsigned long long> {
  1413. static std::string convert(unsigned long long value);
  1414. };
  1415. template<>
  1416. struct StringMaker<bool> {
  1417. static std::string convert(bool b);
  1418. };
  1419. template<>
  1420. struct StringMaker<char> {
  1421. static std::string convert(char c);
  1422. };
  1423. template<>
  1424. struct StringMaker<signed char> {
  1425. static std::string convert(signed char c);
  1426. };
  1427. template<>
  1428. struct StringMaker<unsigned char> {
  1429. static std::string convert(unsigned char c);
  1430. };
  1431. template<>
  1432. struct StringMaker<std::nullptr_t> {
  1433. static std::string convert(std::nullptr_t);
  1434. };
  1435. template<>
  1436. struct StringMaker<float> {
  1437. static std::string convert(float value);
  1438. static int precision;
  1439. };
  1440. template<>
  1441. struct StringMaker<double> {
  1442. static std::string convert(double value);
  1443. static int precision;
  1444. };
  1445. template <typename T>
  1446. struct StringMaker<T*> {
  1447. template <typename U>
  1448. static std::string convert(U* p) {
  1449. if (p) {
  1450. return ::Catch::Detail::rawMemoryToString(p);
  1451. } else {
  1452. return "nullptr";
  1453. }
  1454. }
  1455. };
  1456. template <typename R, typename C>
  1457. struct StringMaker<R C::*> {
  1458. static std::string convert(R C::* p) {
  1459. if (p) {
  1460. return ::Catch::Detail::rawMemoryToString(p);
  1461. } else {
  1462. return "nullptr";
  1463. }
  1464. }
  1465. };
  1466. #if defined(_MANAGED)
  1467. template <typename T>
  1468. struct StringMaker<T^> {
  1469. static std::string convert( T^ ref ) {
  1470. return ::Catch::Detail::clrReferenceToString(ref);
  1471. }
  1472. };
  1473. #endif
  1474. namespace Detail {
  1475. template<typename InputIterator>
  1476. std::string rangeToString(InputIterator first, InputIterator last) {
  1477. ReusableStringStream rss;
  1478. rss << "{ ";
  1479. if (first != last) {
  1480. rss << ::Catch::Detail::stringify(*first);
  1481. for (++first; first != last; ++first)
  1482. rss << ", " << ::Catch::Detail::stringify(*first);
  1483. }
  1484. rss << " }";
  1485. return rss.str();
  1486. }
  1487. }
  1488. #ifdef __OBJC__
  1489. template<>
  1490. struct StringMaker<NSString*> {
  1491. static std::string convert(NSString * nsstring) {
  1492. if (!nsstring)
  1493. return "nil";
  1494. return std::string("@") + [nsstring UTF8String];
  1495. }
  1496. };
  1497. template<>
  1498. struct StringMaker<NSObject*> {
  1499. static std::string convert(NSObject* nsObject) {
  1500. return ::Catch::Detail::stringify([nsObject description]);
  1501. }
  1502. };
  1503. namespace Detail {
  1504. inline std::string stringify( NSString* nsstring ) {
  1505. return StringMaker<NSString*>::convert( nsstring );
  1506. }
  1507. } // namespace Detail
  1508. #endif // __OBJC__
  1509. } // namespace Catch
  1510. //////////////////////////////////////////////////////
  1511. // Separate std-lib types stringification, so it can be selectively enabled
  1512. // This means that we do not bring in
  1513. #if defined(CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS)
  1514. # define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
  1515. # define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
  1516. # define CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
  1517. # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  1518. # define CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
  1519. #endif
  1520. // Separate std::pair specialization
  1521. #if defined(CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER)
  1522. #include <utility>
  1523. namespace Catch {
  1524. template<typename T1, typename T2>
  1525. struct StringMaker<std::pair<T1, T2> > {
  1526. static std::string convert(const std::pair<T1, T2>& pair) {
  1527. ReusableStringStream rss;
  1528. rss << "{ "
  1529. << ::Catch::Detail::stringify(pair.first)
  1530. << ", "
  1531. << ::Catch::Detail::stringify(pair.second)
  1532. << " }";
  1533. return rss.str();
  1534. }
  1535. };
  1536. }
  1537. #endif // CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
  1538. #if defined(CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_OPTIONAL)
  1539. #include <optional>
  1540. namespace Catch {
  1541. template<typename T>
  1542. struct StringMaker<std::optional<T> > {
  1543. static std::string convert(const std::optional<T>& optional) {
  1544. ReusableStringStream rss;
  1545. if (optional.has_value()) {
  1546. rss << ::Catch::Detail::stringify(*optional);
  1547. } else {
  1548. rss << "{ }";
  1549. }
  1550. return rss.str();
  1551. }
  1552. };
  1553. }
  1554. #endif // CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
  1555. // Separate std::tuple specialization
  1556. #if defined(CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER)
  1557. #include <tuple>
  1558. namespace Catch {
  1559. namespace Detail {
  1560. template<
  1561. typename Tuple,
  1562. std::size_t N = 0,
  1563. bool = (N < std::tuple_size<Tuple>::value)
  1564. >
  1565. struct TupleElementPrinter {
  1566. static void print(const Tuple& tuple, std::ostream& os) {
  1567. os << (N ? ", " : " ")
  1568. << ::Catch::Detail::stringify(std::get<N>(tuple));
  1569. TupleElementPrinter<Tuple, N + 1>::print(tuple, os);
  1570. }
  1571. };
  1572. template<
  1573. typename Tuple,
  1574. std::size_t N
  1575. >
  1576. struct TupleElementPrinter<Tuple, N, false> {
  1577. static void print(const Tuple&, std::ostream&) {}
  1578. };
  1579. }
  1580. template<typename ...Types>
  1581. struct StringMaker<std::tuple<Types...>> {
  1582. static std::string convert(const std::tuple<Types...>& tuple) {
  1583. ReusableStringStream rss;
  1584. rss << '{';
  1585. Detail::TupleElementPrinter<std::tuple<Types...>>::print(tuple, rss.get());
  1586. rss << " }";
  1587. return rss.str();
  1588. }
  1589. };
  1590. }
  1591. #endif // CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
  1592. #if defined(CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_VARIANT)
  1593. #include <variant>
  1594. namespace Catch {
  1595. template<>
  1596. struct StringMaker<std::monostate> {
  1597. static std::string convert(const std::monostate&) {
  1598. return "{ }";
  1599. }
  1600. };
  1601. template<typename... Elements>
  1602. struct StringMaker<std::variant<Elements...>> {
  1603. static std::string convert(const std::variant<Elements...>& variant) {
  1604. if (variant.valueless_by_exception()) {
  1605. return "{valueless variant}";
  1606. } else {
  1607. return std::visit(
  1608. [](const auto& value) {
  1609. return ::Catch::Detail::stringify(value);
  1610. },
  1611. variant
  1612. );
  1613. }
  1614. }
  1615. };
  1616. }
  1617. #endif // CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
  1618. namespace Catch {
  1619. struct not_this_one {}; // Tag type for detecting which begin/ end are being selected
  1620. // Import begin/ end from std here so they are considered alongside the fallback (...) overloads in this namespace
  1621. using std::begin;
  1622. using std::end;
  1623. not_this_one begin( ... );
  1624. not_this_one end( ... );
  1625. template <typename T>
  1626. struct is_range {
  1627. static const bool value =
  1628. !std::is_same<decltype(begin(std::declval<T>())), not_this_one>::value &&
  1629. !std::is_same<decltype(end(std::declval<T>())), not_this_one>::value;
  1630. };
  1631. #if defined(_MANAGED) // Managed types are never ranges
  1632. template <typename T>
  1633. struct is_range<T^> {
  1634. static const bool value = false;
  1635. };
  1636. #endif
  1637. template<typename Range>
  1638. std::string rangeToString( Range const& range ) {
  1639. return ::Catch::Detail::rangeToString( begin( range ), end( range ) );
  1640. }
  1641. // Handle vector<bool> specially
  1642. template<typename Allocator>
  1643. std::string rangeToString( std::vector<bool, Allocator> const& v ) {
  1644. ReusableStringStream rss;
  1645. rss << "{ ";
  1646. bool first = true;
  1647. for( bool b : v ) {
  1648. if( first )
  1649. first = false;
  1650. else
  1651. rss << ", ";
  1652. rss << ::Catch::Detail::stringify( b );
  1653. }
  1654. rss << " }";
  1655. return rss.str();
  1656. }
  1657. template<typename R>
  1658. struct StringMaker<R, typename std::enable_if<is_range<R>::value && !::Catch::Detail::IsStreamInsertable<R>::value>::type> {
  1659. static std::string convert( R const& range ) {
  1660. return rangeToString( range );
  1661. }
  1662. };
  1663. template <typename T, int SZ>
  1664. struct StringMaker<T[SZ]> {
  1665. static std::string convert(T const(&arr)[SZ]) {
  1666. return rangeToString(arr);
  1667. }
  1668. };
  1669. } // namespace Catch
  1670. // Separate std::chrono::duration specialization
  1671. #if defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  1672. #include <ctime>
  1673. #include <ratio>
  1674. #include <chrono>
  1675. namespace Catch {
  1676. template <class Ratio>
  1677. struct ratio_string {
  1678. static std::string symbol();
  1679. };
  1680. template <class Ratio>
  1681. std::string ratio_string<Ratio>::symbol() {
  1682. Catch::ReusableStringStream rss;
  1683. rss << '[' << Ratio::num << '/'
  1684. << Ratio::den << ']';
  1685. return rss.str();
  1686. }
  1687. template <>
  1688. struct ratio_string<std::atto> {
  1689. static std::string symbol();
  1690. };
  1691. template <>
  1692. struct ratio_string<std::femto> {
  1693. static std::string symbol();
  1694. };
  1695. template <>
  1696. struct ratio_string<std::pico> {
  1697. static std::string symbol();
  1698. };
  1699. template <>
  1700. struct ratio_string<std::nano> {
  1701. static std::string symbol();
  1702. };
  1703. template <>
  1704. struct ratio_string<std::micro> {
  1705. static std::string symbol();
  1706. };
  1707. template <>
  1708. struct ratio_string<std::milli> {
  1709. static std::string symbol();
  1710. };
  1711. ////////////
  1712. // std::chrono::duration specializations
  1713. template<typename Value, typename Ratio>
  1714. struct StringMaker<std::chrono::duration<Value, Ratio>> {
  1715. static std::string convert(std::chrono::duration<Value, Ratio> const& duration) {
  1716. ReusableStringStream rss;
  1717. rss << duration.count() << ' ' << ratio_string<Ratio>::symbol() << 's';
  1718. return rss.str();
  1719. }
  1720. };
  1721. template<typename Value>
  1722. struct StringMaker<std::chrono::duration<Value, std::ratio<1>>> {
  1723. static std::string convert(std::chrono::duration<Value, std::ratio<1>> const& duration) {
  1724. ReusableStringStream rss;
  1725. rss << duration.count() << " s";
  1726. return rss.str();
  1727. }
  1728. };
  1729. template<typename Value>
  1730. struct StringMaker<std::chrono::duration<Value, std::ratio<60>>> {
  1731. static std::string convert(std::chrono::duration<Value, std::ratio<60>> const& duration) {
  1732. ReusableStringStream rss;
  1733. rss << duration.count() << " m";
  1734. return rss.str();
  1735. }
  1736. };
  1737. template<typename Value>
  1738. struct StringMaker<std::chrono::duration<Value, std::ratio<3600>>> {
  1739. static std::string convert(std::chrono::duration<Value, std::ratio<3600>> const& duration) {
  1740. ReusableStringStream rss;
  1741. rss << duration.count() << " h";
  1742. return rss.str();
  1743. }
  1744. };
  1745. ////////////
  1746. // std::chrono::time_point specialization
  1747. // Generic time_point cannot be specialized, only std::chrono::time_point<system_clock>
  1748. template<typename Clock, typename Duration>
  1749. struct StringMaker<std::chrono::time_point<Clock, Duration>> {
  1750. static std::string convert(std::chrono::time_point<Clock, Duration> const& time_point) {
  1751. return ::Catch::Detail::stringify(time_point.time_since_epoch()) + " since epoch";
  1752. }
  1753. };
  1754. // std::chrono::time_point<system_clock> specialization
  1755. template<typename Duration>
  1756. struct StringMaker<std::chrono::time_point<std::chrono::system_clock, Duration>> {
  1757. static std::string convert(std::chrono::time_point<std::chrono::system_clock, Duration> const& time_point) {
  1758. auto converted = std::chrono::system_clock::to_time_t(time_point);
  1759. #ifdef _MSC_VER
  1760. std::tm timeInfo = {};
  1761. gmtime_s(&timeInfo, &converted);
  1762. #else
  1763. std::tm* timeInfo = std::gmtime(&converted);
  1764. #endif
  1765. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  1766. char timeStamp[timeStampSize];
  1767. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  1768. #ifdef _MSC_VER
  1769. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  1770. #else
  1771. std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
  1772. #endif
  1773. return std::string(timeStamp);
  1774. }
  1775. };
  1776. }
  1777. #endif // CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  1778. #define INTERNAL_CATCH_REGISTER_ENUM( enumName, ... ) \
  1779. namespace Catch { \
  1780. template<> struct StringMaker<enumName> { \
  1781. static std::string convert( enumName value ) { \
  1782. static const auto& enumInfo = ::Catch::getMutableRegistryHub().getMutableEnumValuesRegistry().registerEnum( #enumName, #__VA_ARGS__, { __VA_ARGS__ } ); \
  1783. return enumInfo.lookup( static_cast<int>( value ) ); \
  1784. } \
  1785. }; \
  1786. }
  1787. #define CATCH_REGISTER_ENUM( enumName, ... ) INTERNAL_CATCH_REGISTER_ENUM( enumName, __VA_ARGS__ )
  1788. #ifdef _MSC_VER
  1789. #pragma warning(pop)
  1790. #endif
  1791. // end catch_tostring.h
  1792. #include <iosfwd>
  1793. #ifdef _MSC_VER
  1794. #pragma warning(push)
  1795. #pragma warning(disable:4389) // '==' : signed/unsigned mismatch
  1796. #pragma warning(disable:4018) // more "signed/unsigned mismatch"
  1797. #pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform)
  1798. #pragma warning(disable:4180) // qualifier applied to function type has no meaning
  1799. #pragma warning(disable:4800) // Forcing result to true or false
  1800. #endif
  1801. namespace Catch {
  1802. struct ITransientExpression {
  1803. auto isBinaryExpression() const -> bool { return m_isBinaryExpression; }
  1804. auto getResult() const -> bool { return m_result; }
  1805. virtual void streamReconstructedExpression( std::ostream &os ) const = 0;
  1806. ITransientExpression( bool isBinaryExpression, bool result )
  1807. : m_isBinaryExpression( isBinaryExpression ),
  1808. m_result( result )
  1809. {}
  1810. // We don't actually need a virtual destructor, but many static analysers
  1811. // complain if it's not here :-(
  1812. virtual ~ITransientExpression();
  1813. bool m_isBinaryExpression;
  1814. bool m_result;
  1815. };
  1816. void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs );
  1817. template<typename LhsT, typename RhsT>
  1818. class BinaryExpr : public ITransientExpression {
  1819. LhsT m_lhs;
  1820. StringRef m_op;
  1821. RhsT m_rhs;
  1822. void streamReconstructedExpression( std::ostream &os ) const override {
  1823. formatReconstructedExpression
  1824. ( os, Catch::Detail::stringify( m_lhs ), m_op, Catch::Detail::stringify( m_rhs ) );
  1825. }
  1826. public:
  1827. BinaryExpr( bool comparisonResult, LhsT lhs, StringRef op, RhsT rhs )
  1828. : ITransientExpression{ true, comparisonResult },
  1829. m_lhs( lhs ),
  1830. m_op( op ),
  1831. m_rhs( rhs )
  1832. {}
  1833. template<typename T>
  1834. auto operator && ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1835. static_assert(always_false<T>::value,
  1836. "chained comparisons are not supported inside assertions, "
  1837. "wrap the expression inside parentheses, or decompose it");
  1838. }
  1839. template<typename T>
  1840. auto operator || ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1841. static_assert(always_false<T>::value,
  1842. "chained comparisons are not supported inside assertions, "
  1843. "wrap the expression inside parentheses, or decompose it");
  1844. }
  1845. template<typename T>
  1846. auto operator == ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1847. static_assert(always_false<T>::value,
  1848. "chained comparisons are not supported inside assertions, "
  1849. "wrap the expression inside parentheses, or decompose it");
  1850. }
  1851. template<typename T>
  1852. auto operator != ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1853. static_assert(always_false<T>::value,
  1854. "chained comparisons are not supported inside assertions, "
  1855. "wrap the expression inside parentheses, or decompose it");
  1856. }
  1857. template<typename T>
  1858. auto operator > ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1859. static_assert(always_false<T>::value,
  1860. "chained comparisons are not supported inside assertions, "
  1861. "wrap the expression inside parentheses, or decompose it");
  1862. }
  1863. template<typename T>
  1864. auto operator < ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1865. static_assert(always_false<T>::value,
  1866. "chained comparisons are not supported inside assertions, "
  1867. "wrap the expression inside parentheses, or decompose it");
  1868. }
  1869. template<typename T>
  1870. auto operator >= ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1871. static_assert(always_false<T>::value,
  1872. "chained comparisons are not supported inside assertions, "
  1873. "wrap the expression inside parentheses, or decompose it");
  1874. }
  1875. template<typename T>
  1876. auto operator <= ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1877. static_assert(always_false<T>::value,
  1878. "chained comparisons are not supported inside assertions, "
  1879. "wrap the expression inside parentheses, or decompose it");
  1880. }
  1881. };
  1882. template<typename LhsT>
  1883. class UnaryExpr : public ITransientExpression {
  1884. LhsT m_lhs;
  1885. void streamReconstructedExpression( std::ostream &os ) const override {
  1886. os << Catch::Detail::stringify( m_lhs );
  1887. }
  1888. public:
  1889. explicit UnaryExpr( LhsT lhs )
  1890. : ITransientExpression{ false, static_cast<bool>(lhs) },
  1891. m_lhs( lhs )
  1892. {}
  1893. };
  1894. // Specialised comparison functions to handle equality comparisons between ints and pointers (NULL deduces as an int)
  1895. template<typename LhsT, typename RhsT>
  1896. auto compareEqual( LhsT const& lhs, RhsT const& rhs ) -> bool { return static_cast<bool>(lhs == rhs); }
  1897. template<typename T>
  1898. auto compareEqual( T* const& lhs, int rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
  1899. template<typename T>
  1900. auto compareEqual( T* const& lhs, long rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
  1901. template<typename T>
  1902. auto compareEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
  1903. template<typename T>
  1904. auto compareEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
  1905. template<typename LhsT, typename RhsT>
  1906. auto compareNotEqual( LhsT const& lhs, RhsT&& rhs ) -> bool { return static_cast<bool>(lhs != rhs); }
  1907. template<typename T>
  1908. auto compareNotEqual( T* const& lhs, int rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
  1909. template<typename T>
  1910. auto compareNotEqual( T* const& lhs, long rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
  1911. template<typename T>
  1912. auto compareNotEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
  1913. template<typename T>
  1914. auto compareNotEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
  1915. template<typename LhsT>
  1916. class ExprLhs {
  1917. LhsT m_lhs;
  1918. public:
  1919. explicit ExprLhs( LhsT lhs ) : m_lhs( lhs ) {}
  1920. template<typename RhsT>
  1921. auto operator == ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1922. return { compareEqual( m_lhs, rhs ), m_lhs, "==", rhs };
  1923. }
  1924. auto operator == ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
  1925. return { m_lhs == rhs, m_lhs, "==", rhs };
  1926. }
  1927. template<typename RhsT>
  1928. auto operator != ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1929. return { compareNotEqual( m_lhs, rhs ), m_lhs, "!=", rhs };
  1930. }
  1931. auto operator != ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
  1932. return { m_lhs != rhs, m_lhs, "!=", rhs };
  1933. }
  1934. template<typename RhsT>
  1935. auto operator > ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1936. return { static_cast<bool>(m_lhs > rhs), m_lhs, ">", rhs };
  1937. }
  1938. template<typename RhsT>
  1939. auto operator < ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1940. return { static_cast<bool>(m_lhs < rhs), m_lhs, "<", rhs };
  1941. }
  1942. template<typename RhsT>
  1943. auto operator >= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1944. return { static_cast<bool>(m_lhs >= rhs), m_lhs, ">=", rhs };
  1945. }
  1946. template<typename RhsT>
  1947. auto operator <= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1948. return { static_cast<bool>(m_lhs <= rhs), m_lhs, "<=", rhs };
  1949. }
  1950. template<typename RhsT>
  1951. auto operator && ( RhsT const& ) -> BinaryExpr<LhsT, RhsT const&> const {
  1952. static_assert(always_false<RhsT>::value,
  1953. "operator&& is not supported inside assertions, "
  1954. "wrap the expression inside parentheses, or decompose it");
  1955. }
  1956. template<typename RhsT>
  1957. auto operator || ( RhsT const& ) -> BinaryExpr<LhsT, RhsT const&> const {
  1958. static_assert(always_false<RhsT>::value,
  1959. "operator|| is not supported inside assertions, "
  1960. "wrap the expression inside parentheses, or decompose it");
  1961. }
  1962. auto makeUnaryExpr() const -> UnaryExpr<LhsT> {
  1963. return UnaryExpr<LhsT>{ m_lhs };
  1964. }
  1965. };
  1966. void handleExpression( ITransientExpression const& expr );
  1967. template<typename T>
  1968. void handleExpression( ExprLhs<T> const& expr ) {
  1969. handleExpression( expr.makeUnaryExpr() );
  1970. }
  1971. struct Decomposer {
  1972. template<typename T>
  1973. auto operator <= ( T const& lhs ) -> ExprLhs<T const&> {
  1974. return ExprLhs<T const&>{ lhs };
  1975. }
  1976. auto operator <=( bool value ) -> ExprLhs<bool> {
  1977. return ExprLhs<bool>{ value };
  1978. }
  1979. };
  1980. } // end namespace Catch
  1981. #ifdef _MSC_VER
  1982. #pragma warning(pop)
  1983. #endif
  1984. // end catch_decomposer.h
  1985. // start catch_interfaces_capture.h
  1986. #include <string>
  1987. #include <chrono>
  1988. namespace Catch {
  1989. class AssertionResult;
  1990. struct AssertionInfo;
  1991. struct SectionInfo;
  1992. struct SectionEndInfo;
  1993. struct MessageInfo;
  1994. struct MessageBuilder;
  1995. struct Counts;
  1996. struct AssertionReaction;
  1997. struct SourceLineInfo;
  1998. struct ITransientExpression;
  1999. struct IGeneratorTracker;
  2000. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  2001. struct BenchmarkInfo;
  2002. template <typename Duration = std::chrono::duration<double, std::nano>>
  2003. struct BenchmarkStats;
  2004. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  2005. struct IResultCapture {
  2006. virtual ~IResultCapture();
  2007. virtual bool sectionStarted( SectionInfo const& sectionInfo,
  2008. Counts& assertions ) = 0;
  2009. virtual void sectionEnded( SectionEndInfo const& endInfo ) = 0;
  2010. virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) = 0;
  2011. virtual auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& = 0;
  2012. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  2013. virtual void benchmarkPreparing( std::string const& name ) = 0;
  2014. virtual void benchmarkStarting( BenchmarkInfo const& info ) = 0;
  2015. virtual void benchmarkEnded( BenchmarkStats<> const& stats ) = 0;
  2016. virtual void benchmarkFailed( std::string const& error ) = 0;
  2017. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  2018. virtual void pushScopedMessage( MessageInfo const& message ) = 0;
  2019. virtual void popScopedMessage( MessageInfo const& message ) = 0;
  2020. virtual void emplaceUnscopedMessage( MessageBuilder const& builder ) = 0;
  2021. virtual void handleFatalErrorCondition( StringRef message ) = 0;
  2022. virtual void handleExpr
  2023. ( AssertionInfo const& info,
  2024. ITransientExpression const& expr,
  2025. AssertionReaction& reaction ) = 0;
  2026. virtual void handleMessage
  2027. ( AssertionInfo const& info,
  2028. ResultWas::OfType resultType,
  2029. StringRef const& message,
  2030. AssertionReaction& reaction ) = 0;
  2031. virtual void handleUnexpectedExceptionNotThrown
  2032. ( AssertionInfo const& info,
  2033. AssertionReaction& reaction ) = 0;
  2034. virtual void handleUnexpectedInflightException
  2035. ( AssertionInfo const& info,
  2036. std::string const& message,
  2037. AssertionReaction& reaction ) = 0;
  2038. virtual void handleIncomplete
  2039. ( AssertionInfo const& info ) = 0;
  2040. virtual void handleNonExpr
  2041. ( AssertionInfo const &info,
  2042. ResultWas::OfType resultType,
  2043. AssertionReaction &reaction ) = 0;
  2044. virtual bool lastAssertionPassed() = 0;
  2045. virtual void assertionPassed() = 0;
  2046. // Deprecated, do not use:
  2047. virtual std::string getCurrentTestName() const = 0;
  2048. virtual const AssertionResult* getLastResult() const = 0;
  2049. virtual void exceptionEarlyReported() = 0;
  2050. };
  2051. IResultCapture& getResultCapture();
  2052. }
  2053. // end catch_interfaces_capture.h
  2054. namespace Catch {
  2055. struct TestFailureException{};
  2056. struct AssertionResultData;
  2057. struct IResultCapture;
  2058. class RunContext;
  2059. class LazyExpression {
  2060. friend class AssertionHandler;
  2061. friend struct AssertionStats;
  2062. friend class RunContext;
  2063. ITransientExpression const* m_transientExpression = nullptr;
  2064. bool m_isNegated;
  2065. public:
  2066. LazyExpression( bool isNegated );
  2067. LazyExpression( LazyExpression const& other );
  2068. LazyExpression& operator = ( LazyExpression const& ) = delete;
  2069. explicit operator bool() const;
  2070. friend auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream&;
  2071. };
  2072. struct AssertionReaction {
  2073. bool shouldDebugBreak = false;
  2074. bool shouldThrow = false;
  2075. };
  2076. class AssertionHandler {
  2077. AssertionInfo m_assertionInfo;
  2078. AssertionReaction m_reaction;
  2079. bool m_completed = false;
  2080. IResultCapture& m_resultCapture;
  2081. public:
  2082. AssertionHandler
  2083. ( StringRef const& macroName,
  2084. SourceLineInfo const& lineInfo,
  2085. StringRef capturedExpression,
  2086. ResultDisposition::Flags resultDisposition );
  2087. ~AssertionHandler() {
  2088. if ( !m_completed ) {
  2089. m_resultCapture.handleIncomplete( m_assertionInfo );
  2090. }
  2091. }
  2092. template<typename T>
  2093. void handleExpr( ExprLhs<T> const& expr ) {
  2094. handleExpr( expr.makeUnaryExpr() );
  2095. }
  2096. void handleExpr( ITransientExpression const& expr );
  2097. void handleMessage(ResultWas::OfType resultType, StringRef const& message);
  2098. void handleExceptionThrownAsExpected();
  2099. void handleUnexpectedExceptionNotThrown();
  2100. void handleExceptionNotThrownAsExpected();
  2101. void handleThrowingCallSkipped();
  2102. void handleUnexpectedInflightException();
  2103. void complete();
  2104. void setCompleted();
  2105. // query
  2106. auto allowThrows() const -> bool;
  2107. };
  2108. void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString );
  2109. } // namespace Catch
  2110. // end catch_assertionhandler.h
  2111. // start catch_message.h
  2112. #include <string>
  2113. #include <vector>
  2114. namespace Catch {
  2115. struct MessageInfo {
  2116. MessageInfo( StringRef const& _macroName,
  2117. SourceLineInfo const& _lineInfo,
  2118. ResultWas::OfType _type );
  2119. StringRef macroName;
  2120. std::string message;
  2121. SourceLineInfo lineInfo;
  2122. ResultWas::OfType type;
  2123. unsigned int sequence;
  2124. bool operator == ( MessageInfo const& other ) const;
  2125. bool operator < ( MessageInfo const& other ) const;
  2126. private:
  2127. static unsigned int globalCount;
  2128. };
  2129. struct MessageStream {
  2130. template<typename T>
  2131. MessageStream& operator << ( T const& value ) {
  2132. m_stream << value;
  2133. return *this;
  2134. }
  2135. ReusableStringStream m_stream;
  2136. };
  2137. struct MessageBuilder : MessageStream {
  2138. MessageBuilder( StringRef const& macroName,
  2139. SourceLineInfo const& lineInfo,
  2140. ResultWas::OfType type );
  2141. template<typename T>
  2142. MessageBuilder& operator << ( T const& value ) {
  2143. m_stream << value;
  2144. return *this;
  2145. }
  2146. MessageInfo m_info;
  2147. };
  2148. class ScopedMessage {
  2149. public:
  2150. explicit ScopedMessage( MessageBuilder const& builder );
  2151. ScopedMessage( ScopedMessage& duplicate ) = delete;
  2152. ScopedMessage( ScopedMessage&& old );
  2153. ~ScopedMessage();
  2154. MessageInfo m_info;
  2155. bool m_moved;
  2156. };
  2157. class Capturer {
  2158. std::vector<MessageInfo> m_messages;
  2159. IResultCapture& m_resultCapture = getResultCapture();
  2160. size_t m_captured = 0;
  2161. public:
  2162. Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names );
  2163. ~Capturer();
  2164. void captureValue( size_t index, std::string const& value );
  2165. template<typename T>
  2166. void captureValues( size_t index, T const& value ) {
  2167. captureValue( index, Catch::Detail::stringify( value ) );
  2168. }
  2169. template<typename T, typename... Ts>
  2170. void captureValues( size_t index, T const& value, Ts const&... values ) {
  2171. captureValue( index, Catch::Detail::stringify(value) );
  2172. captureValues( index+1, values... );
  2173. }
  2174. };
  2175. } // end namespace Catch
  2176. // end catch_message.h
  2177. #if !defined(CATCH_CONFIG_DISABLE)
  2178. #if !defined(CATCH_CONFIG_DISABLE_STRINGIFICATION)
  2179. #define CATCH_INTERNAL_STRINGIFY(...) #__VA_ARGS__
  2180. #else
  2181. #define CATCH_INTERNAL_STRINGIFY(...) "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION"
  2182. #endif
  2183. #if defined(CATCH_CONFIG_FAST_COMPILE) || defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  2184. ///////////////////////////////////////////////////////////////////////////////
  2185. // Another way to speed-up compilation is to omit local try-catch for REQUIRE*
  2186. // macros.
  2187. #define INTERNAL_CATCH_TRY
  2188. #define INTERNAL_CATCH_CATCH( capturer )
  2189. #else // CATCH_CONFIG_FAST_COMPILE
  2190. #define INTERNAL_CATCH_TRY try
  2191. #define INTERNAL_CATCH_CATCH( handler ) catch(...) { handler.handleUnexpectedInflightException(); }
  2192. #endif
  2193. #define INTERNAL_CATCH_REACT( handler ) handler.complete();
  2194. ///////////////////////////////////////////////////////////////////////////////
  2195. #define INTERNAL_CATCH_TEST( macroName, resultDisposition, ... ) \
  2196. do { \
  2197. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
  2198. INTERNAL_CATCH_TRY { \
  2199. CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
  2200. catchAssertionHandler.handleExpr( Catch::Decomposer() <= __VA_ARGS__ ); \
  2201. CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
  2202. } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
  2203. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2204. } 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
  2205. // The double negation silences MSVC's C4800 warning, the static_cast forces short-circuit evaluation if the type has overloaded &&.
  2206. ///////////////////////////////////////////////////////////////////////////////
  2207. #define INTERNAL_CATCH_IF( macroName, resultDisposition, ... ) \
  2208. INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
  2209. if( Catch::getResultCapture().lastAssertionPassed() )
  2210. ///////////////////////////////////////////////////////////////////////////////
  2211. #define INTERNAL_CATCH_ELSE( macroName, resultDisposition, ... ) \
  2212. INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
  2213. if( !Catch::getResultCapture().lastAssertionPassed() )
  2214. ///////////////////////////////////////////////////////////////////////////////
  2215. #define INTERNAL_CATCH_NO_THROW( macroName, resultDisposition, ... ) \
  2216. do { \
  2217. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
  2218. try { \
  2219. static_cast<void>(__VA_ARGS__); \
  2220. catchAssertionHandler.handleExceptionNotThrownAsExpected(); \
  2221. } \
  2222. catch( ... ) { \
  2223. catchAssertionHandler.handleUnexpectedInflightException(); \
  2224. } \
  2225. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2226. } while( false )
  2227. ///////////////////////////////////////////////////////////////////////////////
  2228. #define INTERNAL_CATCH_THROWS( macroName, resultDisposition, ... ) \
  2229. do { \
  2230. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition); \
  2231. if( catchAssertionHandler.allowThrows() ) \
  2232. try { \
  2233. static_cast<void>(__VA_ARGS__); \
  2234. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  2235. } \
  2236. catch( ... ) { \
  2237. catchAssertionHandler.handleExceptionThrownAsExpected(); \
  2238. } \
  2239. else \
  2240. catchAssertionHandler.handleThrowingCallSkipped(); \
  2241. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2242. } while( false )
  2243. ///////////////////////////////////////////////////////////////////////////////
  2244. #define INTERNAL_CATCH_THROWS_AS( macroName, exceptionType, resultDisposition, expr ) \
  2245. do { \
  2246. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType), resultDisposition ); \
  2247. if( catchAssertionHandler.allowThrows() ) \
  2248. try { \
  2249. static_cast<void>(expr); \
  2250. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  2251. } \
  2252. catch( exceptionType const& ) { \
  2253. catchAssertionHandler.handleExceptionThrownAsExpected(); \
  2254. } \
  2255. catch( ... ) { \
  2256. catchAssertionHandler.handleUnexpectedInflightException(); \
  2257. } \
  2258. else \
  2259. catchAssertionHandler.handleThrowingCallSkipped(); \
  2260. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2261. } while( false )
  2262. ///////////////////////////////////////////////////////////////////////////////
  2263. #define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, ... ) \
  2264. do { \
  2265. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::StringRef(), resultDisposition ); \
  2266. catchAssertionHandler.handleMessage( messageType, ( Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop() ).m_stream.str() ); \
  2267. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2268. } while( false )
  2269. ///////////////////////////////////////////////////////////////////////////////
  2270. #define INTERNAL_CATCH_CAPTURE( varName, macroName, ... ) \
  2271. auto varName = Catch::Capturer( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info, #__VA_ARGS__ ); \
  2272. varName.captureValues( 0, __VA_ARGS__ )
  2273. ///////////////////////////////////////////////////////////////////////////////
  2274. #define INTERNAL_CATCH_INFO( macroName, log ) \
  2275. Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage )( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log );
  2276. ///////////////////////////////////////////////////////////////////////////////
  2277. #define INTERNAL_CATCH_UNSCOPED_INFO( macroName, log ) \
  2278. Catch::getResultCapture().emplaceUnscopedMessage( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log )
  2279. ///////////////////////////////////////////////////////////////////////////////
  2280. // Although this is matcher-based, it can be used with just a string
  2281. #define INTERNAL_CATCH_THROWS_STR_MATCHES( macroName, resultDisposition, matcher, ... ) \
  2282. do { \
  2283. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  2284. if( catchAssertionHandler.allowThrows() ) \
  2285. try { \
  2286. static_cast<void>(__VA_ARGS__); \
  2287. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  2288. } \
  2289. catch( ... ) { \
  2290. Catch::handleExceptionMatchExpr( catchAssertionHandler, matcher, #matcher##_catch_sr ); \
  2291. } \
  2292. else \
  2293. catchAssertionHandler.handleThrowingCallSkipped(); \
  2294. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2295. } while( false )
  2296. #endif // CATCH_CONFIG_DISABLE
  2297. // end catch_capture.hpp
  2298. // start catch_section.h
  2299. // start catch_section_info.h
  2300. // start catch_totals.h
  2301. #include <cstddef>
  2302. namespace Catch {
  2303. struct Counts {
  2304. Counts operator - ( Counts const& other ) const;
  2305. Counts& operator += ( Counts const& other );
  2306. std::size_t total() const;
  2307. bool allPassed() const;
  2308. bool allOk() const;
  2309. std::size_t passed = 0;
  2310. std::size_t failed = 0;
  2311. std::size_t failedButOk = 0;
  2312. };
  2313. struct Totals {
  2314. Totals operator - ( Totals const& other ) const;
  2315. Totals& operator += ( Totals const& other );
  2316. Totals delta( Totals const& prevTotals ) const;
  2317. int error = 0;
  2318. Counts assertions;
  2319. Counts testCases;
  2320. };
  2321. }
  2322. // end catch_totals.h
  2323. #include <string>
  2324. namespace Catch {
  2325. struct SectionInfo {
  2326. SectionInfo
  2327. ( SourceLineInfo const& _lineInfo,
  2328. std::string const& _name );
  2329. // Deprecated
  2330. SectionInfo
  2331. ( SourceLineInfo const& _lineInfo,
  2332. std::string const& _name,
  2333. std::string const& ) : SectionInfo( _lineInfo, _name ) {}
  2334. std::string name;
  2335. std::string description; // !Deprecated: this will always be empty
  2336. SourceLineInfo lineInfo;
  2337. };
  2338. struct SectionEndInfo {
  2339. SectionInfo sectionInfo;
  2340. Counts prevAssertions;
  2341. double durationInSeconds;
  2342. };
  2343. } // end namespace Catch
  2344. // end catch_section_info.h
  2345. // start catch_timer.h
  2346. #include <cstdint>
  2347. namespace Catch {
  2348. auto getCurrentNanosecondsSinceEpoch() -> uint64_t;
  2349. auto getEstimatedClockResolution() -> uint64_t;
  2350. class Timer {
  2351. uint64_t m_nanoseconds = 0;
  2352. public:
  2353. void start();
  2354. auto getElapsedNanoseconds() const -> uint64_t;
  2355. auto getElapsedMicroseconds() const -> uint64_t;
  2356. auto getElapsedMilliseconds() const -> unsigned int;
  2357. auto getElapsedSeconds() const -> double;
  2358. };
  2359. } // namespace Catch
  2360. // end catch_timer.h
  2361. #include <string>
  2362. namespace Catch {
  2363. class Section : NonCopyable {
  2364. public:
  2365. Section( SectionInfo const& info );
  2366. ~Section();
  2367. // This indicates whether the section should be executed or not
  2368. explicit operator bool() const;
  2369. private:
  2370. SectionInfo m_info;
  2371. std::string m_name;
  2372. Counts m_assertions;
  2373. bool m_sectionIncluded;
  2374. Timer m_timer;
  2375. };
  2376. } // end namespace Catch
  2377. #define INTERNAL_CATCH_SECTION( ... ) \
  2378. CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
  2379. if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) ) \
  2380. CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS
  2381. #define INTERNAL_CATCH_DYNAMIC_SECTION( ... ) \
  2382. CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
  2383. if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, (Catch::ReusableStringStream() << __VA_ARGS__).str() ) ) \
  2384. CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS
  2385. // end catch_section.h
  2386. // start catch_interfaces_exception.h
  2387. // start catch_interfaces_registry_hub.h
  2388. #include <string>
  2389. #include <memory>
  2390. namespace Catch {
  2391. class TestCase;
  2392. struct ITestCaseRegistry;
  2393. struct IExceptionTranslatorRegistry;
  2394. struct IExceptionTranslator;
  2395. struct IReporterRegistry;
  2396. struct IReporterFactory;
  2397. struct ITagAliasRegistry;
  2398. struct IMutableEnumValuesRegistry;
  2399. class StartupExceptionRegistry;
  2400. using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
  2401. struct IRegistryHub {
  2402. virtual ~IRegistryHub();
  2403. virtual IReporterRegistry const& getReporterRegistry() const = 0;
  2404. virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0;
  2405. virtual ITagAliasRegistry const& getTagAliasRegistry() const = 0;
  2406. virtual IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const = 0;
  2407. virtual StartupExceptionRegistry const& getStartupExceptionRegistry() const = 0;
  2408. };
  2409. struct IMutableRegistryHub {
  2410. virtual ~IMutableRegistryHub();
  2411. virtual void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) = 0;
  2412. virtual void registerListener( IReporterFactoryPtr const& factory ) = 0;
  2413. virtual void registerTest( TestCase const& testInfo ) = 0;
  2414. virtual void registerTranslator( const IExceptionTranslator* translator ) = 0;
  2415. virtual void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) = 0;
  2416. virtual void registerStartupException() noexcept = 0;
  2417. virtual IMutableEnumValuesRegistry& getMutableEnumValuesRegistry() = 0;
  2418. };
  2419. IRegistryHub const& getRegistryHub();
  2420. IMutableRegistryHub& getMutableRegistryHub();
  2421. void cleanUp();
  2422. std::string translateActiveException();
  2423. }
  2424. // end catch_interfaces_registry_hub.h
  2425. #if defined(CATCH_CONFIG_DISABLE)
  2426. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( translatorName, signature) \
  2427. static std::string translatorName( signature )
  2428. #endif
  2429. #include <exception>
  2430. #include <string>
  2431. #include <vector>
  2432. namespace Catch {
  2433. using exceptionTranslateFunction = std::string(*)();
  2434. struct IExceptionTranslator;
  2435. using ExceptionTranslators = std::vector<std::unique_ptr<IExceptionTranslator const>>;
  2436. struct IExceptionTranslator {
  2437. virtual ~IExceptionTranslator();
  2438. virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const = 0;
  2439. };
  2440. struct IExceptionTranslatorRegistry {
  2441. virtual ~IExceptionTranslatorRegistry();
  2442. virtual std::string translateActiveException() const = 0;
  2443. };
  2444. class ExceptionTranslatorRegistrar {
  2445. template<typename T>
  2446. class ExceptionTranslator : public IExceptionTranslator {
  2447. public:
  2448. ExceptionTranslator( std::string(*translateFunction)( T& ) )
  2449. : m_translateFunction( translateFunction )
  2450. {}
  2451. std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const override {
  2452. try {
  2453. if( it == itEnd )
  2454. std::rethrow_exception(std::current_exception());
  2455. else
  2456. return (*it)->translate( it+1, itEnd );
  2457. }
  2458. catch( T& ex ) {
  2459. return m_translateFunction( ex );
  2460. }
  2461. }
  2462. protected:
  2463. std::string(*m_translateFunction)( T& );
  2464. };
  2465. public:
  2466. template<typename T>
  2467. ExceptionTranslatorRegistrar( std::string(*translateFunction)( T& ) ) {
  2468. getMutableRegistryHub().registerTranslator
  2469. ( new ExceptionTranslator<T>( translateFunction ) );
  2470. }
  2471. };
  2472. }
  2473. ///////////////////////////////////////////////////////////////////////////////
  2474. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION2( translatorName, signature ) \
  2475. static std::string translatorName( signature ); \
  2476. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  2477. namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &translatorName ); } \
  2478. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  2479. static std::string translatorName( signature )
  2480. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
  2481. // end catch_interfaces_exception.h
  2482. // start catch_approx.h
  2483. #include <type_traits>
  2484. namespace Catch {
  2485. namespace Detail {
  2486. class Approx {
  2487. private:
  2488. bool equalityComparisonImpl(double other) const;
  2489. // Validates the new margin (margin >= 0)
  2490. // out-of-line to avoid including stdexcept in the header
  2491. void setMargin(double margin);
  2492. // Validates the new epsilon (0 < epsilon < 1)
  2493. // out-of-line to avoid including stdexcept in the header
  2494. void setEpsilon(double epsilon);
  2495. public:
  2496. explicit Approx ( double value );
  2497. static Approx custom();
  2498. Approx operator-() const;
  2499. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2500. Approx operator()( T const& value ) {
  2501. Approx approx( static_cast<double>(value) );
  2502. approx.m_epsilon = m_epsilon;
  2503. approx.m_margin = m_margin;
  2504. approx.m_scale = m_scale;
  2505. return approx;
  2506. }
  2507. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2508. explicit Approx( T const& value ): Approx(static_cast<double>(value))
  2509. {}
  2510. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2511. friend bool operator == ( const T& lhs, Approx const& rhs ) {
  2512. auto lhs_v = static_cast<double>(lhs);
  2513. return rhs.equalityComparisonImpl(lhs_v);
  2514. }
  2515. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2516. friend bool operator == ( Approx const& lhs, const T& rhs ) {
  2517. return operator==( rhs, lhs );
  2518. }
  2519. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2520. friend bool operator != ( T const& lhs, Approx const& rhs ) {
  2521. return !operator==( lhs, rhs );
  2522. }
  2523. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2524. friend bool operator != ( Approx const& lhs, T const& rhs ) {
  2525. return !operator==( rhs, lhs );
  2526. }
  2527. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2528. friend bool operator <= ( T const& lhs, Approx const& rhs ) {
  2529. return static_cast<double>(lhs) < rhs.m_value || lhs == rhs;
  2530. }
  2531. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2532. friend bool operator <= ( Approx const& lhs, T const& rhs ) {
  2533. return lhs.m_value < static_cast<double>(rhs) || lhs == rhs;
  2534. }
  2535. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2536. friend bool operator >= ( T const& lhs, Approx const& rhs ) {
  2537. return static_cast<double>(lhs) > rhs.m_value || lhs == rhs;
  2538. }
  2539. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2540. friend bool operator >= ( Approx const& lhs, T const& rhs ) {
  2541. return lhs.m_value > static_cast<double>(rhs) || lhs == rhs;
  2542. }
  2543. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2544. Approx& epsilon( T const& newEpsilon ) {
  2545. double epsilonAsDouble = static_cast<double>(newEpsilon);
  2546. setEpsilon(epsilonAsDouble);
  2547. return *this;
  2548. }
  2549. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2550. Approx& margin( T const& newMargin ) {
  2551. double marginAsDouble = static_cast<double>(newMargin);
  2552. setMargin(marginAsDouble);
  2553. return *this;
  2554. }
  2555. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2556. Approx& scale( T const& newScale ) {
  2557. m_scale = static_cast<double>(newScale);
  2558. return *this;
  2559. }
  2560. std::string toString() const;
  2561. private:
  2562. double m_epsilon;
  2563. double m_margin;
  2564. double m_scale;
  2565. double m_value;
  2566. };
  2567. } // end namespace Detail
  2568. namespace literals {
  2569. Detail::Approx operator "" _a(long double val);
  2570. Detail::Approx operator "" _a(unsigned long long val);
  2571. } // end namespace literals
  2572. template<>
  2573. struct StringMaker<Catch::Detail::Approx> {
  2574. static std::string convert(Catch::Detail::Approx const& value);
  2575. };
  2576. } // end namespace Catch
  2577. // end catch_approx.h
  2578. // start catch_string_manip.h
  2579. #include <string>
  2580. #include <iosfwd>
  2581. #include <vector>
  2582. namespace Catch {
  2583. bool startsWith( std::string const& s, std::string const& prefix );
  2584. bool startsWith( std::string const& s, char prefix );
  2585. bool endsWith( std::string const& s, std::string const& suffix );
  2586. bool endsWith( std::string const& s, char suffix );
  2587. bool contains( std::string const& s, std::string const& infix );
  2588. void toLowerInPlace( std::string& s );
  2589. std::string toLower( std::string const& s );
  2590. std::string trim( std::string const& str );
  2591. // !!! Be aware, returns refs into original string - make sure original string outlives them
  2592. std::vector<StringRef> splitStringRef( StringRef str, char delimiter );
  2593. bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis );
  2594. struct pluralise {
  2595. pluralise( std::size_t count, std::string const& label );
  2596. friend std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser );
  2597. std::size_t m_count;
  2598. std::string m_label;
  2599. };
  2600. }
  2601. // end catch_string_manip.h
  2602. #ifndef CATCH_CONFIG_DISABLE_MATCHERS
  2603. // start catch_capture_matchers.h
  2604. // start catch_matchers.h
  2605. #include <string>
  2606. #include <vector>
  2607. namespace Catch {
  2608. namespace Matchers {
  2609. namespace Impl {
  2610. template<typename ArgT> struct MatchAllOf;
  2611. template<typename ArgT> struct MatchAnyOf;
  2612. template<typename ArgT> struct MatchNotOf;
  2613. class MatcherUntypedBase {
  2614. public:
  2615. MatcherUntypedBase() = default;
  2616. MatcherUntypedBase ( MatcherUntypedBase const& ) = default;
  2617. MatcherUntypedBase& operator = ( MatcherUntypedBase const& ) = delete;
  2618. std::string toString() const;
  2619. protected:
  2620. virtual ~MatcherUntypedBase();
  2621. virtual std::string describe() const = 0;
  2622. mutable std::string m_cachedToString;
  2623. };
  2624. #ifdef __clang__
  2625. # pragma clang diagnostic push
  2626. # pragma clang diagnostic ignored "-Wnon-virtual-dtor"
  2627. #endif
  2628. template<typename ObjectT>
  2629. struct MatcherMethod {
  2630. virtual bool match( ObjectT const& arg ) const = 0;
  2631. };
  2632. #ifdef __clang__
  2633. # pragma clang diagnostic pop
  2634. #endif
  2635. template<typename T>
  2636. struct MatcherBase : MatcherUntypedBase, MatcherMethod<T> {
  2637. MatchAllOf<T> operator && ( MatcherBase const& other ) const;
  2638. MatchAnyOf<T> operator || ( MatcherBase const& other ) const;
  2639. MatchNotOf<T> operator ! () const;
  2640. };
  2641. template<typename ArgT>
  2642. struct MatchAllOf : MatcherBase<ArgT> {
  2643. bool match( ArgT const& arg ) const override {
  2644. for( auto matcher : m_matchers ) {
  2645. if (!matcher->match(arg))
  2646. return false;
  2647. }
  2648. return true;
  2649. }
  2650. std::string describe() const override {
  2651. std::string description;
  2652. description.reserve( 4 + m_matchers.size()*32 );
  2653. description += "( ";
  2654. bool first = true;
  2655. for( auto matcher : m_matchers ) {
  2656. if( first )
  2657. first = false;
  2658. else
  2659. description += " and ";
  2660. description += matcher->toString();
  2661. }
  2662. description += " )";
  2663. return description;
  2664. }
  2665. MatchAllOf<ArgT>& operator && ( MatcherBase<ArgT> const& other ) {
  2666. m_matchers.push_back( &other );
  2667. return *this;
  2668. }
  2669. std::vector<MatcherBase<ArgT> const*> m_matchers;
  2670. };
  2671. template<typename ArgT>
  2672. struct MatchAnyOf : MatcherBase<ArgT> {
  2673. bool match( ArgT const& arg ) const override {
  2674. for( auto matcher : m_matchers ) {
  2675. if (matcher->match(arg))
  2676. return true;
  2677. }
  2678. return false;
  2679. }
  2680. std::string describe() const override {
  2681. std::string description;
  2682. description.reserve( 4 + m_matchers.size()*32 );
  2683. description += "( ";
  2684. bool first = true;
  2685. for( auto matcher : m_matchers ) {
  2686. if( first )
  2687. first = false;
  2688. else
  2689. description += " or ";
  2690. description += matcher->toString();
  2691. }
  2692. description += " )";
  2693. return description;
  2694. }
  2695. MatchAnyOf<ArgT>& operator || ( MatcherBase<ArgT> const& other ) {
  2696. m_matchers.push_back( &other );
  2697. return *this;
  2698. }
  2699. std::vector<MatcherBase<ArgT> const*> m_matchers;
  2700. };
  2701. template<typename ArgT>
  2702. struct MatchNotOf : MatcherBase<ArgT> {
  2703. MatchNotOf( MatcherBase<ArgT> const& underlyingMatcher ) : m_underlyingMatcher( underlyingMatcher ) {}
  2704. bool match( ArgT const& arg ) const override {
  2705. return !m_underlyingMatcher.match( arg );
  2706. }
  2707. std::string describe() const override {
  2708. return "not " + m_underlyingMatcher.toString();
  2709. }
  2710. MatcherBase<ArgT> const& m_underlyingMatcher;
  2711. };
  2712. template<typename T>
  2713. MatchAllOf<T> MatcherBase<T>::operator && ( MatcherBase const& other ) const {
  2714. return MatchAllOf<T>() && *this && other;
  2715. }
  2716. template<typename T>
  2717. MatchAnyOf<T> MatcherBase<T>::operator || ( MatcherBase const& other ) const {
  2718. return MatchAnyOf<T>() || *this || other;
  2719. }
  2720. template<typename T>
  2721. MatchNotOf<T> MatcherBase<T>::operator ! () const {
  2722. return MatchNotOf<T>( *this );
  2723. }
  2724. } // namespace Impl
  2725. } // namespace Matchers
  2726. using namespace Matchers;
  2727. using Matchers::Impl::MatcherBase;
  2728. } // namespace Catch
  2729. // end catch_matchers.h
  2730. // start catch_matchers_floating.h
  2731. #include <type_traits>
  2732. #include <cmath>
  2733. namespace Catch {
  2734. namespace Matchers {
  2735. namespace Floating {
  2736. enum class FloatingPointKind : uint8_t;
  2737. struct WithinAbsMatcher : MatcherBase<double> {
  2738. WithinAbsMatcher(double target, double margin);
  2739. bool match(double const& matchee) const override;
  2740. std::string describe() const override;
  2741. private:
  2742. double m_target;
  2743. double m_margin;
  2744. };
  2745. struct WithinUlpsMatcher : MatcherBase<double> {
  2746. WithinUlpsMatcher(double target, int ulps, FloatingPointKind baseType);
  2747. bool match(double const& matchee) const override;
  2748. std::string describe() const override;
  2749. private:
  2750. double m_target;
  2751. int m_ulps;
  2752. FloatingPointKind m_type;
  2753. };
  2754. } // namespace Floating
  2755. // The following functions create the actual matcher objects.
  2756. // This allows the types to be inferred
  2757. Floating::WithinUlpsMatcher WithinULP(double target, int maxUlpDiff);
  2758. Floating::WithinUlpsMatcher WithinULP(float target, int maxUlpDiff);
  2759. Floating::WithinAbsMatcher WithinAbs(double target, double margin);
  2760. } // namespace Matchers
  2761. } // namespace Catch
  2762. // end catch_matchers_floating.h
  2763. // start catch_matchers_generic.hpp
  2764. #include <functional>
  2765. #include <string>
  2766. namespace Catch {
  2767. namespace Matchers {
  2768. namespace Generic {
  2769. namespace Detail {
  2770. std::string finalizeDescription(const std::string& desc);
  2771. }
  2772. template <typename T>
  2773. class PredicateMatcher : public MatcherBase<T> {
  2774. std::function<bool(T const&)> m_predicate;
  2775. std::string m_description;
  2776. public:
  2777. PredicateMatcher(std::function<bool(T const&)> const& elem, std::string const& descr)
  2778. :m_predicate(std::move(elem)),
  2779. m_description(Detail::finalizeDescription(descr))
  2780. {}
  2781. bool match( T const& item ) const override {
  2782. return m_predicate(item);
  2783. }
  2784. std::string describe() const override {
  2785. return m_description;
  2786. }
  2787. };
  2788. } // namespace Generic
  2789. // The following functions create the actual matcher objects.
  2790. // The user has to explicitly specify type to the function, because
  2791. // inferring std::function<bool(T const&)> is hard (but possible) and
  2792. // requires a lot of TMP.
  2793. template<typename T>
  2794. Generic::PredicateMatcher<T> Predicate(std::function<bool(T const&)> const& predicate, std::string const& description = "") {
  2795. return Generic::PredicateMatcher<T>(predicate, description);
  2796. }
  2797. } // namespace Matchers
  2798. } // namespace Catch
  2799. // end catch_matchers_generic.hpp
  2800. // start catch_matchers_string.h
  2801. #include <string>
  2802. namespace Catch {
  2803. namespace Matchers {
  2804. namespace StdString {
  2805. struct CasedString
  2806. {
  2807. CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity );
  2808. std::string adjustString( std::string const& str ) const;
  2809. std::string caseSensitivitySuffix() const;
  2810. CaseSensitive::Choice m_caseSensitivity;
  2811. std::string m_str;
  2812. };
  2813. struct StringMatcherBase : MatcherBase<std::string> {
  2814. StringMatcherBase( std::string const& operation, CasedString const& comparator );
  2815. std::string describe() const override;
  2816. CasedString m_comparator;
  2817. std::string m_operation;
  2818. };
  2819. struct EqualsMatcher : StringMatcherBase {
  2820. EqualsMatcher( CasedString const& comparator );
  2821. bool match( std::string const& source ) const override;
  2822. };
  2823. struct ContainsMatcher : StringMatcherBase {
  2824. ContainsMatcher( CasedString const& comparator );
  2825. bool match( std::string const& source ) const override;
  2826. };
  2827. struct StartsWithMatcher : StringMatcherBase {
  2828. StartsWithMatcher( CasedString const& comparator );
  2829. bool match( std::string const& source ) const override;
  2830. };
  2831. struct EndsWithMatcher : StringMatcherBase {
  2832. EndsWithMatcher( CasedString const& comparator );
  2833. bool match( std::string const& source ) const override;
  2834. };
  2835. struct RegexMatcher : MatcherBase<std::string> {
  2836. RegexMatcher( std::string regex, CaseSensitive::Choice caseSensitivity );
  2837. bool match( std::string const& matchee ) const override;
  2838. std::string describe() const override;
  2839. private:
  2840. std::string m_regex;
  2841. CaseSensitive::Choice m_caseSensitivity;
  2842. };
  2843. } // namespace StdString
  2844. // The following functions create the actual matcher objects.
  2845. // This allows the types to be inferred
  2846. StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2847. StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2848. StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2849. StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2850. StdString::RegexMatcher Matches( std::string const& regex, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2851. } // namespace Matchers
  2852. } // namespace Catch
  2853. // end catch_matchers_string.h
  2854. // start catch_matchers_vector.h
  2855. #include <algorithm>
  2856. namespace Catch {
  2857. namespace Matchers {
  2858. namespace Vector {
  2859. template<typename T>
  2860. struct ContainsElementMatcher : MatcherBase<std::vector<T>> {
  2861. ContainsElementMatcher(T const &comparator) : m_comparator( comparator) {}
  2862. bool match(std::vector<T> const &v) const override {
  2863. for (auto const& el : v) {
  2864. if (el == m_comparator) {
  2865. return true;
  2866. }
  2867. }
  2868. return false;
  2869. }
  2870. std::string describe() const override {
  2871. return "Contains: " + ::Catch::Detail::stringify( m_comparator );
  2872. }
  2873. T const& m_comparator;
  2874. };
  2875. template<typename T>
  2876. struct ContainsMatcher : MatcherBase<std::vector<T>> {
  2877. ContainsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}
  2878. bool match(std::vector<T> const &v) const override {
  2879. // !TBD: see note in EqualsMatcher
  2880. if (m_comparator.size() > v.size())
  2881. return false;
  2882. for (auto const& comparator : m_comparator) {
  2883. auto present = false;
  2884. for (const auto& el : v) {
  2885. if (el == comparator) {
  2886. present = true;
  2887. break;
  2888. }
  2889. }
  2890. if (!present) {
  2891. return false;
  2892. }
  2893. }
  2894. return true;
  2895. }
  2896. std::string describe() const override {
  2897. return "Contains: " + ::Catch::Detail::stringify( m_comparator );
  2898. }
  2899. std::vector<T> const& m_comparator;
  2900. };
  2901. template<typename T>
  2902. struct EqualsMatcher : MatcherBase<std::vector<T>> {
  2903. EqualsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}
  2904. bool match(std::vector<T> const &v) const override {
  2905. // !TBD: This currently works if all elements can be compared using !=
  2906. // - a more general approach would be via a compare template that defaults
  2907. // to using !=. but could be specialised for, e.g. std::vector<T> etc
  2908. // - then just call that directly
  2909. if (m_comparator.size() != v.size())
  2910. return false;
  2911. for (std::size_t i = 0; i < v.size(); ++i)
  2912. if (m_comparator[i] != v[i])
  2913. return false;
  2914. return true;
  2915. }
  2916. std::string describe() const override {
  2917. return "Equals: " + ::Catch::Detail::stringify( m_comparator );
  2918. }
  2919. std::vector<T> const& m_comparator;
  2920. };
  2921. template<typename T>
  2922. struct ApproxMatcher : MatcherBase<std::vector<T>> {
  2923. ApproxMatcher(std::vector<T> const& comparator) : m_comparator( comparator ) {}
  2924. bool match(std::vector<T> const &v) const override {
  2925. if (m_comparator.size() != v.size())
  2926. return false;
  2927. for (std::size_t i = 0; i < v.size(); ++i)
  2928. if (m_comparator[i] != approx(v[i]))
  2929. return false;
  2930. return true;
  2931. }
  2932. std::string describe() const override {
  2933. return "is approx: " + ::Catch::Detail::stringify( m_comparator );
  2934. }
  2935. template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2936. ApproxMatcher& epsilon( T const& newEpsilon ) {
  2937. approx.epsilon(newEpsilon);
  2938. return *this;
  2939. }
  2940. template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2941. ApproxMatcher& margin( T const& newMargin ) {
  2942. approx.margin(newMargin);
  2943. return *this;
  2944. }
  2945. template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2946. ApproxMatcher& scale( T const& newScale ) {
  2947. approx.scale(newScale);
  2948. return *this;
  2949. }
  2950. std::vector<T> const& m_comparator;
  2951. mutable Catch::Detail::Approx approx = Catch::Detail::Approx::custom();
  2952. };
  2953. template<typename T>
  2954. struct UnorderedEqualsMatcher : MatcherBase<std::vector<T>> {
  2955. UnorderedEqualsMatcher(std::vector<T> const& target) : m_target(target) {}
  2956. bool match(std::vector<T> const& vec) const override {
  2957. // Note: This is a reimplementation of std::is_permutation,
  2958. // because I don't want to include <algorithm> inside the common path
  2959. if (m_target.size() != vec.size()) {
  2960. return false;
  2961. }
  2962. return std::is_permutation(m_target.begin(), m_target.end(), vec.begin());
  2963. }
  2964. std::string describe() const override {
  2965. return "UnorderedEquals: " + ::Catch::Detail::stringify(m_target);
  2966. }
  2967. private:
  2968. std::vector<T> const& m_target;
  2969. };
  2970. } // namespace Vector
  2971. // The following functions create the actual matcher objects.
  2972. // This allows the types to be inferred
  2973. template<typename T>
  2974. Vector::ContainsMatcher<T> Contains( std::vector<T> const& comparator ) {
  2975. return Vector::ContainsMatcher<T>( comparator );
  2976. }
  2977. template<typename T>
  2978. Vector::ContainsElementMatcher<T> VectorContains( T const& comparator ) {
  2979. return Vector::ContainsElementMatcher<T>( comparator );
  2980. }
  2981. template<typename T>
  2982. Vector::EqualsMatcher<T> Equals( std::vector<T> const& comparator ) {
  2983. return Vector::EqualsMatcher<T>( comparator );
  2984. }
  2985. template<typename T>
  2986. Vector::ApproxMatcher<T> Approx( std::vector<T> const& comparator ) {
  2987. return Vector::ApproxMatcher<T>( comparator );
  2988. }
  2989. template<typename T>
  2990. Vector::UnorderedEqualsMatcher<T> UnorderedEquals(std::vector<T> const& target) {
  2991. return Vector::UnorderedEqualsMatcher<T>(target);
  2992. }
  2993. } // namespace Matchers
  2994. } // namespace Catch
  2995. // end catch_matchers_vector.h
  2996. namespace Catch {
  2997. template<typename ArgT, typename MatcherT>
  2998. class MatchExpr : public ITransientExpression {
  2999. ArgT const& m_arg;
  3000. MatcherT m_matcher;
  3001. StringRef m_matcherString;
  3002. public:
  3003. MatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString )
  3004. : ITransientExpression{ true, matcher.match( arg ) },
  3005. m_arg( arg ),
  3006. m_matcher( matcher ),
  3007. m_matcherString( matcherString )
  3008. {}
  3009. void streamReconstructedExpression( std::ostream &os ) const override {
  3010. auto matcherAsString = m_matcher.toString();
  3011. os << Catch::Detail::stringify( m_arg ) << ' ';
  3012. if( matcherAsString == Detail::unprintableString )
  3013. os << m_matcherString;
  3014. else
  3015. os << matcherAsString;
  3016. }
  3017. };
  3018. using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
  3019. void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString );
  3020. template<typename ArgT, typename MatcherT>
  3021. auto makeMatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString ) -> MatchExpr<ArgT, MatcherT> {
  3022. return MatchExpr<ArgT, MatcherT>( arg, matcher, matcherString );
  3023. }
  3024. } // namespace Catch
  3025. ///////////////////////////////////////////////////////////////////////////////
  3026. #define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \
  3027. do { \
  3028. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  3029. INTERNAL_CATCH_TRY { \
  3030. catchAssertionHandler.handleExpr( Catch::makeMatchExpr( arg, matcher, #matcher##_catch_sr ) ); \
  3031. } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
  3032. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  3033. } while( false )
  3034. ///////////////////////////////////////////////////////////////////////////////
  3035. #define INTERNAL_CATCH_THROWS_MATCHES( macroName, exceptionType, resultDisposition, matcher, ... ) \
  3036. do { \
  3037. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(exceptionType) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  3038. if( catchAssertionHandler.allowThrows() ) \
  3039. try { \
  3040. static_cast<void>(__VA_ARGS__ ); \
  3041. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  3042. } \
  3043. catch( exceptionType const& ex ) { \
  3044. catchAssertionHandler.handleExpr( Catch::makeMatchExpr( ex, matcher, #matcher##_catch_sr ) ); \
  3045. } \
  3046. catch( ... ) { \
  3047. catchAssertionHandler.handleUnexpectedInflightException(); \
  3048. } \
  3049. else \
  3050. catchAssertionHandler.handleThrowingCallSkipped(); \
  3051. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  3052. } while( false )
  3053. // end catch_capture_matchers.h
  3054. #endif
  3055. // start catch_generators.hpp
  3056. // start catch_interfaces_generatortracker.h
  3057. #include <memory>
  3058. namespace Catch {
  3059. namespace Generators {
  3060. class GeneratorUntypedBase {
  3061. public:
  3062. GeneratorUntypedBase() = default;
  3063. virtual ~GeneratorUntypedBase();
  3064. // Attempts to move the generator to the next element
  3065. //
  3066. // Returns true iff the move succeeded (and a valid element
  3067. // can be retrieved).
  3068. virtual bool next() = 0;
  3069. };
  3070. using GeneratorBasePtr = std::unique_ptr<GeneratorUntypedBase>;
  3071. } // namespace Generators
  3072. struct IGeneratorTracker {
  3073. virtual ~IGeneratorTracker();
  3074. virtual auto hasGenerator() const -> bool = 0;
  3075. virtual auto getGenerator() const -> Generators::GeneratorBasePtr const& = 0;
  3076. virtual void setGenerator( Generators::GeneratorBasePtr&& generator ) = 0;
  3077. };
  3078. } // namespace Catch
  3079. // end catch_interfaces_generatortracker.h
  3080. // start catch_enforce.h
  3081. #include <exception>
  3082. namespace Catch {
  3083. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  3084. template <typename Ex>
  3085. [[noreturn]]
  3086. void throw_exception(Ex const& e) {
  3087. throw e;
  3088. }
  3089. #else // ^^ Exceptions are enabled // Exceptions are disabled vv
  3090. [[noreturn]]
  3091. void throw_exception(std::exception const& e);
  3092. #endif
  3093. [[noreturn]]
  3094. void throw_logic_error(std::string const& msg);
  3095. [[noreturn]]
  3096. void throw_domain_error(std::string const& msg);
  3097. [[noreturn]]
  3098. void throw_runtime_error(std::string const& msg);
  3099. } // namespace Catch;
  3100. #define CATCH_MAKE_MSG(...) \
  3101. (Catch::ReusableStringStream() << __VA_ARGS__).str()
  3102. #define CATCH_INTERNAL_ERROR(...) \
  3103. Catch::throw_logic_error(CATCH_MAKE_MSG( CATCH_INTERNAL_LINEINFO << ": Internal Catch2 error: " << __VA_ARGS__));
  3104. #define CATCH_ERROR(...) \
  3105. Catch::throw_domain_error(CATCH_MAKE_MSG( __VA_ARGS__ ));
  3106. #define CATCH_RUNTIME_ERROR(...) \
  3107. Catch::throw_runtime_error(CATCH_MAKE_MSG( __VA_ARGS__ ));
  3108. #define CATCH_ENFORCE( condition, ... ) \
  3109. do{ if( !(condition) ) CATCH_ERROR( __VA_ARGS__ ); } while(false)
  3110. // end catch_enforce.h
  3111. #include <memory>
  3112. #include <vector>
  3113. #include <cassert>
  3114. #include <utility>
  3115. #include <exception>
  3116. namespace Catch {
  3117. class GeneratorException : public std::exception {
  3118. const char* const m_msg = "";
  3119. public:
  3120. GeneratorException(const char* msg):
  3121. m_msg(msg)
  3122. {}
  3123. const char* what() const noexcept override final;
  3124. };
  3125. namespace Generators {
  3126. // !TBD move this into its own location?
  3127. namespace pf{
  3128. template<typename T, typename... Args>
  3129. std::unique_ptr<T> make_unique( Args&&... args ) {
  3130. return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
  3131. }
  3132. }
  3133. template<typename T>
  3134. struct IGenerator : GeneratorUntypedBase {
  3135. virtual ~IGenerator() = default;
  3136. // Returns the current element of the generator
  3137. //
  3138. // \Precondition The generator is either freshly constructed,
  3139. // or the last call to `next()` returned true
  3140. virtual T const& get() const = 0;
  3141. using type = T;
  3142. };
  3143. template<typename T>
  3144. class SingleValueGenerator final : public IGenerator<T> {
  3145. T m_value;
  3146. public:
  3147. SingleValueGenerator(T const& value) : m_value( value ) {}
  3148. SingleValueGenerator(T&& value) : m_value(std::move(value)) {}
  3149. T const& get() const override {
  3150. return m_value;
  3151. }
  3152. bool next() override {
  3153. return false;
  3154. }
  3155. };
  3156. template<typename T>
  3157. class FixedValuesGenerator final : public IGenerator<T> {
  3158. std::vector<T> m_values;
  3159. size_t m_idx = 0;
  3160. public:
  3161. FixedValuesGenerator( std::initializer_list<T> values ) : m_values( values ) {}
  3162. T const& get() const override {
  3163. return m_values[m_idx];
  3164. }
  3165. bool next() override {
  3166. ++m_idx;
  3167. return m_idx < m_values.size();
  3168. }
  3169. };
  3170. template <typename T>
  3171. class GeneratorWrapper final {
  3172. std::unique_ptr<IGenerator<T>> m_generator;
  3173. public:
  3174. GeneratorWrapper(std::unique_ptr<IGenerator<T>> generator):
  3175. m_generator(std::move(generator))
  3176. {}
  3177. T const& get() const {
  3178. return m_generator->get();
  3179. }
  3180. bool next() {
  3181. return m_generator->next();
  3182. }
  3183. };
  3184. template <typename T>
  3185. GeneratorWrapper<T> value(T&& value) {
  3186. return GeneratorWrapper<T>(pf::make_unique<SingleValueGenerator<T>>(std::forward<T>(value)));
  3187. }
  3188. template <typename T>
  3189. GeneratorWrapper<T> values(std::initializer_list<T> values) {
  3190. return GeneratorWrapper<T>(pf::make_unique<FixedValuesGenerator<T>>(values));
  3191. }
  3192. template<typename T>
  3193. class Generators : public IGenerator<T> {
  3194. std::vector<GeneratorWrapper<T>> m_generators;
  3195. size_t m_current = 0;
  3196. void populate(GeneratorWrapper<T>&& generator) {
  3197. m_generators.emplace_back(std::move(generator));
  3198. }
  3199. void populate(T&& val) {
  3200. m_generators.emplace_back(value(std::move(val)));
  3201. }
  3202. template<typename U>
  3203. void populate(U&& val) {
  3204. populate(T(std::move(val)));
  3205. }
  3206. template<typename U, typename... Gs>
  3207. void populate(U&& valueOrGenerator, Gs... moreGenerators) {
  3208. populate(std::forward<U>(valueOrGenerator));
  3209. populate(std::forward<Gs>(moreGenerators)...);
  3210. }
  3211. public:
  3212. template <typename... Gs>
  3213. Generators(Gs... moreGenerators) {
  3214. m_generators.reserve(sizeof...(Gs));
  3215. populate(std::forward<Gs>(moreGenerators)...);
  3216. }
  3217. T const& get() const override {
  3218. return m_generators[m_current].get();
  3219. }
  3220. bool next() override {
  3221. if (m_current >= m_generators.size()) {
  3222. return false;
  3223. }
  3224. const bool current_status = m_generators[m_current].next();
  3225. if (!current_status) {
  3226. ++m_current;
  3227. }
  3228. return m_current < m_generators.size();
  3229. }
  3230. };
  3231. template<typename... Ts>
  3232. GeneratorWrapper<std::tuple<Ts...>> table( std::initializer_list<std::tuple<typename std::decay<Ts>::type...>> tuples ) {
  3233. return values<std::tuple<Ts...>>( tuples );
  3234. }
  3235. // Tag type to signal that a generator sequence should convert arguments to a specific type
  3236. template <typename T>
  3237. struct as {};
  3238. template<typename T, typename... Gs>
  3239. auto makeGenerators( GeneratorWrapper<T>&& generator, Gs... moreGenerators ) -> Generators<T> {
  3240. return Generators<T>(std::move(generator), std::forward<Gs>(moreGenerators)...);
  3241. }
  3242. template<typename T>
  3243. auto makeGenerators( GeneratorWrapper<T>&& generator ) -> Generators<T> {
  3244. return Generators<T>(std::move(generator));
  3245. }
  3246. template<typename T, typename... Gs>
  3247. auto makeGenerators( T&& val, Gs... moreGenerators ) -> Generators<T> {
  3248. return makeGenerators( value( std::forward<T>( val ) ), std::forward<Gs>( moreGenerators )... );
  3249. }
  3250. template<typename T, typename U, typename... Gs>
  3251. auto makeGenerators( as<T>, U&& val, Gs... moreGenerators ) -> Generators<T> {
  3252. return makeGenerators( value( T( std::forward<U>( val ) ) ), std::forward<Gs>( moreGenerators )... );
  3253. }
  3254. auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker&;
  3255. template<typename L>
  3256. // Note: The type after -> is weird, because VS2015 cannot parse
  3257. // the expression used in the typedef inside, when it is in
  3258. // return type. Yeah.
  3259. auto generate( SourceLineInfo const& lineInfo, L const& generatorExpression ) -> decltype(std::declval<decltype(generatorExpression())>().get()) {
  3260. using UnderlyingType = typename decltype(generatorExpression())::type;
  3261. IGeneratorTracker& tracker = acquireGeneratorTracker( lineInfo );
  3262. if (!tracker.hasGenerator()) {
  3263. tracker.setGenerator(pf::make_unique<Generators<UnderlyingType>>(generatorExpression()));
  3264. }
  3265. auto const& generator = static_cast<IGenerator<UnderlyingType> const&>( *tracker.getGenerator() );
  3266. return generator.get();
  3267. }
  3268. } // namespace Generators
  3269. } // namespace Catch
  3270. #define GENERATE( ... ) \
  3271. Catch::Generators::generate( CATCH_INTERNAL_LINEINFO, [ ]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } )
  3272. #define GENERATE_COPY( ... ) \
  3273. Catch::Generators::generate( CATCH_INTERNAL_LINEINFO, [=]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } )
  3274. #define GENERATE_REF( ... ) \
  3275. Catch::Generators::generate( CATCH_INTERNAL_LINEINFO, [&]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } )
  3276. // end catch_generators.hpp
  3277. // start catch_generators_generic.hpp
  3278. namespace Catch {
  3279. namespace Generators {
  3280. template <typename T>
  3281. class TakeGenerator : public IGenerator<T> {
  3282. GeneratorWrapper<T> m_generator;
  3283. size_t m_returned = 0;
  3284. size_t m_target;
  3285. public:
  3286. TakeGenerator(size_t target, GeneratorWrapper<T>&& generator):
  3287. m_generator(std::move(generator)),
  3288. m_target(target)
  3289. {
  3290. assert(target != 0 && "Empty generators are not allowed");
  3291. }
  3292. T const& get() const override {
  3293. return m_generator.get();
  3294. }
  3295. bool next() override {
  3296. ++m_returned;
  3297. if (m_returned >= m_target) {
  3298. return false;
  3299. }
  3300. const auto success = m_generator.next();
  3301. // If the underlying generator does not contain enough values
  3302. // then we cut short as well
  3303. if (!success) {
  3304. m_returned = m_target;
  3305. }
  3306. return success;
  3307. }
  3308. };
  3309. template <typename T>
  3310. GeneratorWrapper<T> take(size_t target, GeneratorWrapper<T>&& generator) {
  3311. return GeneratorWrapper<T>(pf::make_unique<TakeGenerator<T>>(target, std::move(generator)));
  3312. }
  3313. template <typename T, typename Predicate>
  3314. class FilterGenerator : public IGenerator<T> {
  3315. GeneratorWrapper<T> m_generator;
  3316. Predicate m_predicate;
  3317. public:
  3318. template <typename P = Predicate>
  3319. FilterGenerator(P&& pred, GeneratorWrapper<T>&& generator):
  3320. m_generator(std::move(generator)),
  3321. m_predicate(std::forward<P>(pred))
  3322. {
  3323. if (!m_predicate(m_generator.get())) {
  3324. // It might happen that there are no values that pass the
  3325. // filter. In that case we throw an exception.
  3326. auto has_initial_value = next();
  3327. if (!has_initial_value) {
  3328. Catch::throw_exception(GeneratorException("No valid value found in filtered generator"));
  3329. }
  3330. }
  3331. }
  3332. T const& get() const override {
  3333. return m_generator.get();
  3334. }
  3335. bool next() override {
  3336. bool success = m_generator.next();
  3337. if (!success) {
  3338. return false;
  3339. }
  3340. while (!m_predicate(m_generator.get()) && (success = m_generator.next()) == true);
  3341. return success;
  3342. }
  3343. };
  3344. template <typename T, typename Predicate>
  3345. GeneratorWrapper<T> filter(Predicate&& pred, GeneratorWrapper<T>&& generator) {
  3346. return GeneratorWrapper<T>(std::unique_ptr<IGenerator<T>>(pf::make_unique<FilterGenerator<T, Predicate>>(std::forward<Predicate>(pred), std::move(generator))));
  3347. }
  3348. template <typename T>
  3349. class RepeatGenerator : public IGenerator<T> {
  3350. GeneratorWrapper<T> m_generator;
  3351. mutable std::vector<T> m_returned;
  3352. size_t m_target_repeats;
  3353. size_t m_current_repeat = 0;
  3354. size_t m_repeat_index = 0;
  3355. public:
  3356. RepeatGenerator(size_t repeats, GeneratorWrapper<T>&& generator):
  3357. m_generator(std::move(generator)),
  3358. m_target_repeats(repeats)
  3359. {
  3360. assert(m_target_repeats > 0 && "Repeat generator must repeat at least once");
  3361. }
  3362. T const& get() const override {
  3363. if (m_current_repeat == 0) {
  3364. m_returned.push_back(m_generator.get());
  3365. return m_returned.back();
  3366. }
  3367. return m_returned[m_repeat_index];
  3368. }
  3369. bool next() override {
  3370. // There are 2 basic cases:
  3371. // 1) We are still reading the generator
  3372. // 2) We are reading our own cache
  3373. // In the first case, we need to poke the underlying generator.
  3374. // If it happily moves, we are left in that state, otherwise it is time to start reading from our cache
  3375. if (m_current_repeat == 0) {
  3376. const auto success = m_generator.next();
  3377. if (!success) {
  3378. ++m_current_repeat;
  3379. }
  3380. return m_current_repeat < m_target_repeats;
  3381. }
  3382. // In the second case, we need to move indices forward and check that we haven't run up against the end
  3383. ++m_repeat_index;
  3384. if (m_repeat_index == m_returned.size()) {
  3385. m_repeat_index = 0;
  3386. ++m_current_repeat;
  3387. }
  3388. return m_current_repeat < m_target_repeats;
  3389. }
  3390. };
  3391. template <typename T>
  3392. GeneratorWrapper<T> repeat(size_t repeats, GeneratorWrapper<T>&& generator) {
  3393. return GeneratorWrapper<T>(pf::make_unique<RepeatGenerator<T>>(repeats, std::move(generator)));
  3394. }
  3395. template <typename T, typename U, typename Func>
  3396. class MapGenerator : public IGenerator<T> {
  3397. // TBD: provide static assert for mapping function, for friendly error message
  3398. GeneratorWrapper<U> m_generator;
  3399. Func m_function;
  3400. // To avoid returning dangling reference, we have to save the values
  3401. T m_cache;
  3402. public:
  3403. template <typename F2 = Func>
  3404. MapGenerator(F2&& function, GeneratorWrapper<U>&& generator) :
  3405. m_generator(std::move(generator)),
  3406. m_function(std::forward<F2>(function)),
  3407. m_cache(m_function(m_generator.get()))
  3408. {}
  3409. T const& get() const override {
  3410. return m_cache;
  3411. }
  3412. bool next() override {
  3413. const auto success = m_generator.next();
  3414. if (success) {
  3415. m_cache = m_function(m_generator.get());
  3416. }
  3417. return success;
  3418. }
  3419. };
  3420. #if defined(__cpp_lib_is_invocable) && __cpp_lib_is_invocable >= 201703
  3421. // std::result_of is deprecated in C++17 and removed in C++20. Hence, it is
  3422. // replaced with std::invoke_result here. Also *_t format is preferred over
  3423. // typename *::type format.
  3424. template <typename Func, typename U>
  3425. using MapFunctionReturnType = std::remove_reference_t<std::remove_cv_t<std::invoke_result_t<Func, U>>>;
  3426. #else
  3427. template <typename Func, typename U>
  3428. using MapFunctionReturnType = typename std::remove_reference<typename std::remove_cv<typename std::result_of<Func(U)>::type>::type>::type;
  3429. #endif
  3430. template <typename Func, typename U, typename T = MapFunctionReturnType<Func, U>>
  3431. GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) {
  3432. return GeneratorWrapper<T>(
  3433. pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(function), std::move(generator))
  3434. );
  3435. }
  3436. template <typename T, typename U, typename Func>
  3437. GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) {
  3438. return GeneratorWrapper<T>(
  3439. pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(function), std::move(generator))
  3440. );
  3441. }
  3442. template <typename T>
  3443. class ChunkGenerator final : public IGenerator<std::vector<T>> {
  3444. std::vector<T> m_chunk;
  3445. size_t m_chunk_size;
  3446. GeneratorWrapper<T> m_generator;
  3447. bool m_used_up = false;
  3448. public:
  3449. ChunkGenerator(size_t size, GeneratorWrapper<T> generator) :
  3450. m_chunk_size(size), m_generator(std::move(generator))
  3451. {
  3452. m_chunk.reserve(m_chunk_size);
  3453. m_chunk.push_back(m_generator.get());
  3454. for (size_t i = 1; i < m_chunk_size; ++i) {
  3455. if (!m_generator.next()) {
  3456. Catch::throw_exception(GeneratorException("Not enough values to initialize the first chunk"));
  3457. }
  3458. m_chunk.push_back(m_generator.get());
  3459. }
  3460. }
  3461. std::vector<T> const& get() const override {
  3462. return m_chunk;
  3463. }
  3464. bool next() override {
  3465. m_chunk.clear();
  3466. for (size_t idx = 0; idx < m_chunk_size; ++idx) {
  3467. if (!m_generator.next()) {
  3468. return false;
  3469. }
  3470. m_chunk.push_back(m_generator.get());
  3471. }
  3472. return true;
  3473. }
  3474. };
  3475. template <typename T>
  3476. GeneratorWrapper<std::vector<T>> chunk(size_t size, GeneratorWrapper<T>&& generator) {
  3477. return GeneratorWrapper<std::vector<T>>(
  3478. pf::make_unique<ChunkGenerator<T>>(size, std::move(generator))
  3479. );
  3480. }
  3481. } // namespace Generators
  3482. } // namespace Catch
  3483. // end catch_generators_generic.hpp
  3484. // start catch_generators_specific.hpp
  3485. // start catch_context.h
  3486. #include <memory>
  3487. namespace Catch {
  3488. struct IResultCapture;
  3489. struct IRunner;
  3490. struct IConfig;
  3491. struct IMutableContext;
  3492. using IConfigPtr = std::shared_ptr<IConfig const>;
  3493. struct IContext
  3494. {
  3495. virtual ~IContext();
  3496. virtual IResultCapture* getResultCapture() = 0;
  3497. virtual IRunner* getRunner() = 0;
  3498. virtual IConfigPtr const& getConfig() const = 0;
  3499. };
  3500. struct IMutableContext : IContext
  3501. {
  3502. virtual ~IMutableContext();
  3503. virtual void setResultCapture( IResultCapture* resultCapture ) = 0;
  3504. virtual void setRunner( IRunner* runner ) = 0;
  3505. virtual void setConfig( IConfigPtr const& config ) = 0;
  3506. private:
  3507. static IMutableContext *currentContext;
  3508. friend IMutableContext& getCurrentMutableContext();
  3509. friend void cleanUpContext();
  3510. static void createContext();
  3511. };
  3512. inline IMutableContext& getCurrentMutableContext()
  3513. {
  3514. if( !IMutableContext::currentContext )
  3515. IMutableContext::createContext();
  3516. return *IMutableContext::currentContext;
  3517. }
  3518. inline IContext& getCurrentContext()
  3519. {
  3520. return getCurrentMutableContext();
  3521. }
  3522. void cleanUpContext();
  3523. }
  3524. // end catch_context.h
  3525. // start catch_interfaces_config.h
  3526. // start catch_option.hpp
  3527. namespace Catch {
  3528. // An optional type
  3529. template<typename T>
  3530. class Option {
  3531. public:
  3532. Option() : nullableValue( nullptr ) {}
  3533. Option( T const& _value )
  3534. : nullableValue( new( storage ) T( _value ) )
  3535. {}
  3536. Option( Option const& _other )
  3537. : nullableValue( _other ? new( storage ) T( *_other ) : nullptr )
  3538. {}
  3539. ~Option() {
  3540. reset();
  3541. }
  3542. Option& operator= ( Option const& _other ) {
  3543. if( &_other != this ) {
  3544. reset();
  3545. if( _other )
  3546. nullableValue = new( storage ) T( *_other );
  3547. }
  3548. return *this;
  3549. }
  3550. Option& operator = ( T const& _value ) {
  3551. reset();
  3552. nullableValue = new( storage ) T( _value );
  3553. return *this;
  3554. }
  3555. void reset() {
  3556. if( nullableValue )
  3557. nullableValue->~T();
  3558. nullableValue = nullptr;
  3559. }
  3560. T& operator*() { return *nullableValue; }
  3561. T const& operator*() const { return *nullableValue; }
  3562. T* operator->() { return nullableValue; }
  3563. const T* operator->() const { return nullableValue; }
  3564. T valueOr( T const& defaultValue ) const {
  3565. return nullableValue ? *nullableValue : defaultValue;
  3566. }
  3567. bool some() const { return nullableValue != nullptr; }
  3568. bool none() const { return nullableValue == nullptr; }
  3569. bool operator !() const { return nullableValue == nullptr; }
  3570. explicit operator bool() const {
  3571. return some();
  3572. }
  3573. private:
  3574. T *nullableValue;
  3575. alignas(alignof(T)) char storage[sizeof(T)];
  3576. };
  3577. } // end namespace Catch
  3578. // end catch_option.hpp
  3579. #include <iosfwd>
  3580. #include <string>
  3581. #include <vector>
  3582. #include <memory>
  3583. namespace Catch {
  3584. enum class Verbosity {
  3585. Quiet = 0,
  3586. Normal,
  3587. High
  3588. };
  3589. struct WarnAbout { enum What {
  3590. Nothing = 0x00,
  3591. NoAssertions = 0x01,
  3592. NoTests = 0x02
  3593. }; };
  3594. struct ShowDurations { enum OrNot {
  3595. DefaultForReporter,
  3596. Always,
  3597. Never
  3598. }; };
  3599. struct RunTests { enum InWhatOrder {
  3600. InDeclarationOrder,
  3601. InLexicographicalOrder,
  3602. InRandomOrder
  3603. }; };
  3604. struct UseColour { enum YesOrNo {
  3605. Auto,
  3606. Yes,
  3607. No
  3608. }; };
  3609. struct WaitForKeypress { enum When {
  3610. Never,
  3611. BeforeStart = 1,
  3612. BeforeExit = 2,
  3613. BeforeStartAndExit = BeforeStart | BeforeExit
  3614. }; };
  3615. class TestSpec;
  3616. struct IConfig : NonCopyable {
  3617. virtual ~IConfig();
  3618. virtual bool allowThrows() const = 0;
  3619. virtual std::ostream& stream() const = 0;
  3620. virtual std::string name() const = 0;
  3621. virtual bool includeSuccessfulResults() const = 0;
  3622. virtual bool shouldDebugBreak() const = 0;
  3623. virtual bool warnAboutMissingAssertions() const = 0;
  3624. virtual bool warnAboutNoTests() const = 0;
  3625. virtual int abortAfter() const = 0;
  3626. virtual bool showInvisibles() const = 0;
  3627. virtual ShowDurations::OrNot showDurations() const = 0;
  3628. virtual TestSpec const& testSpec() const = 0;
  3629. virtual bool hasTestFilters() const = 0;
  3630. virtual std::vector<std::string> const& getTestsOrTags() const = 0;
  3631. virtual RunTests::InWhatOrder runOrder() const = 0;
  3632. virtual unsigned int rngSeed() const = 0;
  3633. virtual UseColour::YesOrNo useColour() const = 0;
  3634. virtual std::vector<std::string> const& getSectionsToRun() const = 0;
  3635. virtual Verbosity verbosity() const = 0;
  3636. virtual bool benchmarkNoAnalysis() const = 0;
  3637. virtual int benchmarkSamples() const = 0;
  3638. virtual double benchmarkConfidenceInterval() const = 0;
  3639. virtual unsigned int benchmarkResamples() const = 0;
  3640. };
  3641. using IConfigPtr = std::shared_ptr<IConfig const>;
  3642. }
  3643. // end catch_interfaces_config.h
  3644. #include <random>
  3645. namespace Catch {
  3646. namespace Generators {
  3647. template <typename Float>
  3648. class RandomFloatingGenerator final : public IGenerator<Float> {
  3649. // FIXME: What is the right seed?
  3650. std::minstd_rand m_rand;
  3651. std::uniform_real_distribution<Float> m_dist;
  3652. Float m_current_number;
  3653. public:
  3654. RandomFloatingGenerator(Float a, Float b):
  3655. m_rand(getCurrentContext().getConfig()->rngSeed()),
  3656. m_dist(a, b) {
  3657. static_cast<void>(next());
  3658. }
  3659. Float const& get() const override {
  3660. return m_current_number;
  3661. }
  3662. bool next() override {
  3663. m_current_number = m_dist(m_rand);
  3664. return true;
  3665. }
  3666. };
  3667. template <typename Integer>
  3668. class RandomIntegerGenerator final : public IGenerator<Integer> {
  3669. std::minstd_rand m_rand;
  3670. std::uniform_int_distribution<Integer> m_dist;
  3671. Integer m_current_number;
  3672. public:
  3673. RandomIntegerGenerator(Integer a, Integer b):
  3674. m_rand(getCurrentContext().getConfig()->rngSeed()),
  3675. m_dist(a, b) {
  3676. static_cast<void>(next());
  3677. }
  3678. Integer const& get() const override {
  3679. return m_current_number;
  3680. }
  3681. bool next() override {
  3682. m_current_number = m_dist(m_rand);
  3683. return true;
  3684. }
  3685. };
  3686. // TODO: Ideally this would be also constrained against the various char types,
  3687. // but I don't expect users to run into that in practice.
  3688. template <typename T>
  3689. typename std::enable_if<std::is_integral<T>::value && !std::is_same<T, bool>::value,
  3690. GeneratorWrapper<T>>::type
  3691. random(T a, T b) {
  3692. return GeneratorWrapper<T>(
  3693. pf::make_unique<RandomIntegerGenerator<T>>(a, b)
  3694. );
  3695. }
  3696. template <typename T>
  3697. typename std::enable_if<std::is_floating_point<T>::value,
  3698. GeneratorWrapper<T>>::type
  3699. random(T a, T b) {
  3700. return GeneratorWrapper<T>(
  3701. pf::make_unique<RandomFloatingGenerator<T>>(a, b)
  3702. );
  3703. }
  3704. template <typename T>
  3705. class RangeGenerator final : public IGenerator<T> {
  3706. T m_current;
  3707. T m_end;
  3708. T m_step;
  3709. bool m_positive;
  3710. public:
  3711. RangeGenerator(T const& start, T const& end, T const& step):
  3712. m_current(start),
  3713. m_end(end),
  3714. m_step(step),
  3715. m_positive(m_step > T(0))
  3716. {
  3717. assert(m_current != m_end && "Range start and end cannot be equal");
  3718. assert(m_step != T(0) && "Step size cannot be zero");
  3719. assert(((m_positive && m_current <= m_end) || (!m_positive && m_current >= m_end)) && "Step moves away from end");
  3720. }
  3721. RangeGenerator(T const& start, T const& end):
  3722. RangeGenerator(start, end, (start < end) ? T(1) : T(-1))
  3723. {}
  3724. T const& get() const override {
  3725. return m_current;
  3726. }
  3727. bool next() override {
  3728. m_current += m_step;
  3729. return (m_positive) ? (m_current < m_end) : (m_current > m_end);
  3730. }
  3731. };
  3732. template <typename T>
  3733. GeneratorWrapper<T> range(T const& start, T const& end, T const& step) {
  3734. static_assert(std::is_integral<T>::value && !std::is_same<T, bool>::value, "Type must be an integer");
  3735. return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end, step));
  3736. }
  3737. template <typename T>
  3738. GeneratorWrapper<T> range(T const& start, T const& end) {
  3739. static_assert(std::is_integral<T>::value && !std::is_same<T, bool>::value, "Type must be an integer");
  3740. return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end));
  3741. }
  3742. } // namespace Generators
  3743. } // namespace Catch
  3744. // end catch_generators_specific.hpp
  3745. // These files are included here so the single_include script doesn't put them
  3746. // in the conditionally compiled sections
  3747. // start catch_test_case_info.h
  3748. #include <string>
  3749. #include <vector>
  3750. #include <memory>
  3751. #ifdef __clang__
  3752. #pragma clang diagnostic push
  3753. #pragma clang diagnostic ignored "-Wpadded"
  3754. #endif
  3755. namespace Catch {
  3756. struct ITestInvoker;
  3757. struct TestCaseInfo {
  3758. enum SpecialProperties{
  3759. None = 0,
  3760. IsHidden = 1 << 1,
  3761. ShouldFail = 1 << 2,
  3762. MayFail = 1 << 3,
  3763. Throws = 1 << 4,
  3764. NonPortable = 1 << 5,
  3765. Benchmark = 1 << 6
  3766. };
  3767. TestCaseInfo( std::string const& _name,
  3768. std::string const& _className,
  3769. std::string const& _description,
  3770. std::vector<std::string> const& _tags,
  3771. SourceLineInfo const& _lineInfo );
  3772. friend void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags );
  3773. bool isHidden() const;
  3774. bool throws() const;
  3775. bool okToFail() const;
  3776. bool expectedToFail() const;
  3777. std::string tagsAsString() const;
  3778. std::string name;
  3779. std::string className;
  3780. std::string description;
  3781. std::vector<std::string> tags;
  3782. std::vector<std::string> lcaseTags;
  3783. SourceLineInfo lineInfo;
  3784. SpecialProperties properties;
  3785. };
  3786. class TestCase : public TestCaseInfo {
  3787. public:
  3788. TestCase( ITestInvoker* testCase, TestCaseInfo&& info );
  3789. TestCase withName( std::string const& _newName ) const;
  3790. void invoke() const;
  3791. TestCaseInfo const& getTestCaseInfo() const;
  3792. bool operator == ( TestCase const& other ) const;
  3793. bool operator < ( TestCase const& other ) const;
  3794. private:
  3795. std::shared_ptr<ITestInvoker> test;
  3796. };
  3797. TestCase makeTestCase( ITestInvoker* testCase,
  3798. std::string const& className,
  3799. NameAndTags const& nameAndTags,
  3800. SourceLineInfo const& lineInfo );
  3801. }
  3802. #ifdef __clang__
  3803. #pragma clang diagnostic pop
  3804. #endif
  3805. // end catch_test_case_info.h
  3806. // start catch_interfaces_runner.h
  3807. namespace Catch {
  3808. struct IRunner {
  3809. virtual ~IRunner();
  3810. virtual bool aborting() const = 0;
  3811. };
  3812. }
  3813. // end catch_interfaces_runner.h
  3814. #ifdef __OBJC__
  3815. // start catch_objc.hpp
  3816. #import <objc/runtime.h>
  3817. #include <string>
  3818. // NB. Any general catch headers included here must be included
  3819. // in catch.hpp first to make sure they are included by the single
  3820. // header for non obj-usage
  3821. ///////////////////////////////////////////////////////////////////////////////
  3822. // This protocol is really only here for (self) documenting purposes, since
  3823. // all its methods are optional.
  3824. @protocol OcFixture
  3825. @optional
  3826. -(void) setUp;
  3827. -(void) tearDown;
  3828. @end
  3829. namespace Catch {
  3830. class OcMethod : public ITestInvoker {
  3831. public:
  3832. OcMethod( Class cls, SEL sel ) : m_cls( cls ), m_sel( sel ) {}
  3833. virtual void invoke() const {
  3834. id obj = [[m_cls alloc] init];
  3835. performOptionalSelector( obj, @selector(setUp) );
  3836. performOptionalSelector( obj, m_sel );
  3837. performOptionalSelector( obj, @selector(tearDown) );
  3838. arcSafeRelease( obj );
  3839. }
  3840. private:
  3841. virtual ~OcMethod() {}
  3842. Class m_cls;
  3843. SEL m_sel;
  3844. };
  3845. namespace Detail{
  3846. inline std::string getAnnotation( Class cls,
  3847. std::string const& annotationName,
  3848. std::string const& testCaseName ) {
  3849. NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()];
  3850. SEL sel = NSSelectorFromString( selStr );
  3851. arcSafeRelease( selStr );
  3852. id value = performOptionalSelector( cls, sel );
  3853. if( value )
  3854. return [(NSString*)value UTF8String];
  3855. return "";
  3856. }
  3857. }
  3858. inline std::size_t registerTestMethods() {
  3859. std::size_t noTestMethods = 0;
  3860. int noClasses = objc_getClassList( nullptr, 0 );
  3861. Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc( sizeof(Class) * noClasses);
  3862. objc_getClassList( classes, noClasses );
  3863. for( int c = 0; c < noClasses; c++ ) {
  3864. Class cls = classes[c];
  3865. {
  3866. u_int count;
  3867. Method* methods = class_copyMethodList( cls, &count );
  3868. for( u_int m = 0; m < count ; m++ ) {
  3869. SEL selector = method_getName(methods[m]);
  3870. std::string methodName = sel_getName(selector);
  3871. if( startsWith( methodName, "Catch_TestCase_" ) ) {
  3872. std::string testCaseName = methodName.substr( 15 );
  3873. std::string name = Detail::getAnnotation( cls, "Name", testCaseName );
  3874. std::string desc = Detail::getAnnotation( cls, "Description", testCaseName );
  3875. const char* className = class_getName( cls );
  3876. getMutableRegistryHub().registerTest( makeTestCase( new OcMethod( cls, selector ), className, NameAndTags( name.c_str(), desc.c_str() ), SourceLineInfo("",0) ) );
  3877. noTestMethods++;
  3878. }
  3879. }
  3880. free(methods);
  3881. }
  3882. }
  3883. return noTestMethods;
  3884. }
  3885. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  3886. namespace Matchers {
  3887. namespace Impl {
  3888. namespace NSStringMatchers {
  3889. struct StringHolder : MatcherBase<NSString*>{
  3890. StringHolder( NSString* substr ) : m_substr( [substr copy] ){}
  3891. StringHolder( StringHolder const& other ) : m_substr( [other.m_substr copy] ){}
  3892. StringHolder() {
  3893. arcSafeRelease( m_substr );
  3894. }
  3895. bool match( NSString* const& str ) const override {
  3896. return false;
  3897. }
  3898. NSString* CATCH_ARC_STRONG m_substr;
  3899. };
  3900. struct Equals : StringHolder {
  3901. Equals( NSString* substr ) : StringHolder( substr ){}
  3902. bool match( NSString* const& str ) const override {
  3903. return (str != nil || m_substr == nil ) &&
  3904. [str isEqualToString:m_substr];
  3905. }
  3906. std::string describe() const override {
  3907. return "equals string: " + Catch::Detail::stringify( m_substr );
  3908. }
  3909. };
  3910. struct Contains : StringHolder {
  3911. Contains( NSString* substr ) : StringHolder( substr ){}
  3912. bool match( NSString* const& str ) const override {
  3913. return (str != nil || m_substr == nil ) &&
  3914. [str rangeOfString:m_substr].location != NSNotFound;
  3915. }
  3916. std::string describe() const override {
  3917. return "contains string: " + Catch::Detail::stringify( m_substr );
  3918. }
  3919. };
  3920. struct StartsWith : StringHolder {
  3921. StartsWith( NSString* substr ) : StringHolder( substr ){}
  3922. bool match( NSString* const& str ) const override {
  3923. return (str != nil || m_substr == nil ) &&
  3924. [str rangeOfString:m_substr].location == 0;
  3925. }
  3926. std::string describe() const override {
  3927. return "starts with: " + Catch::Detail::stringify( m_substr );
  3928. }
  3929. };
  3930. struct EndsWith : StringHolder {
  3931. EndsWith( NSString* substr ) : StringHolder( substr ){}
  3932. bool match( NSString* const& str ) const override {
  3933. return (str != nil || m_substr == nil ) &&
  3934. [str rangeOfString:m_substr].location == [str length] - [m_substr length];
  3935. }
  3936. std::string describe() const override {
  3937. return "ends with: " + Catch::Detail::stringify( m_substr );
  3938. }
  3939. };
  3940. } // namespace NSStringMatchers
  3941. } // namespace Impl
  3942. inline Impl::NSStringMatchers::Equals
  3943. Equals( NSString* substr ){ return Impl::NSStringMatchers::Equals( substr ); }
  3944. inline Impl::NSStringMatchers::Contains
  3945. Contains( NSString* substr ){ return Impl::NSStringMatchers::Contains( substr ); }
  3946. inline Impl::NSStringMatchers::StartsWith
  3947. StartsWith( NSString* substr ){ return Impl::NSStringMatchers::StartsWith( substr ); }
  3948. inline Impl::NSStringMatchers::EndsWith
  3949. EndsWith( NSString* substr ){ return Impl::NSStringMatchers::EndsWith( substr ); }
  3950. } // namespace Matchers
  3951. using namespace Matchers;
  3952. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  3953. } // namespace Catch
  3954. ///////////////////////////////////////////////////////////////////////////////
  3955. #define OC_MAKE_UNIQUE_NAME( root, uniqueSuffix ) root##uniqueSuffix
  3956. #define OC_TEST_CASE2( name, desc, uniqueSuffix ) \
  3957. +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Name_test_, uniqueSuffix ) \
  3958. { \
  3959. return @ name; \
  3960. } \
  3961. +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Description_test_, uniqueSuffix ) \
  3962. { \
  3963. return @ desc; \
  3964. } \
  3965. -(void) OC_MAKE_UNIQUE_NAME( Catch_TestCase_test_, uniqueSuffix )
  3966. #define OC_TEST_CASE( name, desc ) OC_TEST_CASE2( name, desc, __LINE__ )
  3967. // end catch_objc.hpp
  3968. #endif
  3969. #ifdef CATCH_CONFIG_EXTERNAL_INTERFACES
  3970. // start catch_external_interfaces.h
  3971. // start catch_reporter_bases.hpp
  3972. // start catch_interfaces_reporter.h
  3973. // start catch_config.hpp
  3974. // start catch_test_spec_parser.h
  3975. #ifdef __clang__
  3976. #pragma clang diagnostic push
  3977. #pragma clang diagnostic ignored "-Wpadded"
  3978. #endif
  3979. // start catch_test_spec.h
  3980. #ifdef __clang__
  3981. #pragma clang diagnostic push
  3982. #pragma clang diagnostic ignored "-Wpadded"
  3983. #endif
  3984. // start catch_wildcard_pattern.h
  3985. namespace Catch
  3986. {
  3987. class WildcardPattern {
  3988. enum WildcardPosition {
  3989. NoWildcard = 0,
  3990. WildcardAtStart = 1,
  3991. WildcardAtEnd = 2,
  3992. WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd
  3993. };
  3994. public:
  3995. WildcardPattern( std::string const& pattern, CaseSensitive::Choice caseSensitivity );
  3996. virtual ~WildcardPattern() = default;
  3997. virtual bool matches( std::string const& str ) const;
  3998. private:
  3999. std::string adjustCase( std::string const& str ) const;
  4000. CaseSensitive::Choice m_caseSensitivity;
  4001. WildcardPosition m_wildcard = NoWildcard;
  4002. std::string m_pattern;
  4003. };
  4004. }
  4005. // end catch_wildcard_pattern.h
  4006. #include <string>
  4007. #include <vector>
  4008. #include <memory>
  4009. namespace Catch {
  4010. class TestSpec {
  4011. struct Pattern {
  4012. virtual ~Pattern();
  4013. virtual bool matches( TestCaseInfo const& testCase ) const = 0;
  4014. };
  4015. using PatternPtr = std::shared_ptr<Pattern>;
  4016. class NamePattern : public Pattern {
  4017. public:
  4018. NamePattern( std::string const& name );
  4019. virtual ~NamePattern();
  4020. bool matches( TestCaseInfo const& testCase ) const override;
  4021. private:
  4022. WildcardPattern m_wildcardPattern;
  4023. };
  4024. class TagPattern : public Pattern {
  4025. public:
  4026. TagPattern( std::string const& tag );
  4027. virtual ~TagPattern();
  4028. bool matches( TestCaseInfo const& testCase ) const override;
  4029. private:
  4030. std::string m_tag;
  4031. };
  4032. class ExcludedPattern : public Pattern {
  4033. public:
  4034. ExcludedPattern( PatternPtr const& underlyingPattern );
  4035. virtual ~ExcludedPattern();
  4036. bool matches( TestCaseInfo const& testCase ) const override;
  4037. private:
  4038. PatternPtr m_underlyingPattern;
  4039. };
  4040. struct Filter {
  4041. std::vector<PatternPtr> m_patterns;
  4042. bool matches( TestCaseInfo const& testCase ) const;
  4043. };
  4044. public:
  4045. bool hasFilters() const;
  4046. bool matches( TestCaseInfo const& testCase ) const;
  4047. private:
  4048. std::vector<Filter> m_filters;
  4049. friend class TestSpecParser;
  4050. };
  4051. }
  4052. #ifdef __clang__
  4053. #pragma clang diagnostic pop
  4054. #endif
  4055. // end catch_test_spec.h
  4056. // start catch_interfaces_tag_alias_registry.h
  4057. #include <string>
  4058. namespace Catch {
  4059. struct TagAlias;
  4060. struct ITagAliasRegistry {
  4061. virtual ~ITagAliasRegistry();
  4062. // Nullptr if not present
  4063. virtual TagAlias const* find( std::string const& alias ) const = 0;
  4064. virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const = 0;
  4065. static ITagAliasRegistry const& get();
  4066. };
  4067. } // end namespace Catch
  4068. // end catch_interfaces_tag_alias_registry.h
  4069. namespace Catch {
  4070. class TestSpecParser {
  4071. enum Mode{ None, Name, QuotedName, Tag, EscapedName };
  4072. Mode m_mode = None;
  4073. bool m_exclusion = false;
  4074. std::size_t m_start = std::string::npos, m_pos = 0;
  4075. std::string m_arg;
  4076. std::vector<std::size_t> m_escapeChars;
  4077. TestSpec::Filter m_currentFilter;
  4078. TestSpec m_testSpec;
  4079. ITagAliasRegistry const* m_tagAliases = nullptr;
  4080. public:
  4081. TestSpecParser( ITagAliasRegistry const& tagAliases );
  4082. TestSpecParser& parse( std::string const& arg );
  4083. TestSpec testSpec();
  4084. private:
  4085. void visitChar( char c );
  4086. void startNewMode( Mode mode, std::size_t start );
  4087. void escape();
  4088. std::string subString() const;
  4089. template<typename T>
  4090. void addPattern() {
  4091. std::string token = subString();
  4092. for( std::size_t i = 0; i < m_escapeChars.size(); ++i )
  4093. token = token.substr( 0, m_escapeChars[i]-m_start-i ) + token.substr( m_escapeChars[i]-m_start-i+1 );
  4094. m_escapeChars.clear();
  4095. if( startsWith( token, "exclude:" ) ) {
  4096. m_exclusion = true;
  4097. token = token.substr( 8 );
  4098. }
  4099. if( !token.empty() ) {
  4100. TestSpec::PatternPtr pattern = std::make_shared<T>( token );
  4101. if( m_exclusion )
  4102. pattern = std::make_shared<TestSpec::ExcludedPattern>( pattern );
  4103. m_currentFilter.m_patterns.push_back( pattern );
  4104. }
  4105. m_exclusion = false;
  4106. m_mode = None;
  4107. }
  4108. void addFilter();
  4109. };
  4110. TestSpec parseTestSpec( std::string const& arg );
  4111. } // namespace Catch
  4112. #ifdef __clang__
  4113. #pragma clang diagnostic pop
  4114. #endif
  4115. // end catch_test_spec_parser.h
  4116. // Libstdc++ doesn't like incomplete classes for unique_ptr
  4117. #include <memory>
  4118. #include <vector>
  4119. #include <string>
  4120. #ifndef CATCH_CONFIG_CONSOLE_WIDTH
  4121. #define CATCH_CONFIG_CONSOLE_WIDTH 80
  4122. #endif
  4123. namespace Catch {
  4124. struct IStream;
  4125. struct ConfigData {
  4126. bool listTests = false;
  4127. bool listTags = false;
  4128. bool listReporters = false;
  4129. bool listTestNamesOnly = false;
  4130. bool showSuccessfulTests = false;
  4131. bool shouldDebugBreak = false;
  4132. bool noThrow = false;
  4133. bool showHelp = false;
  4134. bool showInvisibles = false;
  4135. bool filenamesAsTags = false;
  4136. bool libIdentify = false;
  4137. int abortAfter = -1;
  4138. unsigned int rngSeed = 0;
  4139. bool benchmarkNoAnalysis = false;
  4140. unsigned int benchmarkSamples = 100;
  4141. double benchmarkConfidenceInterval = 0.95;
  4142. unsigned int benchmarkResamples = 100000;
  4143. Verbosity verbosity = Verbosity::Normal;
  4144. WarnAbout::What warnings = WarnAbout::Nothing;
  4145. ShowDurations::OrNot showDurations = ShowDurations::DefaultForReporter;
  4146. RunTests::InWhatOrder runOrder = RunTests::InDeclarationOrder;
  4147. UseColour::YesOrNo useColour = UseColour::Auto;
  4148. WaitForKeypress::When waitForKeypress = WaitForKeypress::Never;
  4149. std::string outputFilename;
  4150. std::string name;
  4151. std::string processName;
  4152. #ifndef CATCH_CONFIG_DEFAULT_REPORTER
  4153. #define CATCH_CONFIG_DEFAULT_REPORTER "console"
  4154. #endif
  4155. std::string reporterName = CATCH_CONFIG_DEFAULT_REPORTER;
  4156. #undef CATCH_CONFIG_DEFAULT_REPORTER
  4157. std::vector<std::string> testsOrTags;
  4158. std::vector<std::string> sectionsToRun;
  4159. };
  4160. class Config : public IConfig {
  4161. public:
  4162. Config() = default;
  4163. Config( ConfigData const& data );
  4164. virtual ~Config() = default;
  4165. std::string const& getFilename() const;
  4166. bool listTests() const;
  4167. bool listTestNamesOnly() const;
  4168. bool listTags() const;
  4169. bool listReporters() const;
  4170. std::string getProcessName() const;
  4171. std::string const& getReporterName() const;
  4172. std::vector<std::string> const& getTestsOrTags() const override;
  4173. std::vector<std::string> const& getSectionsToRun() const override;
  4174. TestSpec const& testSpec() const override;
  4175. bool hasTestFilters() const override;
  4176. bool showHelp() const;
  4177. // IConfig interface
  4178. bool allowThrows() const override;
  4179. std::ostream& stream() const override;
  4180. std::string name() const override;
  4181. bool includeSuccessfulResults() const override;
  4182. bool warnAboutMissingAssertions() const override;
  4183. bool warnAboutNoTests() const override;
  4184. ShowDurations::OrNot showDurations() const override;
  4185. RunTests::InWhatOrder runOrder() const override;
  4186. unsigned int rngSeed() const override;
  4187. UseColour::YesOrNo useColour() const override;
  4188. bool shouldDebugBreak() const override;
  4189. int abortAfter() const override;
  4190. bool showInvisibles() const override;
  4191. Verbosity verbosity() const override;
  4192. bool benchmarkNoAnalysis() const override;
  4193. int benchmarkSamples() const override;
  4194. double benchmarkConfidenceInterval() const override;
  4195. unsigned int benchmarkResamples() const override;
  4196. private:
  4197. IStream const* openStream();
  4198. ConfigData m_data;
  4199. std::unique_ptr<IStream const> m_stream;
  4200. TestSpec m_testSpec;
  4201. bool m_hasTestFilters = false;
  4202. };
  4203. } // end namespace Catch
  4204. // end catch_config.hpp
  4205. // start catch_assertionresult.h
  4206. #include <string>
  4207. namespace Catch {
  4208. struct AssertionResultData
  4209. {
  4210. AssertionResultData() = delete;
  4211. AssertionResultData( ResultWas::OfType _resultType, LazyExpression const& _lazyExpression );
  4212. std::string message;
  4213. mutable std::string reconstructedExpression;
  4214. LazyExpression lazyExpression;
  4215. ResultWas::OfType resultType;
  4216. std::string reconstructExpression() const;
  4217. };
  4218. class AssertionResult {
  4219. public:
  4220. AssertionResult() = delete;
  4221. AssertionResult( AssertionInfo const& info, AssertionResultData const& data );
  4222. bool isOk() const;
  4223. bool succeeded() const;
  4224. ResultWas::OfType getResultType() const;
  4225. bool hasExpression() const;
  4226. bool hasMessage() const;
  4227. std::string getExpression() const;
  4228. std::string getExpressionInMacro() const;
  4229. bool hasExpandedExpression() const;
  4230. std::string getExpandedExpression() const;
  4231. std::string getMessage() const;
  4232. SourceLineInfo getSourceInfo() const;
  4233. StringRef getTestMacroName() const;
  4234. //protected:
  4235. AssertionInfo m_info;
  4236. AssertionResultData m_resultData;
  4237. };
  4238. } // end namespace Catch
  4239. // end catch_assertionresult.h
  4240. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  4241. // start catch_estimate.hpp
  4242. // Statistics estimates
  4243. namespace Catch {
  4244. namespace Benchmark {
  4245. template <typename Duration>
  4246. struct Estimate {
  4247. Duration point;
  4248. Duration lower_bound;
  4249. Duration upper_bound;
  4250. double confidence_interval;
  4251. template <typename Duration2>
  4252. operator Estimate<Duration2>() const {
  4253. return { point, lower_bound, upper_bound, confidence_interval };
  4254. }
  4255. };
  4256. } // namespace Benchmark
  4257. } // namespace Catch
  4258. // end catch_estimate.hpp
  4259. // start catch_outlier_classification.hpp
  4260. // Outlier information
  4261. namespace Catch {
  4262. namespace Benchmark {
  4263. struct OutlierClassification {
  4264. int samples_seen = 0;
  4265. int low_severe = 0; // more than 3 times IQR below Q1
  4266. int low_mild = 0; // 1.5 to 3 times IQR below Q1
  4267. int high_mild = 0; // 1.5 to 3 times IQR above Q3
  4268. int high_severe = 0; // more than 3 times IQR above Q3
  4269. int total() const {
  4270. return low_severe + low_mild + high_mild + high_severe;
  4271. }
  4272. };
  4273. } // namespace Benchmark
  4274. } // namespace Catch
  4275. // end catch_outlier_classification.hpp
  4276. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  4277. #include <string>
  4278. #include <iosfwd>
  4279. #include <map>
  4280. #include <set>
  4281. #include <memory>
  4282. #include <algorithm>
  4283. namespace Catch {
  4284. struct ReporterConfig {
  4285. explicit ReporterConfig( IConfigPtr const& _fullConfig );
  4286. ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream );
  4287. std::ostream& stream() const;
  4288. IConfigPtr fullConfig() const;
  4289. private:
  4290. std::ostream* m_stream;
  4291. IConfigPtr m_fullConfig;
  4292. };
  4293. struct ReporterPreferences {
  4294. bool shouldRedirectStdOut = false;
  4295. bool shouldReportAllAssertions = false;
  4296. };
  4297. template<typename T>
  4298. struct LazyStat : Option<T> {
  4299. LazyStat& operator=( T const& _value ) {
  4300. Option<T>::operator=( _value );
  4301. used = false;
  4302. return *this;
  4303. }
  4304. void reset() {
  4305. Option<T>::reset();
  4306. used = false;
  4307. }
  4308. bool used = false;
  4309. };
  4310. struct TestRunInfo {
  4311. TestRunInfo( std::string const& _name );
  4312. std::string name;
  4313. };
  4314. struct GroupInfo {
  4315. GroupInfo( std::string const& _name,
  4316. std::size_t _groupIndex,
  4317. std::size_t _groupsCount );
  4318. std::string name;
  4319. std::size_t groupIndex;
  4320. std::size_t groupsCounts;
  4321. };
  4322. struct AssertionStats {
  4323. AssertionStats( AssertionResult const& _assertionResult,
  4324. std::vector<MessageInfo> const& _infoMessages,
  4325. Totals const& _totals );
  4326. AssertionStats( AssertionStats const& ) = default;
  4327. AssertionStats( AssertionStats && ) = default;
  4328. AssertionStats& operator = ( AssertionStats const& ) = delete;
  4329. AssertionStats& operator = ( AssertionStats && ) = delete;
  4330. virtual ~AssertionStats();
  4331. AssertionResult assertionResult;
  4332. std::vector<MessageInfo> infoMessages;
  4333. Totals totals;
  4334. };
  4335. struct SectionStats {
  4336. SectionStats( SectionInfo const& _sectionInfo,
  4337. Counts const& _assertions,
  4338. double _durationInSeconds,
  4339. bool _missingAssertions );
  4340. SectionStats( SectionStats const& ) = default;
  4341. SectionStats( SectionStats && ) = default;
  4342. SectionStats& operator = ( SectionStats const& ) = default;
  4343. SectionStats& operator = ( SectionStats && ) = default;
  4344. virtual ~SectionStats();
  4345. SectionInfo sectionInfo;
  4346. Counts assertions;
  4347. double durationInSeconds;
  4348. bool missingAssertions;
  4349. };
  4350. struct TestCaseStats {
  4351. TestCaseStats( TestCaseInfo const& _testInfo,
  4352. Totals const& _totals,
  4353. std::string const& _stdOut,
  4354. std::string const& _stdErr,
  4355. bool _aborting );
  4356. TestCaseStats( TestCaseStats const& ) = default;
  4357. TestCaseStats( TestCaseStats && ) = default;
  4358. TestCaseStats& operator = ( TestCaseStats const& ) = default;
  4359. TestCaseStats& operator = ( TestCaseStats && ) = default;
  4360. virtual ~TestCaseStats();
  4361. TestCaseInfo testInfo;
  4362. Totals totals;
  4363. std::string stdOut;
  4364. std::string stdErr;
  4365. bool aborting;
  4366. };
  4367. struct TestGroupStats {
  4368. TestGroupStats( GroupInfo const& _groupInfo,
  4369. Totals const& _totals,
  4370. bool _aborting );
  4371. TestGroupStats( GroupInfo const& _groupInfo );
  4372. TestGroupStats( TestGroupStats const& ) = default;
  4373. TestGroupStats( TestGroupStats && ) = default;
  4374. TestGroupStats& operator = ( TestGroupStats const& ) = default;
  4375. TestGroupStats& operator = ( TestGroupStats && ) = default;
  4376. virtual ~TestGroupStats();
  4377. GroupInfo groupInfo;
  4378. Totals totals;
  4379. bool aborting;
  4380. };
  4381. struct TestRunStats {
  4382. TestRunStats( TestRunInfo const& _runInfo,
  4383. Totals const& _totals,
  4384. bool _aborting );
  4385. TestRunStats( TestRunStats const& ) = default;
  4386. TestRunStats( TestRunStats && ) = default;
  4387. TestRunStats& operator = ( TestRunStats const& ) = default;
  4388. TestRunStats& operator = ( TestRunStats && ) = default;
  4389. virtual ~TestRunStats();
  4390. TestRunInfo runInfo;
  4391. Totals totals;
  4392. bool aborting;
  4393. };
  4394. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  4395. struct BenchmarkInfo {
  4396. std::string name;
  4397. double estimatedDuration;
  4398. int iterations;
  4399. int samples;
  4400. unsigned int resamples;
  4401. double clockResolution;
  4402. double clockCost;
  4403. };
  4404. template <class Duration>
  4405. struct BenchmarkStats {
  4406. BenchmarkInfo info;
  4407. std::vector<Duration> samples;
  4408. Benchmark::Estimate<Duration> mean;
  4409. Benchmark::Estimate<Duration> standardDeviation;
  4410. Benchmark::OutlierClassification outliers;
  4411. double outlierVariance;
  4412. template <typename Duration2>
  4413. operator BenchmarkStats<Duration2>() const {
  4414. std::vector<Duration2> samples2;
  4415. samples2.reserve(samples.size());
  4416. std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration d) { return Duration2(d); });
  4417. return {
  4418. info,
  4419. std::move(samples2),
  4420. mean,
  4421. standardDeviation,
  4422. outliers,
  4423. outlierVariance,
  4424. };
  4425. }
  4426. };
  4427. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  4428. struct IStreamingReporter {
  4429. virtual ~IStreamingReporter() = default;
  4430. // Implementing class must also provide the following static methods:
  4431. // static std::string getDescription();
  4432. // static std::set<Verbosity> getSupportedVerbosities()
  4433. virtual ReporterPreferences getPreferences() const = 0;
  4434. virtual void noMatchingTestCases( std::string const& spec ) = 0;
  4435. virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0;
  4436. virtual void testGroupStarting( GroupInfo const& groupInfo ) = 0;
  4437. virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0;
  4438. virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0;
  4439. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  4440. virtual void benchmarkPreparing( std::string const& ) {}
  4441. virtual void benchmarkStarting( BenchmarkInfo const& ) {}
  4442. virtual void benchmarkEnded( BenchmarkStats<> const& ) {}
  4443. virtual void benchmarkFailed( std::string const& ) {}
  4444. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  4445. virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0;
  4446. // The return value indicates if the messages buffer should be cleared:
  4447. virtual bool assertionEnded( AssertionStats const& assertionStats ) = 0;
  4448. virtual void sectionEnded( SectionStats const& sectionStats ) = 0;
  4449. virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0;
  4450. virtual void testGroupEnded( TestGroupStats const& testGroupStats ) = 0;
  4451. virtual void testRunEnded( TestRunStats const& testRunStats ) = 0;
  4452. virtual void skipTest( TestCaseInfo const& testInfo ) = 0;
  4453. // Default empty implementation provided
  4454. virtual void fatalErrorEncountered( StringRef name );
  4455. virtual bool isMulti() const;
  4456. };
  4457. using IStreamingReporterPtr = std::unique_ptr<IStreamingReporter>;
  4458. struct IReporterFactory {
  4459. virtual ~IReporterFactory();
  4460. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const = 0;
  4461. virtual std::string getDescription() const = 0;
  4462. };
  4463. using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
  4464. struct IReporterRegistry {
  4465. using FactoryMap = std::map<std::string, IReporterFactoryPtr>;
  4466. using Listeners = std::vector<IReporterFactoryPtr>;
  4467. virtual ~IReporterRegistry();
  4468. virtual IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const = 0;
  4469. virtual FactoryMap const& getFactories() const = 0;
  4470. virtual Listeners const& getListeners() const = 0;
  4471. };
  4472. } // end namespace Catch
  4473. // end catch_interfaces_reporter.h
  4474. #include <algorithm>
  4475. #include <cstring>
  4476. #include <cfloat>
  4477. #include <cstdio>
  4478. #include <cassert>
  4479. #include <memory>
  4480. #include <ostream>
  4481. namespace Catch {
  4482. void prepareExpandedExpression(AssertionResult& result);
  4483. // Returns double formatted as %.3f (format expected on output)
  4484. std::string getFormattedDuration( double duration );
  4485. std::string serializeFilters( std::vector<std::string> const& container );
  4486. template<typename DerivedT>
  4487. struct StreamingReporterBase : IStreamingReporter {
  4488. StreamingReporterBase( ReporterConfig const& _config )
  4489. : m_config( _config.fullConfig() ),
  4490. stream( _config.stream() )
  4491. {
  4492. m_reporterPrefs.shouldRedirectStdOut = false;
  4493. if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
  4494. CATCH_ERROR( "Verbosity level not supported by this reporter" );
  4495. }
  4496. ReporterPreferences getPreferences() const override {
  4497. return m_reporterPrefs;
  4498. }
  4499. static std::set<Verbosity> getSupportedVerbosities() {
  4500. return { Verbosity::Normal };
  4501. }
  4502. ~StreamingReporterBase() override = default;
  4503. void noMatchingTestCases(std::string const&) override {}
  4504. void testRunStarting(TestRunInfo const& _testRunInfo) override {
  4505. currentTestRunInfo = _testRunInfo;
  4506. }
  4507. void testGroupStarting(GroupInfo const& _groupInfo) override {
  4508. currentGroupInfo = _groupInfo;
  4509. }
  4510. void testCaseStarting(TestCaseInfo const& _testInfo) override {
  4511. currentTestCaseInfo = _testInfo;
  4512. }
  4513. void sectionStarting(SectionInfo const& _sectionInfo) override {
  4514. m_sectionStack.push_back(_sectionInfo);
  4515. }
  4516. void sectionEnded(SectionStats const& /* _sectionStats */) override {
  4517. m_sectionStack.pop_back();
  4518. }
  4519. void testCaseEnded(TestCaseStats const& /* _testCaseStats */) override {
  4520. currentTestCaseInfo.reset();
  4521. }
  4522. void testGroupEnded(TestGroupStats const& /* _testGroupStats */) override {
  4523. currentGroupInfo.reset();
  4524. }
  4525. void testRunEnded(TestRunStats const& /* _testRunStats */) override {
  4526. currentTestCaseInfo.reset();
  4527. currentGroupInfo.reset();
  4528. currentTestRunInfo.reset();
  4529. }
  4530. void skipTest(TestCaseInfo const&) override {
  4531. // Don't do anything with this by default.
  4532. // It can optionally be overridden in the derived class.
  4533. }
  4534. IConfigPtr m_config;
  4535. std::ostream& stream;
  4536. LazyStat<TestRunInfo> currentTestRunInfo;
  4537. LazyStat<GroupInfo> currentGroupInfo;
  4538. LazyStat<TestCaseInfo> currentTestCaseInfo;
  4539. std::vector<SectionInfo> m_sectionStack;
  4540. ReporterPreferences m_reporterPrefs;
  4541. };
  4542. template<typename DerivedT>
  4543. struct CumulativeReporterBase : IStreamingReporter {
  4544. template<typename T, typename ChildNodeT>
  4545. struct Node {
  4546. explicit Node( T const& _value ) : value( _value ) {}
  4547. virtual ~Node() {}
  4548. using ChildNodes = std::vector<std::shared_ptr<ChildNodeT>>;
  4549. T value;
  4550. ChildNodes children;
  4551. };
  4552. struct SectionNode {
  4553. explicit SectionNode(SectionStats const& _stats) : stats(_stats) {}
  4554. virtual ~SectionNode() = default;
  4555. bool operator == (SectionNode const& other) const {
  4556. return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;
  4557. }
  4558. bool operator == (std::shared_ptr<SectionNode> const& other) const {
  4559. return operator==(*other);
  4560. }
  4561. SectionStats stats;
  4562. using ChildSections = std::vector<std::shared_ptr<SectionNode>>;
  4563. using Assertions = std::vector<AssertionStats>;
  4564. ChildSections childSections;
  4565. Assertions assertions;
  4566. std::string stdOut;
  4567. std::string stdErr;
  4568. };
  4569. struct BySectionInfo {
  4570. BySectionInfo( SectionInfo const& other ) : m_other( other ) {}
  4571. BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {}
  4572. bool operator() (std::shared_ptr<SectionNode> const& node) const {
  4573. return ((node->stats.sectionInfo.name == m_other.name) &&
  4574. (node->stats.sectionInfo.lineInfo == m_other.lineInfo));
  4575. }
  4576. void operator=(BySectionInfo const&) = delete;
  4577. private:
  4578. SectionInfo const& m_other;
  4579. };
  4580. using TestCaseNode = Node<TestCaseStats, SectionNode>;
  4581. using TestGroupNode = Node<TestGroupStats, TestCaseNode>;
  4582. using TestRunNode = Node<TestRunStats, TestGroupNode>;
  4583. CumulativeReporterBase( ReporterConfig const& _config )
  4584. : m_config( _config.fullConfig() ),
  4585. stream( _config.stream() )
  4586. {
  4587. m_reporterPrefs.shouldRedirectStdOut = false;
  4588. if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
  4589. CATCH_ERROR( "Verbosity level not supported by this reporter" );
  4590. }
  4591. ~CumulativeReporterBase() override = default;
  4592. ReporterPreferences getPreferences() const override {
  4593. return m_reporterPrefs;
  4594. }
  4595. static std::set<Verbosity> getSupportedVerbosities() {
  4596. return { Verbosity::Normal };
  4597. }
  4598. void testRunStarting( TestRunInfo const& ) override {}
  4599. void testGroupStarting( GroupInfo const& ) override {}
  4600. void testCaseStarting( TestCaseInfo const& ) override {}
  4601. void sectionStarting( SectionInfo const& sectionInfo ) override {
  4602. SectionStats incompleteStats( sectionInfo, Counts(), 0, false );
  4603. std::shared_ptr<SectionNode> node;
  4604. if( m_sectionStack.empty() ) {
  4605. if( !m_rootSection )
  4606. m_rootSection = std::make_shared<SectionNode>( incompleteStats );
  4607. node = m_rootSection;
  4608. }
  4609. else {
  4610. SectionNode& parentNode = *m_sectionStack.back();
  4611. auto it =
  4612. std::find_if( parentNode.childSections.begin(),
  4613. parentNode.childSections.end(),
  4614. BySectionInfo( sectionInfo ) );
  4615. if( it == parentNode.childSections.end() ) {
  4616. node = std::make_shared<SectionNode>( incompleteStats );
  4617. parentNode.childSections.push_back( node );
  4618. }
  4619. else
  4620. node = *it;
  4621. }
  4622. m_sectionStack.push_back( node );
  4623. m_deepestSection = std::move(node);
  4624. }
  4625. void assertionStarting(AssertionInfo const&) override {}
  4626. bool assertionEnded(AssertionStats const& assertionStats) override {
  4627. assert(!m_sectionStack.empty());
  4628. // AssertionResult holds a pointer to a temporary DecomposedExpression,
  4629. // which getExpandedExpression() calls to build the expression string.
  4630. // Our section stack copy of the assertionResult will likely outlive the
  4631. // temporary, so it must be expanded or discarded now to avoid calling
  4632. // a destroyed object later.
  4633. prepareExpandedExpression(const_cast<AssertionResult&>( assertionStats.assertionResult ) );
  4634. SectionNode& sectionNode = *m_sectionStack.back();
  4635. sectionNode.assertions.push_back(assertionStats);
  4636. return true;
  4637. }
  4638. void sectionEnded(SectionStats const& sectionStats) override {
  4639. assert(!m_sectionStack.empty());
  4640. SectionNode& node = *m_sectionStack.back();
  4641. node.stats = sectionStats;
  4642. m_sectionStack.pop_back();
  4643. }
  4644. void testCaseEnded(TestCaseStats const& testCaseStats) override {
  4645. auto node = std::make_shared<TestCaseNode>(testCaseStats);
  4646. assert(m_sectionStack.size() == 0);
  4647. node->children.push_back(m_rootSection);
  4648. m_testCases.push_back(node);
  4649. m_rootSection.reset();
  4650. assert(m_deepestSection);
  4651. m_deepestSection->stdOut = testCaseStats.stdOut;
  4652. m_deepestSection->stdErr = testCaseStats.stdErr;
  4653. }
  4654. void testGroupEnded(TestGroupStats const& testGroupStats) override {
  4655. auto node = std::make_shared<TestGroupNode>(testGroupStats);
  4656. node->children.swap(m_testCases);
  4657. m_testGroups.push_back(node);
  4658. }
  4659. void testRunEnded(TestRunStats const& testRunStats) override {
  4660. auto node = std::make_shared<TestRunNode>(testRunStats);
  4661. node->children.swap(m_testGroups);
  4662. m_testRuns.push_back(node);
  4663. testRunEndedCumulative();
  4664. }
  4665. virtual void testRunEndedCumulative() = 0;
  4666. void skipTest(TestCaseInfo const&) override {}
  4667. IConfigPtr m_config;
  4668. std::ostream& stream;
  4669. std::vector<AssertionStats> m_assertions;
  4670. std::vector<std::vector<std::shared_ptr<SectionNode>>> m_sections;
  4671. std::vector<std::shared_ptr<TestCaseNode>> m_testCases;
  4672. std::vector<std::shared_ptr<TestGroupNode>> m_testGroups;
  4673. std::vector<std::shared_ptr<TestRunNode>> m_testRuns;
  4674. std::shared_ptr<SectionNode> m_rootSection;
  4675. std::shared_ptr<SectionNode> m_deepestSection;
  4676. std::vector<std::shared_ptr<SectionNode>> m_sectionStack;
  4677. ReporterPreferences m_reporterPrefs;
  4678. };
  4679. template<char C>
  4680. char const* getLineOfChars() {
  4681. static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
  4682. if( !*line ) {
  4683. std::memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 );
  4684. line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0;
  4685. }
  4686. return line;
  4687. }
  4688. struct TestEventListenerBase : StreamingReporterBase<TestEventListenerBase> {
  4689. TestEventListenerBase( ReporterConfig const& _config );
  4690. static std::set<Verbosity> getSupportedVerbosities();
  4691. void assertionStarting(AssertionInfo const&) override;
  4692. bool assertionEnded(AssertionStats const&) override;
  4693. };
  4694. } // end namespace Catch
  4695. // end catch_reporter_bases.hpp
  4696. // start catch_console_colour.h
  4697. namespace Catch {
  4698. struct Colour {
  4699. enum Code {
  4700. None = 0,
  4701. White,
  4702. Red,
  4703. Green,
  4704. Blue,
  4705. Cyan,
  4706. Yellow,
  4707. Grey,
  4708. Bright = 0x10,
  4709. BrightRed = Bright | Red,
  4710. BrightGreen = Bright | Green,
  4711. LightGrey = Bright | Grey,
  4712. BrightWhite = Bright | White,
  4713. BrightYellow = Bright | Yellow,
  4714. // By intention
  4715. FileName = LightGrey,
  4716. Warning = BrightYellow,
  4717. ResultError = BrightRed,
  4718. ResultSuccess = BrightGreen,
  4719. ResultExpectedFailure = Warning,
  4720. Error = BrightRed,
  4721. Success = Green,
  4722. OriginalExpression = Cyan,
  4723. ReconstructedExpression = BrightYellow,
  4724. SecondaryText = LightGrey,
  4725. Headers = White
  4726. };
  4727. // Use constructed object for RAII guard
  4728. Colour( Code _colourCode );
  4729. Colour( Colour&& other ) noexcept;
  4730. Colour& operator=( Colour&& other ) noexcept;
  4731. ~Colour();
  4732. // Use static method for one-shot changes
  4733. static void use( Code _colourCode );
  4734. private:
  4735. bool m_moved = false;
  4736. };
  4737. std::ostream& operator << ( std::ostream& os, Colour const& );
  4738. } // end namespace Catch
  4739. // end catch_console_colour.h
  4740. // start catch_reporter_registrars.hpp
  4741. namespace Catch {
  4742. template<typename T>
  4743. class ReporterRegistrar {
  4744. class ReporterFactory : public IReporterFactory {
  4745. IStreamingReporterPtr create( ReporterConfig const& config ) const override {
  4746. return std::unique_ptr<T>( new T( config ) );
  4747. }
  4748. std::string getDescription() const override {
  4749. return T::getDescription();
  4750. }
  4751. };
  4752. public:
  4753. explicit ReporterRegistrar( std::string const& name ) {
  4754. getMutableRegistryHub().registerReporter( name, std::make_shared<ReporterFactory>() );
  4755. }
  4756. };
  4757. template<typename T>
  4758. class ListenerRegistrar {
  4759. class ListenerFactory : public IReporterFactory {
  4760. IStreamingReporterPtr create( ReporterConfig const& config ) const override {
  4761. return std::unique_ptr<T>( new T( config ) );
  4762. }
  4763. std::string getDescription() const override {
  4764. return std::string();
  4765. }
  4766. };
  4767. public:
  4768. ListenerRegistrar() {
  4769. getMutableRegistryHub().registerListener( std::make_shared<ListenerFactory>() );
  4770. }
  4771. };
  4772. }
  4773. #if !defined(CATCH_CONFIG_DISABLE)
  4774. #define CATCH_REGISTER_REPORTER( name, reporterType ) \
  4775. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  4776. namespace{ Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); } \
  4777. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  4778. #define CATCH_REGISTER_LISTENER( listenerType ) \
  4779. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  4780. namespace{ Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; } \
  4781. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  4782. #else // CATCH_CONFIG_DISABLE
  4783. #define CATCH_REGISTER_REPORTER(name, reporterType)
  4784. #define CATCH_REGISTER_LISTENER(listenerType)
  4785. #endif // CATCH_CONFIG_DISABLE
  4786. // end catch_reporter_registrars.hpp
  4787. // Allow users to base their work off existing reporters
  4788. // start catch_reporter_compact.h
  4789. namespace Catch {
  4790. struct CompactReporter : StreamingReporterBase<CompactReporter> {
  4791. using StreamingReporterBase::StreamingReporterBase;
  4792. ~CompactReporter() override;
  4793. static std::string getDescription();
  4794. ReporterPreferences getPreferences() const override;
  4795. void noMatchingTestCases(std::string const& spec) override;
  4796. void assertionStarting(AssertionInfo const&) override;
  4797. bool assertionEnded(AssertionStats const& _assertionStats) override;
  4798. void sectionEnded(SectionStats const& _sectionStats) override;
  4799. void testRunEnded(TestRunStats const& _testRunStats) override;
  4800. };
  4801. } // end namespace Catch
  4802. // end catch_reporter_compact.h
  4803. // start catch_reporter_console.h
  4804. #if defined(_MSC_VER)
  4805. #pragma warning(push)
  4806. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  4807. // Note that 4062 (not all labels are handled
  4808. // and default is missing) is enabled
  4809. #endif
  4810. namespace Catch {
  4811. // Fwd decls
  4812. struct SummaryColumn;
  4813. class TablePrinter;
  4814. struct ConsoleReporter : StreamingReporterBase<ConsoleReporter> {
  4815. std::unique_ptr<TablePrinter> m_tablePrinter;
  4816. ConsoleReporter(ReporterConfig const& config);
  4817. ~ConsoleReporter() override;
  4818. static std::string getDescription();
  4819. void noMatchingTestCases(std::string const& spec) override;
  4820. void assertionStarting(AssertionInfo const&) override;
  4821. bool assertionEnded(AssertionStats const& _assertionStats) override;
  4822. void sectionStarting(SectionInfo const& _sectionInfo) override;
  4823. void sectionEnded(SectionStats const& _sectionStats) override;
  4824. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  4825. void benchmarkPreparing(std::string const& name) override;
  4826. void benchmarkStarting(BenchmarkInfo const& info) override;
  4827. void benchmarkEnded(BenchmarkStats<> const& stats) override;
  4828. void benchmarkFailed(std::string const& error) override;
  4829. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  4830. void testCaseEnded(TestCaseStats const& _testCaseStats) override;
  4831. void testGroupEnded(TestGroupStats const& _testGroupStats) override;
  4832. void testRunEnded(TestRunStats const& _testRunStats) override;
  4833. void testRunStarting(TestRunInfo const& _testRunInfo) override;
  4834. private:
  4835. void lazyPrint();
  4836. void lazyPrintWithoutClosingBenchmarkTable();
  4837. void lazyPrintRunInfo();
  4838. void lazyPrintGroupInfo();
  4839. void printTestCaseAndSectionHeader();
  4840. void printClosedHeader(std::string const& _name);
  4841. void printOpenHeader(std::string const& _name);
  4842. // if string has a : in first line will set indent to follow it on
  4843. // subsequent lines
  4844. void printHeaderString(std::string const& _string, std::size_t indent = 0);
  4845. void printTotals(Totals const& totals);
  4846. void printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row);
  4847. void printTotalsDivider(Totals const& totals);
  4848. void printSummaryDivider();
  4849. void printTestFilters();
  4850. private:
  4851. bool m_headerPrinted = false;
  4852. };
  4853. } // end namespace Catch
  4854. #if defined(_MSC_VER)
  4855. #pragma warning(pop)
  4856. #endif
  4857. // end catch_reporter_console.h
  4858. // start catch_reporter_junit.h
  4859. // start catch_xmlwriter.h
  4860. #include <vector>
  4861. namespace Catch {
  4862. class XmlEncode {
  4863. public:
  4864. enum ForWhat { ForTextNodes, ForAttributes };
  4865. XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes );
  4866. void encodeTo( std::ostream& os ) const;
  4867. friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode );
  4868. private:
  4869. std::string m_str;
  4870. ForWhat m_forWhat;
  4871. };
  4872. class XmlWriter {
  4873. public:
  4874. class ScopedElement {
  4875. public:
  4876. ScopedElement( XmlWriter* writer );
  4877. ScopedElement( ScopedElement&& other ) noexcept;
  4878. ScopedElement& operator=( ScopedElement&& other ) noexcept;
  4879. ~ScopedElement();
  4880. ScopedElement& writeText( std::string const& text, bool indent = true );
  4881. template<typename T>
  4882. ScopedElement& writeAttribute( std::string const& name, T const& attribute ) {
  4883. m_writer->writeAttribute( name, attribute );
  4884. return *this;
  4885. }
  4886. private:
  4887. mutable XmlWriter* m_writer = nullptr;
  4888. };
  4889. XmlWriter( std::ostream& os = Catch::cout() );
  4890. ~XmlWriter();
  4891. XmlWriter( XmlWriter const& ) = delete;
  4892. XmlWriter& operator=( XmlWriter const& ) = delete;
  4893. XmlWriter& startElement( std::string const& name );
  4894. ScopedElement scopedElement( std::string const& name );
  4895. XmlWriter& endElement();
  4896. XmlWriter& writeAttribute( std::string const& name, std::string const& attribute );
  4897. XmlWriter& writeAttribute( std::string const& name, bool attribute );
  4898. template<typename T>
  4899. XmlWriter& writeAttribute( std::string const& name, T const& attribute ) {
  4900. ReusableStringStream rss;
  4901. rss << attribute;
  4902. return writeAttribute( name, rss.str() );
  4903. }
  4904. XmlWriter& writeText( std::string const& text, bool indent = true );
  4905. XmlWriter& writeComment( std::string const& text );
  4906. void writeStylesheetRef( std::string const& url );
  4907. XmlWriter& writeBlankLine();
  4908. void ensureTagClosed();
  4909. private:
  4910. void writeDeclaration();
  4911. void newlineIfNecessary();
  4912. bool m_tagIsOpen = false;
  4913. bool m_needsNewline = false;
  4914. std::vector<std::string> m_tags;
  4915. std::string m_indent;
  4916. std::ostream& m_os;
  4917. };
  4918. }
  4919. // end catch_xmlwriter.h
  4920. namespace Catch {
  4921. class JunitReporter : public CumulativeReporterBase<JunitReporter> {
  4922. public:
  4923. JunitReporter(ReporterConfig const& _config);
  4924. ~JunitReporter() override;
  4925. static std::string getDescription();
  4926. void noMatchingTestCases(std::string const& /*spec*/) override;
  4927. void testRunStarting(TestRunInfo const& runInfo) override;
  4928. void testGroupStarting(GroupInfo const& groupInfo) override;
  4929. void testCaseStarting(TestCaseInfo const& testCaseInfo) override;
  4930. bool assertionEnded(AssertionStats const& assertionStats) override;
  4931. void testCaseEnded(TestCaseStats const& testCaseStats) override;
  4932. void testGroupEnded(TestGroupStats const& testGroupStats) override;
  4933. void testRunEndedCumulative() override;
  4934. void writeGroup(TestGroupNode const& groupNode, double suiteTime);
  4935. void writeTestCase(TestCaseNode const& testCaseNode);
  4936. void writeSection(std::string const& className,
  4937. std::string const& rootName,
  4938. SectionNode const& sectionNode);
  4939. void writeAssertions(SectionNode const& sectionNode);
  4940. void writeAssertion(AssertionStats const& stats);
  4941. XmlWriter xml;
  4942. Timer suiteTimer;
  4943. std::string stdOutForSuite;
  4944. std::string stdErrForSuite;
  4945. unsigned int unexpectedExceptions = 0;
  4946. bool m_okToFail = false;
  4947. };
  4948. } // end namespace Catch
  4949. // end catch_reporter_junit.h
  4950. // start catch_reporter_xml.h
  4951. namespace Catch {
  4952. class XmlReporter : public StreamingReporterBase<XmlReporter> {
  4953. public:
  4954. XmlReporter(ReporterConfig const& _config);
  4955. ~XmlReporter() override;
  4956. static std::string getDescription();
  4957. virtual std::string getStylesheetRef() const;
  4958. void writeSourceInfo(SourceLineInfo const& sourceInfo);
  4959. public: // StreamingReporterBase
  4960. void noMatchingTestCases(std::string const& s) override;
  4961. void testRunStarting(TestRunInfo const& testInfo) override;
  4962. void testGroupStarting(GroupInfo const& groupInfo) override;
  4963. void testCaseStarting(TestCaseInfo const& testInfo) override;
  4964. void sectionStarting(SectionInfo const& sectionInfo) override;
  4965. void assertionStarting(AssertionInfo const&) override;
  4966. bool assertionEnded(AssertionStats const& assertionStats) override;
  4967. void sectionEnded(SectionStats const& sectionStats) override;
  4968. void testCaseEnded(TestCaseStats const& testCaseStats) override;
  4969. void testGroupEnded(TestGroupStats const& testGroupStats) override;
  4970. void testRunEnded(TestRunStats const& testRunStats) override;
  4971. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  4972. void benchmarkStarting(BenchmarkInfo const&) override;
  4973. void benchmarkEnded(BenchmarkStats<> const&) override;
  4974. void benchmarkFailed(std::string const&) override;
  4975. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  4976. private:
  4977. Timer m_testCaseTimer;
  4978. XmlWriter m_xml;
  4979. int m_sectionDepth = 0;
  4980. };
  4981. } // end namespace Catch
  4982. // end catch_reporter_xml.h
  4983. // end catch_external_interfaces.h
  4984. #endif
  4985. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  4986. // start catch_benchmark.hpp
  4987. // Benchmark
  4988. // start catch_chronometer.hpp
  4989. // User-facing chronometer
  4990. // start catch_clock.hpp
  4991. // Clocks
  4992. #include <chrono>
  4993. #include <ratio>
  4994. namespace Catch {
  4995. namespace Benchmark {
  4996. template <typename Clock>
  4997. using ClockDuration = typename Clock::duration;
  4998. template <typename Clock>
  4999. using FloatDuration = std::chrono::duration<double, typename Clock::period>;
  5000. template <typename Clock>
  5001. using TimePoint = typename Clock::time_point;
  5002. using default_clock = std::chrono::steady_clock;
  5003. template <typename Clock>
  5004. struct now {
  5005. TimePoint<Clock> operator()() const {
  5006. return Clock::now();
  5007. }
  5008. };
  5009. using fp_seconds = std::chrono::duration<double, std::ratio<1>>;
  5010. } // namespace Benchmark
  5011. } // namespace Catch
  5012. // end catch_clock.hpp
  5013. // start catch_optimizer.hpp
  5014. // Hinting the optimizer
  5015. #if defined(_MSC_VER)
  5016. # include <atomic> // atomic_thread_fence
  5017. #endif
  5018. namespace Catch {
  5019. namespace Benchmark {
  5020. #if defined(__GNUC__) || defined(__clang__)
  5021. template <typename T>
  5022. inline void keep_memory(T* p) {
  5023. asm volatile("" : : "g"(p) : "memory");
  5024. }
  5025. inline void keep_memory() {
  5026. asm volatile("" : : : "memory");
  5027. }
  5028. namespace Detail {
  5029. inline void optimizer_barrier() { keep_memory(); }
  5030. } // namespace Detail
  5031. #elif defined(_MSC_VER)
  5032. #pragma optimize("", off)
  5033. template <typename T>
  5034. inline void keep_memory(T* p) {
  5035. // thanks @milleniumbug
  5036. *reinterpret_cast<char volatile*>(p) = *reinterpret_cast<char const volatile*>(p);
  5037. }
  5038. // TODO equivalent keep_memory()
  5039. #pragma optimize("", on)
  5040. namespace Detail {
  5041. inline void optimizer_barrier() {
  5042. std::atomic_thread_fence(std::memory_order_seq_cst);
  5043. }
  5044. } // namespace Detail
  5045. #endif
  5046. template <typename T>
  5047. inline void deoptimize_value(T&& x) {
  5048. keep_memory(&x);
  5049. }
  5050. template <typename Fn, typename... Args>
  5051. inline auto invoke_deoptimized(Fn&& fn, Args&&... args) -> typename std::enable_if<!std::is_same<void, decltype(fn(args...))>::value>::type {
  5052. deoptimize_value(std::forward<Fn>(fn) (std::forward<Args...>(args...)));
  5053. }
  5054. template <typename Fn, typename... Args>
  5055. inline auto invoke_deoptimized(Fn&& fn, Args&&... args) -> typename std::enable_if<std::is_same<void, decltype(fn(args...))>::value>::type {
  5056. std::forward<Fn>(fn) (std::forward<Args...>(args...));
  5057. }
  5058. } // namespace Benchmark
  5059. } // namespace Catch
  5060. // end catch_optimizer.hpp
  5061. // start catch_complete_invoke.hpp
  5062. // Invoke with a special case for void
  5063. #include <type_traits>
  5064. #include <utility>
  5065. namespace Catch {
  5066. namespace Benchmark {
  5067. namespace Detail {
  5068. template <typename T>
  5069. struct CompleteType { using type = T; };
  5070. template <>
  5071. struct CompleteType<void> { struct type {}; };
  5072. template <typename T>
  5073. using CompleteType_t = typename CompleteType<T>::type;
  5074. template <typename Result>
  5075. struct CompleteInvoker {
  5076. template <typename Fun, typename... Args>
  5077. static Result invoke(Fun&& fun, Args&&... args) {
  5078. return std::forward<Fun>(fun)(std::forward<Args>(args)...);
  5079. }
  5080. };
  5081. template <>
  5082. struct CompleteInvoker<void> {
  5083. template <typename Fun, typename... Args>
  5084. static CompleteType_t<void> invoke(Fun&& fun, Args&&... args) {
  5085. std::forward<Fun>(fun)(std::forward<Args>(args)...);
  5086. return {};
  5087. }
  5088. };
  5089. template <typename Sig>
  5090. using ResultOf_t = typename std::result_of<Sig>::type;
  5091. // invoke and not return void :(
  5092. template <typename Fun, typename... Args>
  5093. CompleteType_t<ResultOf_t<Fun(Args...)>> complete_invoke(Fun&& fun, Args&&... args) {
  5094. return CompleteInvoker<ResultOf_t<Fun(Args...)>>::invoke(std::forward<Fun>(fun), std::forward<Args>(args)...);
  5095. }
  5096. const std::string benchmarkErrorMsg = "a benchmark failed to run successfully";
  5097. } // namespace Detail
  5098. template <typename Fun>
  5099. Detail::CompleteType_t<Detail::ResultOf_t<Fun()>> user_code(Fun&& fun) {
  5100. CATCH_TRY{
  5101. return Detail::complete_invoke(std::forward<Fun>(fun));
  5102. } CATCH_CATCH_ALL{
  5103. getResultCapture().benchmarkFailed(translateActiveException());
  5104. CATCH_RUNTIME_ERROR(Detail::benchmarkErrorMsg);
  5105. }
  5106. }
  5107. } // namespace Benchmark
  5108. } // namespace Catch
  5109. // end catch_complete_invoke.hpp
  5110. namespace Catch {
  5111. namespace Benchmark {
  5112. namespace Detail {
  5113. struct ChronometerConcept {
  5114. virtual void start() = 0;
  5115. virtual void finish() = 0;
  5116. virtual ~ChronometerConcept() = default;
  5117. };
  5118. template <typename Clock>
  5119. struct ChronometerModel final : public ChronometerConcept {
  5120. void start() override { started = Clock::now(); }
  5121. void finish() override { finished = Clock::now(); }
  5122. ClockDuration<Clock> elapsed() const { return finished - started; }
  5123. TimePoint<Clock> started;
  5124. TimePoint<Clock> finished;
  5125. };
  5126. } // namespace Detail
  5127. struct Chronometer {
  5128. public:
  5129. template <typename Fun>
  5130. void measure(Fun&& fun) { measure(std::forward<Fun>(fun), is_callable<Fun(int)>()); }
  5131. int runs() const { return k; }
  5132. Chronometer(Detail::ChronometerConcept& meter, int k)
  5133. : impl(&meter)
  5134. , k(k) {}
  5135. private:
  5136. template <typename Fun>
  5137. void measure(Fun&& fun, std::false_type) {
  5138. measure([&fun](int) { return fun(); }, std::true_type());
  5139. }
  5140. template <typename Fun>
  5141. void measure(Fun&& fun, std::true_type) {
  5142. Detail::optimizer_barrier();
  5143. impl->start();
  5144. for (int i = 0; i < k; ++i) invoke_deoptimized(fun, i);
  5145. impl->finish();
  5146. Detail::optimizer_barrier();
  5147. }
  5148. Detail::ChronometerConcept* impl;
  5149. int k;
  5150. };
  5151. } // namespace Benchmark
  5152. } // namespace Catch
  5153. // end catch_chronometer.hpp
  5154. // start catch_environment.hpp
  5155. // Environment information
  5156. namespace Catch {
  5157. namespace Benchmark {
  5158. template <typename Duration>
  5159. struct EnvironmentEstimate {
  5160. Duration mean;
  5161. OutlierClassification outliers;
  5162. template <typename Duration2>
  5163. operator EnvironmentEstimate<Duration2>() const {
  5164. return { mean, outliers };
  5165. }
  5166. };
  5167. template <typename Clock>
  5168. struct Environment {
  5169. using clock_type = Clock;
  5170. EnvironmentEstimate<FloatDuration<Clock>> clock_resolution;
  5171. EnvironmentEstimate<FloatDuration<Clock>> clock_cost;
  5172. };
  5173. } // namespace Benchmark
  5174. } // namespace Catch
  5175. // end catch_environment.hpp
  5176. // start catch_execution_plan.hpp
  5177. // Execution plan
  5178. // start catch_benchmark_function.hpp
  5179. // Dumb std::function implementation for consistent call overhead
  5180. #include <cassert>
  5181. #include <type_traits>
  5182. #include <utility>
  5183. #include <memory>
  5184. namespace Catch {
  5185. namespace Benchmark {
  5186. namespace Detail {
  5187. template <typename T>
  5188. using Decay = typename std::decay<T>::type;
  5189. template <typename T, typename U>
  5190. struct is_related
  5191. : std::is_same<Decay<T>, Decay<U>> {};
  5192. /// We need to reinvent std::function because every piece of code that might add overhead
  5193. /// in a measurement context needs to have consistent performance characteristics so that we
  5194. /// can account for it in the measurement.
  5195. /// Implementations of std::function with optimizations that aren't always applicable, like
  5196. /// small buffer optimizations, are not uncommon.
  5197. /// This is effectively an implementation of std::function without any such optimizations;
  5198. /// it may be slow, but it is consistently slow.
  5199. struct BenchmarkFunction {
  5200. private:
  5201. struct callable {
  5202. virtual void call(Chronometer meter) const = 0;
  5203. virtual callable* clone() const = 0;
  5204. virtual ~callable() = default;
  5205. };
  5206. template <typename Fun>
  5207. struct model : public callable {
  5208. model(Fun&& fun) : fun(std::move(fun)) {}
  5209. model(Fun const& fun) : fun(fun) {}
  5210. model<Fun>* clone() const override { return new model<Fun>(*this); }
  5211. void call(Chronometer meter) const override {
  5212. call(meter, is_callable<Fun(Chronometer)>());
  5213. }
  5214. void call(Chronometer meter, std::true_type) const {
  5215. fun(meter);
  5216. }
  5217. void call(Chronometer meter, std::false_type) const {
  5218. meter.measure(fun);
  5219. }
  5220. Fun fun;
  5221. };
  5222. struct do_nothing { void operator()() const {} };
  5223. template <typename T>
  5224. BenchmarkFunction(model<T>* c) : f(c) {}
  5225. public:
  5226. BenchmarkFunction()
  5227. : f(new model<do_nothing>{ {} }) {}
  5228. template <typename Fun,
  5229. typename std::enable_if<!is_related<Fun, BenchmarkFunction>::value, int>::type = 0>
  5230. BenchmarkFunction(Fun&& fun)
  5231. : f(new model<typename std::decay<Fun>::type>(std::forward<Fun>(fun))) {}
  5232. BenchmarkFunction(BenchmarkFunction&& that)
  5233. : f(std::move(that.f)) {}
  5234. BenchmarkFunction(BenchmarkFunction const& that)
  5235. : f(that.f->clone()) {}
  5236. BenchmarkFunction& operator=(BenchmarkFunction&& that) {
  5237. f = std::move(that.f);
  5238. return *this;
  5239. }
  5240. BenchmarkFunction& operator=(BenchmarkFunction const& that) {
  5241. f.reset(that.f->clone());
  5242. return *this;
  5243. }
  5244. void operator()(Chronometer meter) const { f->call(meter); }
  5245. private:
  5246. std::unique_ptr<callable> f;
  5247. };
  5248. } // namespace Detail
  5249. } // namespace Benchmark
  5250. } // namespace Catch
  5251. // end catch_benchmark_function.hpp
  5252. // start catch_repeat.hpp
  5253. // repeat algorithm
  5254. #include <type_traits>
  5255. #include <utility>
  5256. namespace Catch {
  5257. namespace Benchmark {
  5258. namespace Detail {
  5259. template <typename Fun>
  5260. struct repeater {
  5261. void operator()(int k) const {
  5262. for (int i = 0; i < k; ++i) {
  5263. fun();
  5264. }
  5265. }
  5266. Fun fun;
  5267. };
  5268. template <typename Fun>
  5269. repeater<typename std::decay<Fun>::type> repeat(Fun&& fun) {
  5270. return { std::forward<Fun>(fun) };
  5271. }
  5272. } // namespace Detail
  5273. } // namespace Benchmark
  5274. } // namespace Catch
  5275. // end catch_repeat.hpp
  5276. // start catch_run_for_at_least.hpp
  5277. // Run a function for a minimum amount of time
  5278. // start catch_measure.hpp
  5279. // Measure
  5280. // start catch_timing.hpp
  5281. // Timing
  5282. #include <tuple>
  5283. #include <type_traits>
  5284. namespace Catch {
  5285. namespace Benchmark {
  5286. template <typename Duration, typename Result>
  5287. struct Timing {
  5288. Duration elapsed;
  5289. Result result;
  5290. int iterations;
  5291. };
  5292. template <typename Clock, typename Sig>
  5293. using TimingOf = Timing<ClockDuration<Clock>, Detail::CompleteType_t<Detail::ResultOf_t<Sig>>>;
  5294. } // namespace Benchmark
  5295. } // namespace Catch
  5296. // end catch_timing.hpp
  5297. #include <utility>
  5298. namespace Catch {
  5299. namespace Benchmark {
  5300. namespace Detail {
  5301. template <typename Clock, typename Fun, typename... Args>
  5302. TimingOf<Clock, Fun(Args...)> measure(Fun&& fun, Args&&... args) {
  5303. auto start = Clock::now();
  5304. auto&& r = Detail::complete_invoke(fun, std::forward<Args>(args)...);
  5305. auto end = Clock::now();
  5306. auto delta = end - start;
  5307. return { delta, std::forward<decltype(r)>(r), 1 };
  5308. }
  5309. } // namespace Detail
  5310. } // namespace Benchmark
  5311. } // namespace Catch
  5312. // end catch_measure.hpp
  5313. #include <utility>
  5314. #include <type_traits>
  5315. namespace Catch {
  5316. namespace Benchmark {
  5317. namespace Detail {
  5318. template <typename Clock, typename Fun>
  5319. TimingOf<Clock, Fun(int)> measure_one(Fun&& fun, int iters, std::false_type) {
  5320. return Detail::measure<Clock>(fun, iters);
  5321. }
  5322. template <typename Clock, typename Fun>
  5323. TimingOf<Clock, Fun(Chronometer)> measure_one(Fun&& fun, int iters, std::true_type) {
  5324. Detail::ChronometerModel<Clock> meter;
  5325. auto&& result = Detail::complete_invoke(fun, Chronometer(meter, iters));
  5326. return { meter.elapsed(), std::move(result), iters };
  5327. }
  5328. template <typename Clock, typename Fun>
  5329. using run_for_at_least_argument_t = typename std::conditional<is_callable<Fun(Chronometer)>::value, Chronometer, int>::type;
  5330. struct optimized_away_error : std::exception {
  5331. const char* what() const noexcept override {
  5332. return "could not measure benchmark, maybe it was optimized away";
  5333. }
  5334. };
  5335. template <typename Clock, typename Fun>
  5336. TimingOf<Clock, Fun(run_for_at_least_argument_t<Clock, Fun>)> run_for_at_least(ClockDuration<Clock> how_long, int seed, Fun&& fun) {
  5337. auto iters = seed;
  5338. while (iters < (1 << 30)) {
  5339. auto&& Timing = measure_one<Clock>(fun, iters, is_callable<Fun(Chronometer)>());
  5340. if (Timing.elapsed >= how_long) {
  5341. return { Timing.elapsed, std::move(Timing.result), iters };
  5342. }
  5343. iters *= 2;
  5344. }
  5345. throw optimized_away_error{};
  5346. }
  5347. } // namespace Detail
  5348. } // namespace Benchmark
  5349. } // namespace Catch
  5350. // end catch_run_for_at_least.hpp
  5351. #include <algorithm>
  5352. namespace Catch {
  5353. namespace Benchmark {
  5354. template <typename Duration>
  5355. struct ExecutionPlan {
  5356. int iterations_per_sample;
  5357. Duration estimated_duration;
  5358. Detail::BenchmarkFunction benchmark;
  5359. Duration warmup_time;
  5360. int warmup_iterations;
  5361. template <typename Duration2>
  5362. operator ExecutionPlan<Duration2>() const {
  5363. return { iterations_per_sample, estimated_duration, benchmark, warmup_time, warmup_iterations };
  5364. }
  5365. template <typename Clock>
  5366. std::vector<FloatDuration<Clock>> run(const IConfig &cfg, Environment<FloatDuration<Clock>> env) const {
  5367. // warmup a bit
  5368. Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_iterations, Detail::repeat(now<Clock>{}));
  5369. std::vector<FloatDuration<Clock>> times;
  5370. times.reserve(cfg.benchmarkSamples());
  5371. std::generate_n(std::back_inserter(times), cfg.benchmarkSamples(), [this, env] {
  5372. Detail::ChronometerModel<Clock> model;
  5373. this->benchmark(Chronometer(model, iterations_per_sample));
  5374. auto sample_time = model.elapsed() - env.clock_cost.mean;
  5375. if (sample_time < FloatDuration<Clock>::zero()) sample_time = FloatDuration<Clock>::zero();
  5376. return sample_time / iterations_per_sample;
  5377. });
  5378. return times;
  5379. }
  5380. };
  5381. } // namespace Benchmark
  5382. } // namespace Catch
  5383. // end catch_execution_plan.hpp
  5384. // start catch_estimate_clock.hpp
  5385. // Environment measurement
  5386. // start catch_stats.hpp
  5387. // Statistical analysis tools
  5388. #include <algorithm>
  5389. #include <functional>
  5390. #include <vector>
  5391. #include <numeric>
  5392. #include <tuple>
  5393. #include <cmath>
  5394. #include <utility>
  5395. #include <cstddef>
  5396. namespace Catch {
  5397. namespace Benchmark {
  5398. namespace Detail {
  5399. using sample = std::vector<double>;
  5400. double weighted_average_quantile(int k, int q, std::vector<double>::iterator first, std::vector<double>::iterator last);
  5401. template <typename Iterator>
  5402. OutlierClassification classify_outliers(Iterator first, Iterator last) {
  5403. std::vector<double> copy(first, last);
  5404. auto q1 = weighted_average_quantile(1, 4, copy.begin(), copy.end());
  5405. auto q3 = weighted_average_quantile(3, 4, copy.begin(), copy.end());
  5406. auto iqr = q3 - q1;
  5407. auto los = q1 - (iqr * 3.);
  5408. auto lom = q1 - (iqr * 1.5);
  5409. auto him = q3 + (iqr * 1.5);
  5410. auto his = q3 + (iqr * 3.);
  5411. OutlierClassification o;
  5412. for (; first != last; ++first) {
  5413. auto&& t = *first;
  5414. if (t < los) ++o.low_severe;
  5415. else if (t < lom) ++o.low_mild;
  5416. else if (t > his) ++o.high_severe;
  5417. else if (t > him) ++o.high_mild;
  5418. ++o.samples_seen;
  5419. }
  5420. return o;
  5421. }
  5422. template <typename Iterator>
  5423. double mean(Iterator first, Iterator last) {
  5424. auto count = last - first;
  5425. double sum = std::accumulate(first, last, 0.);
  5426. return sum / count;
  5427. }
  5428. template <typename URng, typename Iterator, typename Estimator>
  5429. sample resample(URng& rng, int resamples, Iterator first, Iterator last, Estimator& estimator) {
  5430. auto n = last - first;
  5431. std::uniform_int_distribution<decltype(n)> dist(0, n - 1);
  5432. sample out;
  5433. out.reserve(resamples);
  5434. std::generate_n(std::back_inserter(out), resamples, [n, first, &estimator, &dist, &rng] {
  5435. std::vector<double> resampled;
  5436. resampled.reserve(n);
  5437. std::generate_n(std::back_inserter(resampled), n, [first, &dist, &rng] { return first[dist(rng)]; });
  5438. return estimator(resampled.begin(), resampled.end());
  5439. });
  5440. std::sort(out.begin(), out.end());
  5441. return out;
  5442. }
  5443. template <typename Estimator, typename Iterator>
  5444. sample jackknife(Estimator&& estimator, Iterator first, Iterator last) {
  5445. auto n = last - first;
  5446. auto second = std::next(first);
  5447. sample results;
  5448. results.reserve(n);
  5449. for (auto it = first; it != last; ++it) {
  5450. std::iter_swap(it, first);
  5451. results.push_back(estimator(second, last));
  5452. }
  5453. return results;
  5454. }
  5455. inline double normal_cdf(double x) {
  5456. return std::erfc(-x / std::sqrt(2.0)) / 2.0;
  5457. }
  5458. double erfc_inv(double x);
  5459. double normal_quantile(double p);
  5460. template <typename Iterator, typename Estimator>
  5461. Estimate<double> bootstrap(double confidence_level, Iterator first, Iterator last, sample const& resample, Estimator&& estimator) {
  5462. auto n_samples = last - first;
  5463. double point = estimator(first, last);
  5464. // Degenerate case with a single sample
  5465. if (n_samples == 1) return { point, point, point, confidence_level };
  5466. sample jack = jackknife(estimator, first, last);
  5467. double jack_mean = mean(jack.begin(), jack.end());
  5468. double sum_squares, sum_cubes;
  5469. 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> {
  5470. auto d = jack_mean - x;
  5471. auto d2 = d * d;
  5472. auto d3 = d2 * d;
  5473. return { sqcb.first + d2, sqcb.second + d3 };
  5474. });
  5475. double accel = sum_cubes / (6 * std::pow(sum_squares, 1.5));
  5476. int n = static_cast<int>(resample.size());
  5477. double prob_n = std::count_if(resample.begin(), resample.end(), [point](double x) { return x < point; }) / (double)n;
  5478. // degenerate case with uniform samples
  5479. if (prob_n == 0) return { point, point, point, confidence_level };
  5480. double bias = normal_quantile(prob_n);
  5481. double z1 = normal_quantile((1. - confidence_level) / 2.);
  5482. auto cumn = [n](double x) -> int {
  5483. return std::lround(normal_cdf(x) * n); };
  5484. auto a = [bias, accel](double b) { return bias + b / (1. - accel * b); };
  5485. double b1 = bias + z1;
  5486. double b2 = bias - z1;
  5487. double a1 = a(b1);
  5488. double a2 = a(b2);
  5489. auto lo = std::max(cumn(a1), 0);
  5490. auto hi = std::min(cumn(a2), n - 1);
  5491. return { point, resample[lo], resample[hi], confidence_level };
  5492. }
  5493. double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n);
  5494. struct bootstrap_analysis {
  5495. Estimate<double> mean;
  5496. Estimate<double> standard_deviation;
  5497. double outlier_variance;
  5498. };
  5499. bootstrap_analysis analyse_samples(double confidence_level, int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last);
  5500. } // namespace Detail
  5501. } // namespace Benchmark
  5502. } // namespace Catch
  5503. // end catch_stats.hpp
  5504. #include <algorithm>
  5505. #include <iterator>
  5506. #include <tuple>
  5507. #include <vector>
  5508. #include <cmath>
  5509. namespace Catch {
  5510. namespace Benchmark {
  5511. namespace Detail {
  5512. template <typename Clock>
  5513. std::vector<double> resolution(int k) {
  5514. std::vector<TimePoint<Clock>> times;
  5515. times.reserve(k + 1);
  5516. std::generate_n(std::back_inserter(times), k + 1, now<Clock>{});
  5517. std::vector<double> deltas;
  5518. deltas.reserve(k);
  5519. std::transform(std::next(times.begin()), times.end(), times.begin(),
  5520. std::back_inserter(deltas),
  5521. [](TimePoint<Clock> a, TimePoint<Clock> b) { return static_cast<double>((a - b).count()); });
  5522. return deltas;
  5523. }
  5524. const auto warmup_iterations = 10000;
  5525. const auto warmup_time = std::chrono::milliseconds(100);
  5526. const auto minimum_ticks = 1000;
  5527. const auto warmup_seed = 10000;
  5528. const auto clock_resolution_estimation_time = std::chrono::milliseconds(500);
  5529. const auto clock_cost_estimation_time_limit = std::chrono::seconds(1);
  5530. const auto clock_cost_estimation_tick_limit = 100000;
  5531. const auto clock_cost_estimation_time = std::chrono::milliseconds(10);
  5532. const auto clock_cost_estimation_iterations = 10000;
  5533. template <typename Clock>
  5534. int warmup() {
  5535. return run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_seed, &resolution<Clock>)
  5536. .iterations;
  5537. }
  5538. template <typename Clock>
  5539. EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_resolution(int iterations) {
  5540. auto r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_resolution_estimation_time), iterations, &resolution<Clock>)
  5541. .result;
  5542. return {
  5543. FloatDuration<Clock>(mean(r.begin(), r.end())),
  5544. classify_outliers(r.begin(), r.end()),
  5545. };
  5546. }
  5547. template <typename Clock>
  5548. EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_cost(FloatDuration<Clock> resolution) {
  5549. auto time_limit = std::min(resolution * clock_cost_estimation_tick_limit, FloatDuration<Clock>(clock_cost_estimation_time_limit));
  5550. auto time_clock = [](int k) {
  5551. return Detail::measure<Clock>([k] {
  5552. for (int i = 0; i < k; ++i) {
  5553. volatile auto ignored = Clock::now();
  5554. (void)ignored;
  5555. }
  5556. }).elapsed;
  5557. };
  5558. time_clock(1);
  5559. int iters = clock_cost_estimation_iterations;
  5560. auto&& r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_cost_estimation_time), iters, time_clock);
  5561. std::vector<double> times;
  5562. int nsamples = static_cast<int>(std::ceil(time_limit / r.elapsed));
  5563. times.reserve(nsamples);
  5564. std::generate_n(std::back_inserter(times), nsamples, [time_clock, &r] {
  5565. return static_cast<double>((time_clock(r.iterations) / r.iterations).count());
  5566. });
  5567. return {
  5568. FloatDuration<Clock>(mean(times.begin(), times.end())),
  5569. classify_outliers(times.begin(), times.end()),
  5570. };
  5571. }
  5572. template <typename Clock>
  5573. Environment<FloatDuration<Clock>> measure_environment() {
  5574. static Environment<FloatDuration<Clock>>* env = nullptr;
  5575. if (env) {
  5576. return *env;
  5577. }
  5578. auto iters = Detail::warmup<Clock>();
  5579. auto resolution = Detail::estimate_clock_resolution<Clock>(iters);
  5580. auto cost = Detail::estimate_clock_cost<Clock>(resolution.mean);
  5581. env = new Environment<FloatDuration<Clock>>{ resolution, cost };
  5582. return *env;
  5583. }
  5584. } // namespace Detail
  5585. } // namespace Benchmark
  5586. } // namespace Catch
  5587. // end catch_estimate_clock.hpp
  5588. // start catch_analyse.hpp
  5589. // Run and analyse one benchmark
  5590. // start catch_sample_analysis.hpp
  5591. // Benchmark results
  5592. #include <algorithm>
  5593. #include <vector>
  5594. #include <string>
  5595. #include <iterator>
  5596. namespace Catch {
  5597. namespace Benchmark {
  5598. template <typename Duration>
  5599. struct SampleAnalysis {
  5600. std::vector<Duration> samples;
  5601. Estimate<Duration> mean;
  5602. Estimate<Duration> standard_deviation;
  5603. OutlierClassification outliers;
  5604. double outlier_variance;
  5605. template <typename Duration2>
  5606. operator SampleAnalysis<Duration2>() const {
  5607. std::vector<Duration2> samples2;
  5608. samples2.reserve(samples.size());
  5609. std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration d) { return Duration2(d); });
  5610. return {
  5611. std::move(samples2),
  5612. mean,
  5613. standard_deviation,
  5614. outliers,
  5615. outlier_variance,
  5616. };
  5617. }
  5618. };
  5619. } // namespace Benchmark
  5620. } // namespace Catch
  5621. // end catch_sample_analysis.hpp
  5622. #include <algorithm>
  5623. #include <iterator>
  5624. #include <vector>
  5625. namespace Catch {
  5626. namespace Benchmark {
  5627. namespace Detail {
  5628. template <typename Duration, typename Iterator>
  5629. SampleAnalysis<Duration> analyse(const IConfig &cfg, Environment<Duration>, Iterator first, Iterator last) {
  5630. if (!cfg.benchmarkNoAnalysis()) {
  5631. std::vector<double> samples;
  5632. samples.reserve(last - first);
  5633. std::transform(first, last, std::back_inserter(samples), [](Duration d) { return d.count(); });
  5634. auto analysis = Catch::Benchmark::Detail::analyse_samples(cfg.benchmarkConfidenceInterval(), cfg.benchmarkResamples(), samples.begin(), samples.end());
  5635. auto outliers = Catch::Benchmark::Detail::classify_outliers(samples.begin(), samples.end());
  5636. auto wrap_estimate = [](Estimate<double> e) {
  5637. return Estimate<Duration> {
  5638. Duration(e.point),
  5639. Duration(e.lower_bound),
  5640. Duration(e.upper_bound),
  5641. e.confidence_interval,
  5642. };
  5643. };
  5644. std::vector<Duration> samples2;
  5645. samples2.reserve(samples.size());
  5646. std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](double d) { return Duration(d); });
  5647. return {
  5648. std::move(samples2),
  5649. wrap_estimate(analysis.mean),
  5650. wrap_estimate(analysis.standard_deviation),
  5651. outliers,
  5652. analysis.outlier_variance,
  5653. };
  5654. } else {
  5655. std::vector<Duration> samples;
  5656. samples.reserve(last - first);
  5657. Duration mean = Duration(0);
  5658. int i = 0;
  5659. for (auto it = first; it < last; ++it, ++i) {
  5660. samples.push_back(Duration(*it));
  5661. mean += Duration(*it);
  5662. }
  5663. mean /= i;
  5664. return {
  5665. std::move(samples),
  5666. Estimate<Duration>{mean, mean, mean, 0.0},
  5667. Estimate<Duration>{Duration(0), Duration(0), Duration(0), 0.0},
  5668. OutlierClassification{},
  5669. 0.0
  5670. };
  5671. }
  5672. }
  5673. } // namespace Detail
  5674. } // namespace Benchmark
  5675. } // namespace Catch
  5676. // end catch_analyse.hpp
  5677. #include <algorithm>
  5678. #include <functional>
  5679. #include <string>
  5680. #include <vector>
  5681. #include <cmath>
  5682. namespace Catch {
  5683. namespace Benchmark {
  5684. struct Benchmark {
  5685. Benchmark(std::string &&name)
  5686. : name(std::move(name)) {}
  5687. template <class FUN>
  5688. Benchmark(std::string &&name, FUN &&func)
  5689. : fun(std::move(func)), name(std::move(name)) {}
  5690. template <typename Clock>
  5691. ExecutionPlan<FloatDuration<Clock>> prepare(const IConfig &cfg, Environment<FloatDuration<Clock>> env) const {
  5692. auto min_time = env.clock_resolution.mean * Detail::minimum_ticks;
  5693. auto run_time = std::max(min_time, std::chrono::duration_cast<decltype(min_time)>(Detail::warmup_time));
  5694. auto&& test = Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(run_time), 1, fun);
  5695. int new_iters = static_cast<int>(std::ceil(min_time * test.iterations / test.elapsed));
  5696. return { new_iters, test.elapsed / test.iterations * new_iters * cfg.benchmarkSamples(), fun, std::chrono::duration_cast<FloatDuration<Clock>>(Detail::warmup_time), Detail::warmup_iterations };
  5697. }
  5698. template <typename Clock = default_clock>
  5699. void run() {
  5700. IConfigPtr cfg = getCurrentContext().getConfig();
  5701. auto env = Detail::measure_environment<Clock>();
  5702. getResultCapture().benchmarkPreparing(name);
  5703. CATCH_TRY{
  5704. auto plan = user_code([&] {
  5705. return prepare<Clock>(*cfg, env);
  5706. });
  5707. BenchmarkInfo info {
  5708. name,
  5709. plan.estimated_duration.count(),
  5710. plan.iterations_per_sample,
  5711. cfg->benchmarkSamples(),
  5712. cfg->benchmarkResamples(),
  5713. env.clock_resolution.mean.count(),
  5714. env.clock_cost.mean.count()
  5715. };
  5716. getResultCapture().benchmarkStarting(info);
  5717. auto samples = user_code([&] {
  5718. return plan.template run<Clock>(*cfg, env);
  5719. });
  5720. auto analysis = Detail::analyse(*cfg, env, samples.begin(), samples.end());
  5721. BenchmarkStats<std::chrono::duration<double, std::nano>> stats{ info, analysis.samples, analysis.mean, analysis.standard_deviation, analysis.outliers, analysis.outlier_variance };
  5722. getResultCapture().benchmarkEnded(stats);
  5723. } CATCH_CATCH_ALL{
  5724. if (translateActiveException() != Detail::benchmarkErrorMsg) // benchmark errors have been reported, otherwise rethrow.
  5725. std::rethrow_exception(std::current_exception());
  5726. }
  5727. }
  5728. // sets lambda to be used in fun *and* executes benchmark!
  5729. template <typename Fun,
  5730. typename std::enable_if<!Detail::is_related<Fun, Benchmark>::value, int>::type = 0>
  5731. Benchmark & operator=(Fun func) {
  5732. fun = Detail::BenchmarkFunction(func);
  5733. run();
  5734. return *this;
  5735. }
  5736. explicit operator bool() {
  5737. return true;
  5738. }
  5739. private:
  5740. Detail::BenchmarkFunction fun;
  5741. std::string name;
  5742. };
  5743. }
  5744. } // namespace Catch
  5745. #define INTERNAL_CATCH_GET_1_ARG(arg1, arg2, ...) arg1
  5746. #define INTERNAL_CATCH_GET_2_ARG(arg1, arg2, ...) arg2
  5747. #define INTERNAL_CATCH_BENCHMARK(BenchmarkName, name, benchmarkIndex)\
  5748. if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \
  5749. BenchmarkName = [&](int benchmarkIndex)
  5750. #define INTERNAL_CATCH_BENCHMARK_ADVANCED(BenchmarkName, name)\
  5751. if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \
  5752. BenchmarkName = [&]
  5753. // end catch_benchmark.hpp
  5754. #endif
  5755. #endif // ! CATCH_CONFIG_IMPL_ONLY
  5756. #ifdef CATCH_IMPL
  5757. // start catch_impl.hpp
  5758. #ifdef __clang__
  5759. #pragma clang diagnostic push
  5760. #pragma clang diagnostic ignored "-Wweak-vtables"
  5761. #endif
  5762. // Keep these here for external reporters
  5763. // start catch_test_case_tracker.h
  5764. #include <string>
  5765. #include <vector>
  5766. #include <memory>
  5767. namespace Catch {
  5768. namespace TestCaseTracking {
  5769. struct NameAndLocation {
  5770. std::string name;
  5771. SourceLineInfo location;
  5772. NameAndLocation( std::string const& _name, SourceLineInfo const& _location );
  5773. };
  5774. struct ITracker;
  5775. using ITrackerPtr = std::shared_ptr<ITracker>;
  5776. struct ITracker {
  5777. virtual ~ITracker();
  5778. // static queries
  5779. virtual NameAndLocation const& nameAndLocation() const = 0;
  5780. // dynamic queries
  5781. virtual bool isComplete() const = 0; // Successfully completed or failed
  5782. virtual bool isSuccessfullyCompleted() const = 0;
  5783. virtual bool isOpen() const = 0; // Started but not complete
  5784. virtual bool hasChildren() const = 0;
  5785. virtual ITracker& parent() = 0;
  5786. // actions
  5787. virtual void close() = 0; // Successfully complete
  5788. virtual void fail() = 0;
  5789. virtual void markAsNeedingAnotherRun() = 0;
  5790. virtual void addChild( ITrackerPtr const& child ) = 0;
  5791. virtual ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) = 0;
  5792. virtual void openChild() = 0;
  5793. // Debug/ checking
  5794. virtual bool isSectionTracker() const = 0;
  5795. virtual bool isGeneratorTracker() const = 0;
  5796. };
  5797. class TrackerContext {
  5798. enum RunState {
  5799. NotStarted,
  5800. Executing,
  5801. CompletedCycle
  5802. };
  5803. ITrackerPtr m_rootTracker;
  5804. ITracker* m_currentTracker = nullptr;
  5805. RunState m_runState = NotStarted;
  5806. public:
  5807. ITracker& startRun();
  5808. void endRun();
  5809. void startCycle();
  5810. void completeCycle();
  5811. bool completedCycle() const;
  5812. ITracker& currentTracker();
  5813. void setCurrentTracker( ITracker* tracker );
  5814. };
  5815. class TrackerBase : public ITracker {
  5816. protected:
  5817. enum CycleState {
  5818. NotStarted,
  5819. Executing,
  5820. ExecutingChildren,
  5821. NeedsAnotherRun,
  5822. CompletedSuccessfully,
  5823. Failed
  5824. };
  5825. using Children = std::vector<ITrackerPtr>;
  5826. NameAndLocation m_nameAndLocation;
  5827. TrackerContext& m_ctx;
  5828. ITracker* m_parent;
  5829. Children m_children;
  5830. CycleState m_runState = NotStarted;
  5831. public:
  5832. TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  5833. NameAndLocation const& nameAndLocation() const override;
  5834. bool isComplete() const override;
  5835. bool isSuccessfullyCompleted() const override;
  5836. bool isOpen() const override;
  5837. bool hasChildren() const override;
  5838. void addChild( ITrackerPtr const& child ) override;
  5839. ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) override;
  5840. ITracker& parent() override;
  5841. void openChild() override;
  5842. bool isSectionTracker() const override;
  5843. bool isGeneratorTracker() const override;
  5844. void open();
  5845. void close() override;
  5846. void fail() override;
  5847. void markAsNeedingAnotherRun() override;
  5848. private:
  5849. void moveToParent();
  5850. void moveToThis();
  5851. };
  5852. class SectionTracker : public TrackerBase {
  5853. std::vector<std::string> m_filters;
  5854. public:
  5855. SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  5856. bool isSectionTracker() const override;
  5857. bool isComplete() const override;
  5858. static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation );
  5859. void tryOpen();
  5860. void addInitialFilters( std::vector<std::string> const& filters );
  5861. void addNextFilters( std::vector<std::string> const& filters );
  5862. };
  5863. } // namespace TestCaseTracking
  5864. using TestCaseTracking::ITracker;
  5865. using TestCaseTracking::TrackerContext;
  5866. using TestCaseTracking::SectionTracker;
  5867. } // namespace Catch
  5868. // end catch_test_case_tracker.h
  5869. // start catch_leak_detector.h
  5870. namespace Catch {
  5871. struct LeakDetector {
  5872. LeakDetector();
  5873. ~LeakDetector();
  5874. };
  5875. }
  5876. // end catch_leak_detector.h
  5877. // Cpp files will be included in the single-header file here
  5878. // start catch_stats.cpp
  5879. // Statistical analysis tools
  5880. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  5881. #include <cassert>
  5882. #include <random>
  5883. #if defined(CATCH_CONFIG_USE_ASYNC)
  5884. #include <future>
  5885. #endif
  5886. namespace {
  5887. double erf_inv(double x) {
  5888. // Code accompanying the article "Approximating the erfinv function" in GPU Computing Gems, Volume 2
  5889. double w, p;
  5890. w = -log((1.0 - x) * (1.0 + x));
  5891. if (w < 6.250000) {
  5892. w = w - 3.125000;
  5893. p = -3.6444120640178196996e-21;
  5894. p = -1.685059138182016589e-19 + p * w;
  5895. p = 1.2858480715256400167e-18 + p * w;
  5896. p = 1.115787767802518096e-17 + p * w;
  5897. p = -1.333171662854620906e-16 + p * w;
  5898. p = 2.0972767875968561637e-17 + p * w;
  5899. p = 6.6376381343583238325e-15 + p * w;
  5900. p = -4.0545662729752068639e-14 + p * w;
  5901. p = -8.1519341976054721522e-14 + p * w;
  5902. p = 2.6335093153082322977e-12 + p * w;
  5903. p = -1.2975133253453532498e-11 + p * w;
  5904. p = -5.4154120542946279317e-11 + p * w;
  5905. p = 1.051212273321532285e-09 + p * w;
  5906. p = -4.1126339803469836976e-09 + p * w;
  5907. p = -2.9070369957882005086e-08 + p * w;
  5908. p = 4.2347877827932403518e-07 + p * w;
  5909. p = -1.3654692000834678645e-06 + p * w;
  5910. p = -1.3882523362786468719e-05 + p * w;
  5911. p = 0.0001867342080340571352 + p * w;
  5912. p = -0.00074070253416626697512 + p * w;
  5913. p = -0.0060336708714301490533 + p * w;
  5914. p = 0.24015818242558961693 + p * w;
  5915. p = 1.6536545626831027356 + p * w;
  5916. } else if (w < 16.000000) {
  5917. w = sqrt(w) - 3.250000;
  5918. p = 2.2137376921775787049e-09;
  5919. p = 9.0756561938885390979e-08 + p * w;
  5920. p = -2.7517406297064545428e-07 + p * w;
  5921. p = 1.8239629214389227755e-08 + p * w;
  5922. p = 1.5027403968909827627e-06 + p * w;
  5923. p = -4.013867526981545969e-06 + p * w;
  5924. p = 2.9234449089955446044e-06 + p * w;
  5925. p = 1.2475304481671778723e-05 + p * w;
  5926. p = -4.7318229009055733981e-05 + p * w;
  5927. p = 6.8284851459573175448e-05 + p * w;
  5928. p = 2.4031110387097893999e-05 + p * w;
  5929. p = -0.0003550375203628474796 + p * w;
  5930. p = 0.00095328937973738049703 + p * w;
  5931. p = -0.0016882755560235047313 + p * w;
  5932. p = 0.0024914420961078508066 + p * w;
  5933. p = -0.0037512085075692412107 + p * w;
  5934. p = 0.005370914553590063617 + p * w;
  5935. p = 1.0052589676941592334 + p * w;
  5936. p = 3.0838856104922207635 + p * w;
  5937. } else {
  5938. w = sqrt(w) - 5.000000;
  5939. p = -2.7109920616438573243e-11;
  5940. p = -2.5556418169965252055e-10 + p * w;
  5941. p = 1.5076572693500548083e-09 + p * w;
  5942. p = -3.7894654401267369937e-09 + p * w;
  5943. p = 7.6157012080783393804e-09 + p * w;
  5944. p = -1.4960026627149240478e-08 + p * w;
  5945. p = 2.9147953450901080826e-08 + p * w;
  5946. p = -6.7711997758452339498e-08 + p * w;
  5947. p = 2.2900482228026654717e-07 + p * w;
  5948. p = -9.9298272942317002539e-07 + p * w;
  5949. p = 4.5260625972231537039e-06 + p * w;
  5950. p = -1.9681778105531670567e-05 + p * w;
  5951. p = 7.5995277030017761139e-05 + p * w;
  5952. p = -0.00021503011930044477347 + p * w;
  5953. p = -0.00013871931833623122026 + p * w;
  5954. p = 1.0103004648645343977 + p * w;
  5955. p = 4.8499064014085844221 + p * w;
  5956. }
  5957. return p * x;
  5958. }
  5959. double standard_deviation(std::vector<double>::iterator first, std::vector<double>::iterator last) {
  5960. auto m = Catch::Benchmark::Detail::mean(first, last);
  5961. double variance = std::accumulate(first, last, 0., [m](double a, double b) {
  5962. double diff = b - m;
  5963. return a + diff * diff;
  5964. }) / (last - first);
  5965. return std::sqrt(variance);
  5966. }
  5967. }
  5968. namespace Catch {
  5969. namespace Benchmark {
  5970. namespace Detail {
  5971. double weighted_average_quantile(int k, int q, std::vector<double>::iterator first, std::vector<double>::iterator last) {
  5972. auto count = last - first;
  5973. double idx = (count - 1) * k / static_cast<double>(q);
  5974. int j = static_cast<int>(idx);
  5975. double g = idx - j;
  5976. std::nth_element(first, first + j, last);
  5977. auto xj = first[j];
  5978. if (g == 0) return xj;
  5979. auto xj1 = *std::min_element(first + (j + 1), last);
  5980. return xj + g * (xj1 - xj);
  5981. }
  5982. double erfc_inv(double x) {
  5983. return erf_inv(1.0 - x);
  5984. }
  5985. double normal_quantile(double p) {
  5986. static const double ROOT_TWO = std::sqrt(2.0);
  5987. double result = 0.0;
  5988. assert(p >= 0 && p <= 1);
  5989. if (p < 0 || p > 1) {
  5990. return result;
  5991. }
  5992. result = -erfc_inv(2.0 * p);
  5993. // result *= normal distribution standard deviation (1.0) * sqrt(2)
  5994. result *= /*sd * */ ROOT_TWO;
  5995. // result += normal disttribution mean (0)
  5996. return result;
  5997. }
  5998. double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n) {
  5999. double sb = stddev.point;
  6000. double mn = mean.point / n;
  6001. double mg_min = mn / 2.;
  6002. double sg = std::min(mg_min / 4., sb / std::sqrt(n));
  6003. double sg2 = sg * sg;
  6004. double sb2 = sb * sb;
  6005. auto c_max = [n, mn, sb2, sg2](double x) -> double {
  6006. double k = mn - x;
  6007. double d = k * k;
  6008. double nd = n * d;
  6009. double k0 = -n * nd;
  6010. double k1 = sb2 - n * sg2 + nd;
  6011. double det = k1 * k1 - 4 * sg2 * k0;
  6012. return (int)(-2. * k0 / (k1 + std::sqrt(det)));
  6013. };
  6014. auto var_out = [n, sb2, sg2](double c) {
  6015. double nc = n - c;
  6016. return (nc / n) * (sb2 - nc * sg2);
  6017. };
  6018. return std::min(var_out(1), var_out(std::min(c_max(0.), c_max(mg_min)))) / sb2;
  6019. }
  6020. bootstrap_analysis analyse_samples(double confidence_level, int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last) {
  6021. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  6022. static std::random_device entropy;
  6023. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  6024. auto n = static_cast<int>(last - first); // seriously, one can't use integral types without hell in C++
  6025. auto mean = &Detail::mean<std::vector<double>::iterator>;
  6026. auto stddev = &standard_deviation;
  6027. #if defined(CATCH_CONFIG_USE_ASYNC)
  6028. auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
  6029. auto seed = entropy();
  6030. return std::async(std::launch::async, [=] {
  6031. std::mt19937 rng(seed);
  6032. auto resampled = resample(rng, n_resamples, first, last, f);
  6033. return bootstrap(confidence_level, first, last, resampled, f);
  6034. });
  6035. };
  6036. auto mean_future = Estimate(mean);
  6037. auto stddev_future = Estimate(stddev);
  6038. auto mean_estimate = mean_future.get();
  6039. auto stddev_estimate = stddev_future.get();
  6040. #else
  6041. auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
  6042. auto seed = entropy();
  6043. std::mt19937 rng(seed);
  6044. auto resampled = resample(rng, n_resamples, first, last, f);
  6045. return bootstrap(confidence_level, first, last, resampled, f);
  6046. };
  6047. auto mean_estimate = Estimate(mean);
  6048. auto stddev_estimate = Estimate(stddev);
  6049. #endif // CATCH_USE_ASYNC
  6050. double outlier_variance = Detail::outlier_variance(mean_estimate, stddev_estimate, n);
  6051. return { mean_estimate, stddev_estimate, outlier_variance };
  6052. }
  6053. } // namespace Detail
  6054. } // namespace Benchmark
  6055. } // namespace Catch
  6056. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  6057. // end catch_stats.cpp
  6058. // start catch_approx.cpp
  6059. #include <cmath>
  6060. #include <limits>
  6061. namespace {
  6062. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  6063. // But without the subtraction to allow for INFINITY in comparison
  6064. bool marginComparison(double lhs, double rhs, double margin) {
  6065. return (lhs + margin >= rhs) && (rhs + margin >= lhs);
  6066. }
  6067. }
  6068. namespace Catch {
  6069. namespace Detail {
  6070. Approx::Approx ( double value )
  6071. : m_epsilon( std::numeric_limits<float>::epsilon()*100 ),
  6072. m_margin( 0.0 ),
  6073. m_scale( 0.0 ),
  6074. m_value( value )
  6075. {}
  6076. Approx Approx::custom() {
  6077. return Approx( 0 );
  6078. }
  6079. Approx Approx::operator-() const {
  6080. auto temp(*this);
  6081. temp.m_value = -temp.m_value;
  6082. return temp;
  6083. }
  6084. std::string Approx::toString() const {
  6085. ReusableStringStream rss;
  6086. rss << "Approx( " << ::Catch::Detail::stringify( m_value ) << " )";
  6087. return rss.str();
  6088. }
  6089. bool Approx::equalityComparisonImpl(const double other) const {
  6090. // First try with fixed margin, then compute margin based on epsilon, scale and Approx's value
  6091. // Thanks to Richard Harris for his help refining the scaled margin value
  6092. return marginComparison(m_value, other, m_margin) || marginComparison(m_value, other, m_epsilon * (m_scale + std::fabs(m_value)));
  6093. }
  6094. void Approx::setMargin(double newMargin) {
  6095. CATCH_ENFORCE(newMargin >= 0,
  6096. "Invalid Approx::margin: " << newMargin << '.'
  6097. << " Approx::Margin has to be non-negative.");
  6098. m_margin = newMargin;
  6099. }
  6100. void Approx::setEpsilon(double newEpsilon) {
  6101. CATCH_ENFORCE(newEpsilon >= 0 && newEpsilon <= 1.0,
  6102. "Invalid Approx::epsilon: " << newEpsilon << '.'
  6103. << " Approx::epsilon has to be in [0, 1]");
  6104. m_epsilon = newEpsilon;
  6105. }
  6106. } // end namespace Detail
  6107. namespace literals {
  6108. Detail::Approx operator "" _a(long double val) {
  6109. return Detail::Approx(val);
  6110. }
  6111. Detail::Approx operator "" _a(unsigned long long val) {
  6112. return Detail::Approx(val);
  6113. }
  6114. } // end namespace literals
  6115. std::string StringMaker<Catch::Detail::Approx>::convert(Catch::Detail::Approx const& value) {
  6116. return value.toString();
  6117. }
  6118. } // end namespace Catch
  6119. // end catch_approx.cpp
  6120. // start catch_assertionhandler.cpp
  6121. // start catch_debugger.h
  6122. namespace Catch {
  6123. bool isDebuggerActive();
  6124. }
  6125. #ifdef CATCH_PLATFORM_MAC
  6126. #define CATCH_TRAP() __asm__("int $3\n" : : ) /* NOLINT */
  6127. #elif defined(CATCH_PLATFORM_LINUX)
  6128. // If we can use inline assembler, do it because this allows us to break
  6129. // directly at the location of the failing check instead of breaking inside
  6130. // raise() called from it, i.e. one stack frame below.
  6131. #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64))
  6132. #define CATCH_TRAP() asm volatile ("int $3") /* NOLINT */
  6133. #else // Fall back to the generic way.
  6134. #include <signal.h>
  6135. #define CATCH_TRAP() raise(SIGTRAP)
  6136. #endif
  6137. #elif defined(_MSC_VER)
  6138. #define CATCH_TRAP() __debugbreak()
  6139. #elif defined(__MINGW32__)
  6140. extern "C" __declspec(dllimport) void __stdcall DebugBreak();
  6141. #define CATCH_TRAP() DebugBreak()
  6142. #endif
  6143. #ifdef CATCH_TRAP
  6144. #define CATCH_BREAK_INTO_DEBUGGER() []{ if( Catch::isDebuggerActive() ) { CATCH_TRAP(); } }()
  6145. #else
  6146. #define CATCH_BREAK_INTO_DEBUGGER() []{}()
  6147. #endif
  6148. // end catch_debugger.h
  6149. // start catch_run_context.h
  6150. // start catch_fatal_condition.h
  6151. // start catch_windows_h_proxy.h
  6152. #if defined(CATCH_PLATFORM_WINDOWS)
  6153. #if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX)
  6154. # define CATCH_DEFINED_NOMINMAX
  6155. # define NOMINMAX
  6156. #endif
  6157. #if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN)
  6158. # define CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  6159. # define WIN32_LEAN_AND_MEAN
  6160. #endif
  6161. #ifdef __AFXDLL
  6162. #include <AfxWin.h>
  6163. #else
  6164. #include <windows.h>
  6165. #endif
  6166. #ifdef CATCH_DEFINED_NOMINMAX
  6167. # undef NOMINMAX
  6168. #endif
  6169. #ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  6170. # undef WIN32_LEAN_AND_MEAN
  6171. #endif
  6172. #endif // defined(CATCH_PLATFORM_WINDOWS)
  6173. // end catch_windows_h_proxy.h
  6174. #if defined( CATCH_CONFIG_WINDOWS_SEH )
  6175. namespace Catch {
  6176. struct FatalConditionHandler {
  6177. static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo);
  6178. FatalConditionHandler();
  6179. static void reset();
  6180. ~FatalConditionHandler();
  6181. private:
  6182. static bool isSet;
  6183. static ULONG guaranteeSize;
  6184. static PVOID exceptionHandlerHandle;
  6185. };
  6186. } // namespace Catch
  6187. #elif defined ( CATCH_CONFIG_POSIX_SIGNALS )
  6188. #include <signal.h>
  6189. namespace Catch {
  6190. struct FatalConditionHandler {
  6191. static bool isSet;
  6192. static struct sigaction oldSigActions[];
  6193. static stack_t oldSigStack;
  6194. static char altStackMem[];
  6195. static void handleSignal( int sig );
  6196. FatalConditionHandler();
  6197. ~FatalConditionHandler();
  6198. static void reset();
  6199. };
  6200. } // namespace Catch
  6201. #else
  6202. namespace Catch {
  6203. struct FatalConditionHandler {
  6204. void reset();
  6205. };
  6206. }
  6207. #endif
  6208. // end catch_fatal_condition.h
  6209. #include <string>
  6210. namespace Catch {
  6211. struct IMutableContext;
  6212. ///////////////////////////////////////////////////////////////////////////
  6213. class RunContext : public IResultCapture, public IRunner {
  6214. public:
  6215. RunContext( RunContext const& ) = delete;
  6216. RunContext& operator =( RunContext const& ) = delete;
  6217. explicit RunContext( IConfigPtr const& _config, IStreamingReporterPtr&& reporter );
  6218. ~RunContext() override;
  6219. void testGroupStarting( std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount );
  6220. void testGroupEnded( std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount );
  6221. Totals runTest(TestCase const& testCase);
  6222. IConfigPtr config() const;
  6223. IStreamingReporter& reporter() const;
  6224. public: // IResultCapture
  6225. // Assertion handlers
  6226. void handleExpr
  6227. ( AssertionInfo const& info,
  6228. ITransientExpression const& expr,
  6229. AssertionReaction& reaction ) override;
  6230. void handleMessage
  6231. ( AssertionInfo const& info,
  6232. ResultWas::OfType resultType,
  6233. StringRef const& message,
  6234. AssertionReaction& reaction ) override;
  6235. void handleUnexpectedExceptionNotThrown
  6236. ( AssertionInfo const& info,
  6237. AssertionReaction& reaction ) override;
  6238. void handleUnexpectedInflightException
  6239. ( AssertionInfo const& info,
  6240. std::string const& message,
  6241. AssertionReaction& reaction ) override;
  6242. void handleIncomplete
  6243. ( AssertionInfo const& info ) override;
  6244. void handleNonExpr
  6245. ( AssertionInfo const &info,
  6246. ResultWas::OfType resultType,
  6247. AssertionReaction &reaction ) override;
  6248. bool sectionStarted( SectionInfo const& sectionInfo, Counts& assertions ) override;
  6249. void sectionEnded( SectionEndInfo const& endInfo ) override;
  6250. void sectionEndedEarly( SectionEndInfo const& endInfo ) override;
  6251. auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& override;
  6252. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  6253. void benchmarkPreparing( std::string const& name ) override;
  6254. void benchmarkStarting( BenchmarkInfo const& info ) override;
  6255. void benchmarkEnded( BenchmarkStats<> const& stats ) override;
  6256. void benchmarkFailed( std::string const& error ) override;
  6257. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  6258. void pushScopedMessage( MessageInfo const& message ) override;
  6259. void popScopedMessage( MessageInfo const& message ) override;
  6260. void emplaceUnscopedMessage( MessageBuilder const& builder ) override;
  6261. std::string getCurrentTestName() const override;
  6262. const AssertionResult* getLastResult() const override;
  6263. void exceptionEarlyReported() override;
  6264. void handleFatalErrorCondition( StringRef message ) override;
  6265. bool lastAssertionPassed() override;
  6266. void assertionPassed() override;
  6267. public:
  6268. // !TBD We need to do this another way!
  6269. bool aborting() const final;
  6270. private:
  6271. void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr );
  6272. void invokeActiveTestCase();
  6273. void resetAssertionInfo();
  6274. bool testForMissingAssertions( Counts& assertions );
  6275. void assertionEnded( AssertionResult const& result );
  6276. void reportExpr
  6277. ( AssertionInfo const &info,
  6278. ResultWas::OfType resultType,
  6279. ITransientExpression const *expr,
  6280. bool negated );
  6281. void populateReaction( AssertionReaction& reaction );
  6282. private:
  6283. void handleUnfinishedSections();
  6284. TestRunInfo m_runInfo;
  6285. IMutableContext& m_context;
  6286. TestCase const* m_activeTestCase = nullptr;
  6287. ITracker* m_testCaseTracker = nullptr;
  6288. Option<AssertionResult> m_lastResult;
  6289. IConfigPtr m_config;
  6290. Totals m_totals;
  6291. IStreamingReporterPtr m_reporter;
  6292. std::vector<MessageInfo> m_messages;
  6293. std::vector<ScopedMessage> m_messageScopes; /* Keeps owners of so-called unscoped messages. */
  6294. AssertionInfo m_lastAssertionInfo;
  6295. std::vector<SectionEndInfo> m_unfinishedSections;
  6296. std::vector<ITracker*> m_activeSections;
  6297. TrackerContext m_trackerContext;
  6298. bool m_lastAssertionPassed = false;
  6299. bool m_shouldReportUnexpected = true;
  6300. bool m_includeSuccessfulResults;
  6301. };
  6302. } // end namespace Catch
  6303. // end catch_run_context.h
  6304. namespace Catch {
  6305. namespace {
  6306. auto operator <<( std::ostream& os, ITransientExpression const& expr ) -> std::ostream& {
  6307. expr.streamReconstructedExpression( os );
  6308. return os;
  6309. }
  6310. }
  6311. LazyExpression::LazyExpression( bool isNegated )
  6312. : m_isNegated( isNegated )
  6313. {}
  6314. LazyExpression::LazyExpression( LazyExpression const& other ) : m_isNegated( other.m_isNegated ) {}
  6315. LazyExpression::operator bool() const {
  6316. return m_transientExpression != nullptr;
  6317. }
  6318. auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream& {
  6319. if( lazyExpr.m_isNegated )
  6320. os << "!";
  6321. if( lazyExpr ) {
  6322. if( lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression() )
  6323. os << "(" << *lazyExpr.m_transientExpression << ")";
  6324. else
  6325. os << *lazyExpr.m_transientExpression;
  6326. }
  6327. else {
  6328. os << "{** error - unchecked empty expression requested **}";
  6329. }
  6330. return os;
  6331. }
  6332. AssertionHandler::AssertionHandler
  6333. ( StringRef const& macroName,
  6334. SourceLineInfo const& lineInfo,
  6335. StringRef capturedExpression,
  6336. ResultDisposition::Flags resultDisposition )
  6337. : m_assertionInfo{ macroName, lineInfo, capturedExpression, resultDisposition },
  6338. m_resultCapture( getResultCapture() )
  6339. {}
  6340. void AssertionHandler::handleExpr( ITransientExpression const& expr ) {
  6341. m_resultCapture.handleExpr( m_assertionInfo, expr, m_reaction );
  6342. }
  6343. void AssertionHandler::handleMessage(ResultWas::OfType resultType, StringRef const& message) {
  6344. m_resultCapture.handleMessage( m_assertionInfo, resultType, message, m_reaction );
  6345. }
  6346. auto AssertionHandler::allowThrows() const -> bool {
  6347. return getCurrentContext().getConfig()->allowThrows();
  6348. }
  6349. void AssertionHandler::complete() {
  6350. setCompleted();
  6351. if( m_reaction.shouldDebugBreak ) {
  6352. // If you find your debugger stopping you here then go one level up on the
  6353. // call-stack for the code that caused it (typically a failed assertion)
  6354. // (To go back to the test and change execution, jump over the throw, next)
  6355. CATCH_BREAK_INTO_DEBUGGER();
  6356. }
  6357. if (m_reaction.shouldThrow) {
  6358. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  6359. throw Catch::TestFailureException();
  6360. #else
  6361. CATCH_ERROR( "Test failure requires aborting test!" );
  6362. #endif
  6363. }
  6364. }
  6365. void AssertionHandler::setCompleted() {
  6366. m_completed = true;
  6367. }
  6368. void AssertionHandler::handleUnexpectedInflightException() {
  6369. m_resultCapture.handleUnexpectedInflightException( m_assertionInfo, Catch::translateActiveException(), m_reaction );
  6370. }
  6371. void AssertionHandler::handleExceptionThrownAsExpected() {
  6372. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  6373. }
  6374. void AssertionHandler::handleExceptionNotThrownAsExpected() {
  6375. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  6376. }
  6377. void AssertionHandler::handleUnexpectedExceptionNotThrown() {
  6378. m_resultCapture.handleUnexpectedExceptionNotThrown( m_assertionInfo, m_reaction );
  6379. }
  6380. void AssertionHandler::handleThrowingCallSkipped() {
  6381. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  6382. }
  6383. // This is the overload that takes a string and infers the Equals matcher from it
  6384. // The more general overload, that takes any string matcher, is in catch_capture_matchers.cpp
  6385. void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString ) {
  6386. handleExceptionMatchExpr( handler, Matchers::Equals( str ), matcherString );
  6387. }
  6388. } // namespace Catch
  6389. // end catch_assertionhandler.cpp
  6390. // start catch_assertionresult.cpp
  6391. namespace Catch {
  6392. AssertionResultData::AssertionResultData(ResultWas::OfType _resultType, LazyExpression const & _lazyExpression):
  6393. lazyExpression(_lazyExpression),
  6394. resultType(_resultType) {}
  6395. std::string AssertionResultData::reconstructExpression() const {
  6396. if( reconstructedExpression.empty() ) {
  6397. if( lazyExpression ) {
  6398. ReusableStringStream rss;
  6399. rss << lazyExpression;
  6400. reconstructedExpression = rss.str();
  6401. }
  6402. }
  6403. return reconstructedExpression;
  6404. }
  6405. AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data )
  6406. : m_info( info ),
  6407. m_resultData( data )
  6408. {}
  6409. // Result was a success
  6410. bool AssertionResult::succeeded() const {
  6411. return Catch::isOk( m_resultData.resultType );
  6412. }
  6413. // Result was a success, or failure is suppressed
  6414. bool AssertionResult::isOk() const {
  6415. return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition );
  6416. }
  6417. ResultWas::OfType AssertionResult::getResultType() const {
  6418. return m_resultData.resultType;
  6419. }
  6420. bool AssertionResult::hasExpression() const {
  6421. return m_info.capturedExpression[0] != 0;
  6422. }
  6423. bool AssertionResult::hasMessage() const {
  6424. return !m_resultData.message.empty();
  6425. }
  6426. std::string AssertionResult::getExpression() const {
  6427. if( isFalseTest( m_info.resultDisposition ) )
  6428. return "!(" + m_info.capturedExpression + ")";
  6429. else
  6430. return m_info.capturedExpression;
  6431. }
  6432. std::string AssertionResult::getExpressionInMacro() const {
  6433. std::string expr;
  6434. if( m_info.macroName[0] == 0 )
  6435. expr = m_info.capturedExpression;
  6436. else {
  6437. expr.reserve( m_info.macroName.size() + m_info.capturedExpression.size() + 4 );
  6438. expr += m_info.macroName;
  6439. expr += "( ";
  6440. expr += m_info.capturedExpression;
  6441. expr += " )";
  6442. }
  6443. return expr;
  6444. }
  6445. bool AssertionResult::hasExpandedExpression() const {
  6446. return hasExpression() && getExpandedExpression() != getExpression();
  6447. }
  6448. std::string AssertionResult::getExpandedExpression() const {
  6449. std::string expr = m_resultData.reconstructExpression();
  6450. return expr.empty()
  6451. ? getExpression()
  6452. : expr;
  6453. }
  6454. std::string AssertionResult::getMessage() const {
  6455. return m_resultData.message;
  6456. }
  6457. SourceLineInfo AssertionResult::getSourceInfo() const {
  6458. return m_info.lineInfo;
  6459. }
  6460. StringRef AssertionResult::getTestMacroName() const {
  6461. return m_info.macroName;
  6462. }
  6463. } // end namespace Catch
  6464. // end catch_assertionresult.cpp
  6465. // start catch_capture_matchers.cpp
  6466. namespace Catch {
  6467. using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
  6468. // This is the general overload that takes a any string matcher
  6469. // There is another overload, in catch_assertionhandler.h/.cpp, that only takes a string and infers
  6470. // the Equals matcher (so the header does not mention matchers)
  6471. void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString ) {
  6472. std::string exceptionMessage = Catch::translateActiveException();
  6473. MatchExpr<std::string, StringMatcher const&> expr( exceptionMessage, matcher, matcherString );
  6474. handler.handleExpr( expr );
  6475. }
  6476. } // namespace Catch
  6477. // end catch_capture_matchers.cpp
  6478. // start catch_commandline.cpp
  6479. // start catch_commandline.h
  6480. // start catch_clara.h
  6481. // Use Catch's value for console width (store Clara's off to the side, if present)
  6482. #ifdef CLARA_CONFIG_CONSOLE_WIDTH
  6483. #define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  6484. #undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  6485. #endif
  6486. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH-1
  6487. #ifdef __clang__
  6488. #pragma clang diagnostic push
  6489. #pragma clang diagnostic ignored "-Wweak-vtables"
  6490. #pragma clang diagnostic ignored "-Wexit-time-destructors"
  6491. #pragma clang diagnostic ignored "-Wshadow"
  6492. #endif
  6493. // start clara.hpp
  6494. // Copyright 2017 Two Blue Cubes Ltd. All rights reserved.
  6495. //
  6496. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  6497. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6498. //
  6499. // See https://github.com/philsquared/Clara for more details
  6500. // Clara v1.1.5
  6501. #ifndef CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  6502. #define CATCH_CLARA_CONFIG_CONSOLE_WIDTH 80
  6503. #endif
  6504. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  6505. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  6506. #endif
  6507. #ifndef CLARA_CONFIG_OPTIONAL_TYPE
  6508. #ifdef __has_include
  6509. #if __has_include(<optional>) && __cplusplus >= 201703L
  6510. #include <optional>
  6511. #define CLARA_CONFIG_OPTIONAL_TYPE std::optional
  6512. #endif
  6513. #endif
  6514. #endif
  6515. // ----------- #included from clara_textflow.hpp -----------
  6516. // TextFlowCpp
  6517. //
  6518. // A single-header library for wrapping and laying out basic text, by Phil Nash
  6519. //
  6520. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  6521. // file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6522. //
  6523. // This project is hosted at https://github.com/philsquared/textflowcpp
  6524. #include <cassert>
  6525. #include <ostream>
  6526. #include <sstream>
  6527. #include <vector>
  6528. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  6529. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80
  6530. #endif
  6531. namespace Catch {
  6532. namespace clara {
  6533. namespace TextFlow {
  6534. inline auto isWhitespace(char c) -> bool {
  6535. static std::string chars = " \t\n\r";
  6536. return chars.find(c) != std::string::npos;
  6537. }
  6538. inline auto isBreakableBefore(char c) -> bool {
  6539. static std::string chars = "[({<|";
  6540. return chars.find(c) != std::string::npos;
  6541. }
  6542. inline auto isBreakableAfter(char c) -> bool {
  6543. static std::string chars = "])}>.,:;*+-=&/\\";
  6544. return chars.find(c) != std::string::npos;
  6545. }
  6546. class Columns;
  6547. class Column {
  6548. std::vector<std::string> m_strings;
  6549. size_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH;
  6550. size_t m_indent = 0;
  6551. size_t m_initialIndent = std::string::npos;
  6552. public:
  6553. class iterator {
  6554. friend Column;
  6555. Column const& m_column;
  6556. size_t m_stringIndex = 0;
  6557. size_t m_pos = 0;
  6558. size_t m_len = 0;
  6559. size_t m_end = 0;
  6560. bool m_suffix = false;
  6561. iterator(Column const& column, size_t stringIndex)
  6562. : m_column(column),
  6563. m_stringIndex(stringIndex) {}
  6564. auto line() const -> std::string const& { return m_column.m_strings[m_stringIndex]; }
  6565. auto isBoundary(size_t at) const -> bool {
  6566. assert(at > 0);
  6567. assert(at <= line().size());
  6568. return at == line().size() ||
  6569. (isWhitespace(line()[at]) && !isWhitespace(line()[at - 1])) ||
  6570. isBreakableBefore(line()[at]) ||
  6571. isBreakableAfter(line()[at - 1]);
  6572. }
  6573. void calcLength() {
  6574. assert(m_stringIndex < m_column.m_strings.size());
  6575. m_suffix = false;
  6576. auto width = m_column.m_width - indent();
  6577. m_end = m_pos;
  6578. if (line()[m_pos] == '\n') {
  6579. ++m_end;
  6580. }
  6581. while (m_end < line().size() && line()[m_end] != '\n')
  6582. ++m_end;
  6583. if (m_end < m_pos + width) {
  6584. m_len = m_end - m_pos;
  6585. } else {
  6586. size_t len = width;
  6587. while (len > 0 && !isBoundary(m_pos + len))
  6588. --len;
  6589. while (len > 0 && isWhitespace(line()[m_pos + len - 1]))
  6590. --len;
  6591. if (len > 0) {
  6592. m_len = len;
  6593. } else {
  6594. m_suffix = true;
  6595. m_len = width - 1;
  6596. }
  6597. }
  6598. }
  6599. auto indent() const -> size_t {
  6600. auto initial = m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos;
  6601. return initial == std::string::npos ? m_column.m_indent : initial;
  6602. }
  6603. auto addIndentAndSuffix(std::string const &plain) const -> std::string {
  6604. return std::string(indent(), ' ') + (m_suffix ? plain + "-" : plain);
  6605. }
  6606. public:
  6607. using difference_type = std::ptrdiff_t;
  6608. using value_type = std::string;
  6609. using pointer = value_type * ;
  6610. using reference = value_type & ;
  6611. using iterator_category = std::forward_iterator_tag;
  6612. explicit iterator(Column const& column) : m_column(column) {
  6613. assert(m_column.m_width > m_column.m_indent);
  6614. assert(m_column.m_initialIndent == std::string::npos || m_column.m_width > m_column.m_initialIndent);
  6615. calcLength();
  6616. if (m_len == 0)
  6617. m_stringIndex++; // Empty string
  6618. }
  6619. auto operator *() const -> std::string {
  6620. assert(m_stringIndex < m_column.m_strings.size());
  6621. assert(m_pos <= m_end);
  6622. return addIndentAndSuffix(line().substr(m_pos, m_len));
  6623. }
  6624. auto operator ++() -> iterator& {
  6625. m_pos += m_len;
  6626. if (m_pos < line().size() && line()[m_pos] == '\n')
  6627. m_pos += 1;
  6628. else
  6629. while (m_pos < line().size() && isWhitespace(line()[m_pos]))
  6630. ++m_pos;
  6631. if (m_pos == line().size()) {
  6632. m_pos = 0;
  6633. ++m_stringIndex;
  6634. }
  6635. if (m_stringIndex < m_column.m_strings.size())
  6636. calcLength();
  6637. return *this;
  6638. }
  6639. auto operator ++(int) -> iterator {
  6640. iterator prev(*this);
  6641. operator++();
  6642. return prev;
  6643. }
  6644. auto operator ==(iterator const& other) const -> bool {
  6645. return
  6646. m_pos == other.m_pos &&
  6647. m_stringIndex == other.m_stringIndex &&
  6648. &m_column == &other.m_column;
  6649. }
  6650. auto operator !=(iterator const& other) const -> bool {
  6651. return !operator==(other);
  6652. }
  6653. };
  6654. using const_iterator = iterator;
  6655. explicit Column(std::string const& text) { m_strings.push_back(text); }
  6656. auto width(size_t newWidth) -> Column& {
  6657. assert(newWidth > 0);
  6658. m_width = newWidth;
  6659. return *this;
  6660. }
  6661. auto indent(size_t newIndent) -> Column& {
  6662. m_indent = newIndent;
  6663. return *this;
  6664. }
  6665. auto initialIndent(size_t newIndent) -> Column& {
  6666. m_initialIndent = newIndent;
  6667. return *this;
  6668. }
  6669. auto width() const -> size_t { return m_width; }
  6670. auto begin() const -> iterator { return iterator(*this); }
  6671. auto end() const -> iterator { return { *this, m_strings.size() }; }
  6672. inline friend std::ostream& operator << (std::ostream& os, Column const& col) {
  6673. bool first = true;
  6674. for (auto line : col) {
  6675. if (first)
  6676. first = false;
  6677. else
  6678. os << "\n";
  6679. os << line;
  6680. }
  6681. return os;
  6682. }
  6683. auto operator + (Column const& other)->Columns;
  6684. auto toString() const -> std::string {
  6685. std::ostringstream oss;
  6686. oss << *this;
  6687. return oss.str();
  6688. }
  6689. };
  6690. class Spacer : public Column {
  6691. public:
  6692. explicit Spacer(size_t spaceWidth) : Column("") {
  6693. width(spaceWidth);
  6694. }
  6695. };
  6696. class Columns {
  6697. std::vector<Column> m_columns;
  6698. public:
  6699. class iterator {
  6700. friend Columns;
  6701. struct EndTag {};
  6702. std::vector<Column> const& m_columns;
  6703. std::vector<Column::iterator> m_iterators;
  6704. size_t m_activeIterators;
  6705. iterator(Columns const& columns, EndTag)
  6706. : m_columns(columns.m_columns),
  6707. m_activeIterators(0) {
  6708. m_iterators.reserve(m_columns.size());
  6709. for (auto const& col : m_columns)
  6710. m_iterators.push_back(col.end());
  6711. }
  6712. public:
  6713. using difference_type = std::ptrdiff_t;
  6714. using value_type = std::string;
  6715. using pointer = value_type * ;
  6716. using reference = value_type & ;
  6717. using iterator_category = std::forward_iterator_tag;
  6718. explicit iterator(Columns const& columns)
  6719. : m_columns(columns.m_columns),
  6720. m_activeIterators(m_columns.size()) {
  6721. m_iterators.reserve(m_columns.size());
  6722. for (auto const& col : m_columns)
  6723. m_iterators.push_back(col.begin());
  6724. }
  6725. auto operator ==(iterator const& other) const -> bool {
  6726. return m_iterators == other.m_iterators;
  6727. }
  6728. auto operator !=(iterator const& other) const -> bool {
  6729. return m_iterators != other.m_iterators;
  6730. }
  6731. auto operator *() const -> std::string {
  6732. std::string row, padding;
  6733. for (size_t i = 0; i < m_columns.size(); ++i) {
  6734. auto width = m_columns[i].width();
  6735. if (m_iterators[i] != m_columns[i].end()) {
  6736. std::string col = *m_iterators[i];
  6737. row += padding + col;
  6738. if (col.size() < width)
  6739. padding = std::string(width - col.size(), ' ');
  6740. else
  6741. padding = "";
  6742. } else {
  6743. padding += std::string(width, ' ');
  6744. }
  6745. }
  6746. return row;
  6747. }
  6748. auto operator ++() -> iterator& {
  6749. for (size_t i = 0; i < m_columns.size(); ++i) {
  6750. if (m_iterators[i] != m_columns[i].end())
  6751. ++m_iterators[i];
  6752. }
  6753. return *this;
  6754. }
  6755. auto operator ++(int) -> iterator {
  6756. iterator prev(*this);
  6757. operator++();
  6758. return prev;
  6759. }
  6760. };
  6761. using const_iterator = iterator;
  6762. auto begin() const -> iterator { return iterator(*this); }
  6763. auto end() const -> iterator { return { *this, iterator::EndTag() }; }
  6764. auto operator += (Column const& col) -> Columns& {
  6765. m_columns.push_back(col);
  6766. return *this;
  6767. }
  6768. auto operator + (Column const& col) -> Columns {
  6769. Columns combined = *this;
  6770. combined += col;
  6771. return combined;
  6772. }
  6773. inline friend std::ostream& operator << (std::ostream& os, Columns const& cols) {
  6774. bool first = true;
  6775. for (auto line : cols) {
  6776. if (first)
  6777. first = false;
  6778. else
  6779. os << "\n";
  6780. os << line;
  6781. }
  6782. return os;
  6783. }
  6784. auto toString() const -> std::string {
  6785. std::ostringstream oss;
  6786. oss << *this;
  6787. return oss.str();
  6788. }
  6789. };
  6790. inline auto Column::operator + (Column const& other) -> Columns {
  6791. Columns cols;
  6792. cols += *this;
  6793. cols += other;
  6794. return cols;
  6795. }
  6796. }
  6797. }
  6798. }
  6799. // ----------- end of #include from clara_textflow.hpp -----------
  6800. // ........... back in clara.hpp
  6801. #include <cctype>
  6802. #include <string>
  6803. #include <memory>
  6804. #include <set>
  6805. #include <algorithm>
  6806. #if !defined(CATCH_PLATFORM_WINDOWS) && ( defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) )
  6807. #define CATCH_PLATFORM_WINDOWS
  6808. #endif
  6809. namespace Catch { namespace clara {
  6810. namespace detail {
  6811. // Traits for extracting arg and return type of lambdas (for single argument lambdas)
  6812. template<typename L>
  6813. struct UnaryLambdaTraits : UnaryLambdaTraits<decltype( &L::operator() )> {};
  6814. template<typename ClassT, typename ReturnT, typename... Args>
  6815. struct UnaryLambdaTraits<ReturnT( ClassT::* )( Args... ) const> {
  6816. static const bool isValid = false;
  6817. };
  6818. template<typename ClassT, typename ReturnT, typename ArgT>
  6819. struct UnaryLambdaTraits<ReturnT( ClassT::* )( ArgT ) const> {
  6820. static const bool isValid = true;
  6821. using ArgType = typename std::remove_const<typename std::remove_reference<ArgT>::type>::type;
  6822. using ReturnType = ReturnT;
  6823. };
  6824. class TokenStream;
  6825. // Transport for raw args (copied from main args, or supplied via init list for testing)
  6826. class Args {
  6827. friend TokenStream;
  6828. std::string m_exeName;
  6829. std::vector<std::string> m_args;
  6830. public:
  6831. Args( int argc, char const* const* argv )
  6832. : m_exeName(argv[0]),
  6833. m_args(argv + 1, argv + argc) {}
  6834. Args( std::initializer_list<std::string> args )
  6835. : m_exeName( *args.begin() ),
  6836. m_args( args.begin()+1, args.end() )
  6837. {}
  6838. auto exeName() const -> std::string {
  6839. return m_exeName;
  6840. }
  6841. };
  6842. // Wraps a token coming from a token stream. These may not directly correspond to strings as a single string
  6843. // may encode an option + its argument if the : or = form is used
  6844. enum class TokenType {
  6845. Option, Argument
  6846. };
  6847. struct Token {
  6848. TokenType type;
  6849. std::string token;
  6850. };
  6851. inline auto isOptPrefix( char c ) -> bool {
  6852. return c == '-'
  6853. #ifdef CATCH_PLATFORM_WINDOWS
  6854. || c == '/'
  6855. #endif
  6856. ;
  6857. }
  6858. // Abstracts iterators into args as a stream of tokens, with option arguments uniformly handled
  6859. class TokenStream {
  6860. using Iterator = std::vector<std::string>::const_iterator;
  6861. Iterator it;
  6862. Iterator itEnd;
  6863. std::vector<Token> m_tokenBuffer;
  6864. void loadBuffer() {
  6865. m_tokenBuffer.resize( 0 );
  6866. // Skip any empty strings
  6867. while( it != itEnd && it->empty() )
  6868. ++it;
  6869. if( it != itEnd ) {
  6870. auto const &next = *it;
  6871. if( isOptPrefix( next[0] ) ) {
  6872. auto delimiterPos = next.find_first_of( " :=" );
  6873. if( delimiterPos != std::string::npos ) {
  6874. m_tokenBuffer.push_back( { TokenType::Option, next.substr( 0, delimiterPos ) } );
  6875. m_tokenBuffer.push_back( { TokenType::Argument, next.substr( delimiterPos + 1 ) } );
  6876. } else {
  6877. if( next[1] != '-' && next.size() > 2 ) {
  6878. std::string opt = "- ";
  6879. for( size_t i = 1; i < next.size(); ++i ) {
  6880. opt[1] = next[i];
  6881. m_tokenBuffer.push_back( { TokenType::Option, opt } );
  6882. }
  6883. } else {
  6884. m_tokenBuffer.push_back( { TokenType::Option, next } );
  6885. }
  6886. }
  6887. } else {
  6888. m_tokenBuffer.push_back( { TokenType::Argument, next } );
  6889. }
  6890. }
  6891. }
  6892. public:
  6893. explicit TokenStream( Args const &args ) : TokenStream( args.m_args.begin(), args.m_args.end() ) {}
  6894. TokenStream( Iterator it, Iterator itEnd ) : it( it ), itEnd( itEnd ) {
  6895. loadBuffer();
  6896. }
  6897. explicit operator bool() const {
  6898. return !m_tokenBuffer.empty() || it != itEnd;
  6899. }
  6900. auto count() const -> size_t { return m_tokenBuffer.size() + (itEnd - it); }
  6901. auto operator*() const -> Token {
  6902. assert( !m_tokenBuffer.empty() );
  6903. return m_tokenBuffer.front();
  6904. }
  6905. auto operator->() const -> Token const * {
  6906. assert( !m_tokenBuffer.empty() );
  6907. return &m_tokenBuffer.front();
  6908. }
  6909. auto operator++() -> TokenStream & {
  6910. if( m_tokenBuffer.size() >= 2 ) {
  6911. m_tokenBuffer.erase( m_tokenBuffer.begin() );
  6912. } else {
  6913. if( it != itEnd )
  6914. ++it;
  6915. loadBuffer();
  6916. }
  6917. return *this;
  6918. }
  6919. };
  6920. class ResultBase {
  6921. public:
  6922. enum Type {
  6923. Ok, LogicError, RuntimeError
  6924. };
  6925. protected:
  6926. ResultBase( Type type ) : m_type( type ) {}
  6927. virtual ~ResultBase() = default;
  6928. virtual void enforceOk() const = 0;
  6929. Type m_type;
  6930. };
  6931. template<typename T>
  6932. class ResultValueBase : public ResultBase {
  6933. public:
  6934. auto value() const -> T const & {
  6935. enforceOk();
  6936. return m_value;
  6937. }
  6938. protected:
  6939. ResultValueBase( Type type ) : ResultBase( type ) {}
  6940. ResultValueBase( ResultValueBase const &other ) : ResultBase( other ) {
  6941. if( m_type == ResultBase::Ok )
  6942. new( &m_value ) T( other.m_value );
  6943. }
  6944. ResultValueBase( Type, T const &value ) : ResultBase( Ok ) {
  6945. new( &m_value ) T( value );
  6946. }
  6947. auto operator=( ResultValueBase const &other ) -> ResultValueBase & {
  6948. if( m_type == ResultBase::Ok )
  6949. m_value.~T();
  6950. ResultBase::operator=(other);
  6951. if( m_type == ResultBase::Ok )
  6952. new( &m_value ) T( other.m_value );
  6953. return *this;
  6954. }
  6955. ~ResultValueBase() override {
  6956. if( m_type == Ok )
  6957. m_value.~T();
  6958. }
  6959. union {
  6960. T m_value;
  6961. };
  6962. };
  6963. template<>
  6964. class ResultValueBase<void> : public ResultBase {
  6965. protected:
  6966. using ResultBase::ResultBase;
  6967. };
  6968. template<typename T = void>
  6969. class BasicResult : public ResultValueBase<T> {
  6970. public:
  6971. template<typename U>
  6972. explicit BasicResult( BasicResult<U> const &other )
  6973. : ResultValueBase<T>( other.type() ),
  6974. m_errorMessage( other.errorMessage() )
  6975. {
  6976. assert( type() != ResultBase::Ok );
  6977. }
  6978. template<typename U>
  6979. static auto ok( U const &value ) -> BasicResult { return { ResultBase::Ok, value }; }
  6980. static auto ok() -> BasicResult { return { ResultBase::Ok }; }
  6981. static auto logicError( std::string const &message ) -> BasicResult { return { ResultBase::LogicError, message }; }
  6982. static auto runtimeError( std::string const &message ) -> BasicResult { return { ResultBase::RuntimeError, message }; }
  6983. explicit operator bool() const { return m_type == ResultBase::Ok; }
  6984. auto type() const -> ResultBase::Type { return m_type; }
  6985. auto errorMessage() const -> std::string { return m_errorMessage; }
  6986. protected:
  6987. void enforceOk() const override {
  6988. // Errors shouldn't reach this point, but if they do
  6989. // the actual error message will be in m_errorMessage
  6990. assert( m_type != ResultBase::LogicError );
  6991. assert( m_type != ResultBase::RuntimeError );
  6992. if( m_type != ResultBase::Ok )
  6993. std::abort();
  6994. }
  6995. std::string m_errorMessage; // Only populated if resultType is an error
  6996. BasicResult( ResultBase::Type type, std::string const &message )
  6997. : ResultValueBase<T>(type),
  6998. m_errorMessage(message)
  6999. {
  7000. assert( m_type != ResultBase::Ok );
  7001. }
  7002. using ResultValueBase<T>::ResultValueBase;
  7003. using ResultBase::m_type;
  7004. };
  7005. enum class ParseResultType {
  7006. Matched, NoMatch, ShortCircuitAll, ShortCircuitSame
  7007. };
  7008. class ParseState {
  7009. public:
  7010. ParseState( ParseResultType type, TokenStream const &remainingTokens )
  7011. : m_type(type),
  7012. m_remainingTokens( remainingTokens )
  7013. {}
  7014. auto type() const -> ParseResultType { return m_type; }
  7015. auto remainingTokens() const -> TokenStream { return m_remainingTokens; }
  7016. private:
  7017. ParseResultType m_type;
  7018. TokenStream m_remainingTokens;
  7019. };
  7020. using Result = BasicResult<void>;
  7021. using ParserResult = BasicResult<ParseResultType>;
  7022. using InternalParseResult = BasicResult<ParseState>;
  7023. struct HelpColumns {
  7024. std::string left;
  7025. std::string right;
  7026. };
  7027. template<typename T>
  7028. inline auto convertInto( std::string const &source, T& target ) -> ParserResult {
  7029. std::stringstream ss;
  7030. ss << source;
  7031. ss >> target;
  7032. if( ss.fail() )
  7033. return ParserResult::runtimeError( "Unable to convert '" + source + "' to destination type" );
  7034. else
  7035. return ParserResult::ok( ParseResultType::Matched );
  7036. }
  7037. inline auto convertInto( std::string const &source, std::string& target ) -> ParserResult {
  7038. target = source;
  7039. return ParserResult::ok( ParseResultType::Matched );
  7040. }
  7041. inline auto convertInto( std::string const &source, bool &target ) -> ParserResult {
  7042. std::string srcLC = source;
  7043. std::transform( srcLC.begin(), srcLC.end(), srcLC.begin(), []( char c ) { return static_cast<char>( std::tolower(c) ); } );
  7044. if (srcLC == "y" || srcLC == "1" || srcLC == "true" || srcLC == "yes" || srcLC == "on")
  7045. target = true;
  7046. else if (srcLC == "n" || srcLC == "0" || srcLC == "false" || srcLC == "no" || srcLC == "off")
  7047. target = false;
  7048. else
  7049. return ParserResult::runtimeError( "Expected a boolean value but did not recognise: '" + source + "'" );
  7050. return ParserResult::ok( ParseResultType::Matched );
  7051. }
  7052. #ifdef CLARA_CONFIG_OPTIONAL_TYPE
  7053. template<typename T>
  7054. inline auto convertInto( std::string const &source, CLARA_CONFIG_OPTIONAL_TYPE<T>& target ) -> ParserResult {
  7055. T temp;
  7056. auto result = convertInto( source, temp );
  7057. if( result )
  7058. target = std::move(temp);
  7059. return result;
  7060. }
  7061. #endif // CLARA_CONFIG_OPTIONAL_TYPE
  7062. struct NonCopyable {
  7063. NonCopyable() = default;
  7064. NonCopyable( NonCopyable const & ) = delete;
  7065. NonCopyable( NonCopyable && ) = delete;
  7066. NonCopyable &operator=( NonCopyable const & ) = delete;
  7067. NonCopyable &operator=( NonCopyable && ) = delete;
  7068. };
  7069. struct BoundRef : NonCopyable {
  7070. virtual ~BoundRef() = default;
  7071. virtual auto isContainer() const -> bool { return false; }
  7072. virtual auto isFlag() const -> bool { return false; }
  7073. };
  7074. struct BoundValueRefBase : BoundRef {
  7075. virtual auto setValue( std::string const &arg ) -> ParserResult = 0;
  7076. };
  7077. struct BoundFlagRefBase : BoundRef {
  7078. virtual auto setFlag( bool flag ) -> ParserResult = 0;
  7079. virtual auto isFlag() const -> bool { return true; }
  7080. };
  7081. template<typename T>
  7082. struct BoundValueRef : BoundValueRefBase {
  7083. T &m_ref;
  7084. explicit BoundValueRef( T &ref ) : m_ref( ref ) {}
  7085. auto setValue( std::string const &arg ) -> ParserResult override {
  7086. return convertInto( arg, m_ref );
  7087. }
  7088. };
  7089. template<typename T>
  7090. struct BoundValueRef<std::vector<T>> : BoundValueRefBase {
  7091. std::vector<T> &m_ref;
  7092. explicit BoundValueRef( std::vector<T> &ref ) : m_ref( ref ) {}
  7093. auto isContainer() const -> bool override { return true; }
  7094. auto setValue( std::string const &arg ) -> ParserResult override {
  7095. T temp;
  7096. auto result = convertInto( arg, temp );
  7097. if( result )
  7098. m_ref.push_back( temp );
  7099. return result;
  7100. }
  7101. };
  7102. struct BoundFlagRef : BoundFlagRefBase {
  7103. bool &m_ref;
  7104. explicit BoundFlagRef( bool &ref ) : m_ref( ref ) {}
  7105. auto setFlag( bool flag ) -> ParserResult override {
  7106. m_ref = flag;
  7107. return ParserResult::ok( ParseResultType::Matched );
  7108. }
  7109. };
  7110. template<typename ReturnType>
  7111. struct LambdaInvoker {
  7112. static_assert( std::is_same<ReturnType, ParserResult>::value, "Lambda must return void or clara::ParserResult" );
  7113. template<typename L, typename ArgType>
  7114. static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
  7115. return lambda( arg );
  7116. }
  7117. };
  7118. template<>
  7119. struct LambdaInvoker<void> {
  7120. template<typename L, typename ArgType>
  7121. static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
  7122. lambda( arg );
  7123. return ParserResult::ok( ParseResultType::Matched );
  7124. }
  7125. };
  7126. template<typename ArgType, typename L>
  7127. inline auto invokeLambda( L const &lambda, std::string const &arg ) -> ParserResult {
  7128. ArgType temp{};
  7129. auto result = convertInto( arg, temp );
  7130. return !result
  7131. ? result
  7132. : LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( lambda, temp );
  7133. }
  7134. template<typename L>
  7135. struct BoundLambda : BoundValueRefBase {
  7136. L m_lambda;
  7137. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  7138. explicit BoundLambda( L const &lambda ) : m_lambda( lambda ) {}
  7139. auto setValue( std::string const &arg ) -> ParserResult override {
  7140. return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>( m_lambda, arg );
  7141. }
  7142. };
  7143. template<typename L>
  7144. struct BoundFlagLambda : BoundFlagRefBase {
  7145. L m_lambda;
  7146. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  7147. static_assert( std::is_same<typename UnaryLambdaTraits<L>::ArgType, bool>::value, "flags must be boolean" );
  7148. explicit BoundFlagLambda( L const &lambda ) : m_lambda( lambda ) {}
  7149. auto setFlag( bool flag ) -> ParserResult override {
  7150. return LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( m_lambda, flag );
  7151. }
  7152. };
  7153. enum class Optionality { Optional, Required };
  7154. struct Parser;
  7155. class ParserBase {
  7156. public:
  7157. virtual ~ParserBase() = default;
  7158. virtual auto validate() const -> Result { return Result::ok(); }
  7159. virtual auto parse( std::string const& exeName, TokenStream const &tokens) const -> InternalParseResult = 0;
  7160. virtual auto cardinality() const -> size_t { return 1; }
  7161. auto parse( Args const &args ) const -> InternalParseResult {
  7162. return parse( args.exeName(), TokenStream( args ) );
  7163. }
  7164. };
  7165. template<typename DerivedT>
  7166. class ComposableParserImpl : public ParserBase {
  7167. public:
  7168. template<typename T>
  7169. auto operator|( T const &other ) const -> Parser;
  7170. template<typename T>
  7171. auto operator+( T const &other ) const -> Parser;
  7172. };
  7173. // Common code and state for Args and Opts
  7174. template<typename DerivedT>
  7175. class ParserRefImpl : public ComposableParserImpl<DerivedT> {
  7176. protected:
  7177. Optionality m_optionality = Optionality::Optional;
  7178. std::shared_ptr<BoundRef> m_ref;
  7179. std::string m_hint;
  7180. std::string m_description;
  7181. explicit ParserRefImpl( std::shared_ptr<BoundRef> const &ref ) : m_ref( ref ) {}
  7182. public:
  7183. template<typename T>
  7184. ParserRefImpl( T &ref, std::string const &hint )
  7185. : m_ref( std::make_shared<BoundValueRef<T>>( ref ) ),
  7186. m_hint( hint )
  7187. {}
  7188. template<typename LambdaT>
  7189. ParserRefImpl( LambdaT const &ref, std::string const &hint )
  7190. : m_ref( std::make_shared<BoundLambda<LambdaT>>( ref ) ),
  7191. m_hint(hint)
  7192. {}
  7193. auto operator()( std::string const &description ) -> DerivedT & {
  7194. m_description = description;
  7195. return static_cast<DerivedT &>( *this );
  7196. }
  7197. auto optional() -> DerivedT & {
  7198. m_optionality = Optionality::Optional;
  7199. return static_cast<DerivedT &>( *this );
  7200. };
  7201. auto required() -> DerivedT & {
  7202. m_optionality = Optionality::Required;
  7203. return static_cast<DerivedT &>( *this );
  7204. };
  7205. auto isOptional() const -> bool {
  7206. return m_optionality == Optionality::Optional;
  7207. }
  7208. auto cardinality() const -> size_t override {
  7209. if( m_ref->isContainer() )
  7210. return 0;
  7211. else
  7212. return 1;
  7213. }
  7214. auto hint() const -> std::string { return m_hint; }
  7215. };
  7216. class ExeName : public ComposableParserImpl<ExeName> {
  7217. std::shared_ptr<std::string> m_name;
  7218. std::shared_ptr<BoundValueRefBase> m_ref;
  7219. template<typename LambdaT>
  7220. static auto makeRef(LambdaT const &lambda) -> std::shared_ptr<BoundValueRefBase> {
  7221. return std::make_shared<BoundLambda<LambdaT>>( lambda) ;
  7222. }
  7223. public:
  7224. ExeName() : m_name( std::make_shared<std::string>( "<executable>" ) ) {}
  7225. explicit ExeName( std::string &ref ) : ExeName() {
  7226. m_ref = std::make_shared<BoundValueRef<std::string>>( ref );
  7227. }
  7228. template<typename LambdaT>
  7229. explicit ExeName( LambdaT const& lambda ) : ExeName() {
  7230. m_ref = std::make_shared<BoundLambda<LambdaT>>( lambda );
  7231. }
  7232. // The exe name is not parsed out of the normal tokens, but is handled specially
  7233. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  7234. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
  7235. }
  7236. auto name() const -> std::string { return *m_name; }
  7237. auto set( std::string const& newName ) -> ParserResult {
  7238. auto lastSlash = newName.find_last_of( "\\/" );
  7239. auto filename = ( lastSlash == std::string::npos )
  7240. ? newName
  7241. : newName.substr( lastSlash+1 );
  7242. *m_name = filename;
  7243. if( m_ref )
  7244. return m_ref->setValue( filename );
  7245. else
  7246. return ParserResult::ok( ParseResultType::Matched );
  7247. }
  7248. };
  7249. class Arg : public ParserRefImpl<Arg> {
  7250. public:
  7251. using ParserRefImpl::ParserRefImpl;
  7252. auto parse( std::string const &, TokenStream const &tokens ) const -> InternalParseResult override {
  7253. auto validationResult = validate();
  7254. if( !validationResult )
  7255. return InternalParseResult( validationResult );
  7256. auto remainingTokens = tokens;
  7257. auto const &token = *remainingTokens;
  7258. if( token.type != TokenType::Argument )
  7259. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
  7260. assert( !m_ref->isFlag() );
  7261. auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
  7262. auto result = valueRef->setValue( remainingTokens->token );
  7263. if( !result )
  7264. return InternalParseResult( result );
  7265. else
  7266. return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
  7267. }
  7268. };
  7269. inline auto normaliseOpt( std::string const &optName ) -> std::string {
  7270. #ifdef CATCH_PLATFORM_WINDOWS
  7271. if( optName[0] == '/' )
  7272. return "-" + optName.substr( 1 );
  7273. else
  7274. #endif
  7275. return optName;
  7276. }
  7277. class Opt : public ParserRefImpl<Opt> {
  7278. protected:
  7279. std::vector<std::string> m_optNames;
  7280. public:
  7281. template<typename LambdaT>
  7282. explicit Opt( LambdaT const &ref ) : ParserRefImpl( std::make_shared<BoundFlagLambda<LambdaT>>( ref ) ) {}
  7283. explicit Opt( bool &ref ) : ParserRefImpl( std::make_shared<BoundFlagRef>( ref ) ) {}
  7284. template<typename LambdaT>
  7285. Opt( LambdaT const &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  7286. template<typename T>
  7287. Opt( T &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  7288. auto operator[]( std::string const &optName ) -> Opt & {
  7289. m_optNames.push_back( optName );
  7290. return *this;
  7291. }
  7292. auto getHelpColumns() const -> std::vector<HelpColumns> {
  7293. std::ostringstream oss;
  7294. bool first = true;
  7295. for( auto const &opt : m_optNames ) {
  7296. if (first)
  7297. first = false;
  7298. else
  7299. oss << ", ";
  7300. oss << opt;
  7301. }
  7302. if( !m_hint.empty() )
  7303. oss << " <" << m_hint << ">";
  7304. return { { oss.str(), m_description } };
  7305. }
  7306. auto isMatch( std::string const &optToken ) const -> bool {
  7307. auto normalisedToken = normaliseOpt( optToken );
  7308. for( auto const &name : m_optNames ) {
  7309. if( normaliseOpt( name ) == normalisedToken )
  7310. return true;
  7311. }
  7312. return false;
  7313. }
  7314. using ParserBase::parse;
  7315. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  7316. auto validationResult = validate();
  7317. if( !validationResult )
  7318. return InternalParseResult( validationResult );
  7319. auto remainingTokens = tokens;
  7320. if( remainingTokens && remainingTokens->type == TokenType::Option ) {
  7321. auto const &token = *remainingTokens;
  7322. if( isMatch(token.token ) ) {
  7323. if( m_ref->isFlag() ) {
  7324. auto flagRef = static_cast<detail::BoundFlagRefBase*>( m_ref.get() );
  7325. auto result = flagRef->setFlag( true );
  7326. if( !result )
  7327. return InternalParseResult( result );
  7328. if( result.value() == ParseResultType::ShortCircuitAll )
  7329. return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
  7330. } else {
  7331. auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
  7332. ++remainingTokens;
  7333. if( !remainingTokens )
  7334. return InternalParseResult::runtimeError( "Expected argument following " + token.token );
  7335. auto const &argToken = *remainingTokens;
  7336. if( argToken.type != TokenType::Argument )
  7337. return InternalParseResult::runtimeError( "Expected argument following " + token.token );
  7338. auto result = valueRef->setValue( argToken.token );
  7339. if( !result )
  7340. return InternalParseResult( result );
  7341. if( result.value() == ParseResultType::ShortCircuitAll )
  7342. return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
  7343. }
  7344. return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
  7345. }
  7346. }
  7347. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
  7348. }
  7349. auto validate() const -> Result override {
  7350. if( m_optNames.empty() )
  7351. return Result::logicError( "No options supplied to Opt" );
  7352. for( auto const &name : m_optNames ) {
  7353. if( name.empty() )
  7354. return Result::logicError( "Option name cannot be empty" );
  7355. #ifdef CATCH_PLATFORM_WINDOWS
  7356. if( name[0] != '-' && name[0] != '/' )
  7357. return Result::logicError( "Option name must begin with '-' or '/'" );
  7358. #else
  7359. if( name[0] != '-' )
  7360. return Result::logicError( "Option name must begin with '-'" );
  7361. #endif
  7362. }
  7363. return ParserRefImpl::validate();
  7364. }
  7365. };
  7366. struct Help : Opt {
  7367. Help( bool &showHelpFlag )
  7368. : Opt([&]( bool flag ) {
  7369. showHelpFlag = flag;
  7370. return ParserResult::ok( ParseResultType::ShortCircuitAll );
  7371. })
  7372. {
  7373. static_cast<Opt &>( *this )
  7374. ("display usage information")
  7375. ["-?"]["-h"]["--help"]
  7376. .optional();
  7377. }
  7378. };
  7379. struct Parser : ParserBase {
  7380. mutable ExeName m_exeName;
  7381. std::vector<Opt> m_options;
  7382. std::vector<Arg> m_args;
  7383. auto operator|=( ExeName const &exeName ) -> Parser & {
  7384. m_exeName = exeName;
  7385. return *this;
  7386. }
  7387. auto operator|=( Arg const &arg ) -> Parser & {
  7388. m_args.push_back(arg);
  7389. return *this;
  7390. }
  7391. auto operator|=( Opt const &opt ) -> Parser & {
  7392. m_options.push_back(opt);
  7393. return *this;
  7394. }
  7395. auto operator|=( Parser const &other ) -> Parser & {
  7396. m_options.insert(m_options.end(), other.m_options.begin(), other.m_options.end());
  7397. m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end());
  7398. return *this;
  7399. }
  7400. template<typename T>
  7401. auto operator|( T const &other ) const -> Parser {
  7402. return Parser( *this ) |= other;
  7403. }
  7404. // Forward deprecated interface with '+' instead of '|'
  7405. template<typename T>
  7406. auto operator+=( T const &other ) -> Parser & { return operator|=( other ); }
  7407. template<typename T>
  7408. auto operator+( T const &other ) const -> Parser { return operator|( other ); }
  7409. auto getHelpColumns() const -> std::vector<HelpColumns> {
  7410. std::vector<HelpColumns> cols;
  7411. for (auto const &o : m_options) {
  7412. auto childCols = o.getHelpColumns();
  7413. cols.insert( cols.end(), childCols.begin(), childCols.end() );
  7414. }
  7415. return cols;
  7416. }
  7417. void writeToStream( std::ostream &os ) const {
  7418. if (!m_exeName.name().empty()) {
  7419. os << "usage:\n" << " " << m_exeName.name() << " ";
  7420. bool required = true, first = true;
  7421. for( auto const &arg : m_args ) {
  7422. if (first)
  7423. first = false;
  7424. else
  7425. os << " ";
  7426. if( arg.isOptional() && required ) {
  7427. os << "[";
  7428. required = false;
  7429. }
  7430. os << "<" << arg.hint() << ">";
  7431. if( arg.cardinality() == 0 )
  7432. os << " ... ";
  7433. }
  7434. if( !required )
  7435. os << "]";
  7436. if( !m_options.empty() )
  7437. os << " options";
  7438. os << "\n\nwhere options are:" << std::endl;
  7439. }
  7440. auto rows = getHelpColumns();
  7441. size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH;
  7442. size_t optWidth = 0;
  7443. for( auto const &cols : rows )
  7444. optWidth = (std::max)(optWidth, cols.left.size() + 2);
  7445. optWidth = (std::min)(optWidth, consoleWidth/2);
  7446. for( auto const &cols : rows ) {
  7447. auto row =
  7448. TextFlow::Column( cols.left ).width( optWidth ).indent( 2 ) +
  7449. TextFlow::Spacer(4) +
  7450. TextFlow::Column( cols.right ).width( consoleWidth - 7 - optWidth );
  7451. os << row << std::endl;
  7452. }
  7453. }
  7454. friend auto operator<<( std::ostream &os, Parser const &parser ) -> std::ostream& {
  7455. parser.writeToStream( os );
  7456. return os;
  7457. }
  7458. auto validate() const -> Result override {
  7459. for( auto const &opt : m_options ) {
  7460. auto result = opt.validate();
  7461. if( !result )
  7462. return result;
  7463. }
  7464. for( auto const &arg : m_args ) {
  7465. auto result = arg.validate();
  7466. if( !result )
  7467. return result;
  7468. }
  7469. return Result::ok();
  7470. }
  7471. using ParserBase::parse;
  7472. auto parse( std::string const& exeName, TokenStream const &tokens ) const -> InternalParseResult override {
  7473. struct ParserInfo {
  7474. ParserBase const* parser = nullptr;
  7475. size_t count = 0;
  7476. };
  7477. const size_t totalParsers = m_options.size() + m_args.size();
  7478. assert( totalParsers < 512 );
  7479. // ParserInfo parseInfos[totalParsers]; // <-- this is what we really want to do
  7480. ParserInfo parseInfos[512];
  7481. {
  7482. size_t i = 0;
  7483. for (auto const &opt : m_options) parseInfos[i++].parser = &opt;
  7484. for (auto const &arg : m_args) parseInfos[i++].parser = &arg;
  7485. }
  7486. m_exeName.set( exeName );
  7487. auto result = InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
  7488. while( result.value().remainingTokens() ) {
  7489. bool tokenParsed = false;
  7490. for( size_t i = 0; i < totalParsers; ++i ) {
  7491. auto& parseInfo = parseInfos[i];
  7492. if( parseInfo.parser->cardinality() == 0 || parseInfo.count < parseInfo.parser->cardinality() ) {
  7493. result = parseInfo.parser->parse(exeName, result.value().remainingTokens());
  7494. if (!result)
  7495. return result;
  7496. if (result.value().type() != ParseResultType::NoMatch) {
  7497. tokenParsed = true;
  7498. ++parseInfo.count;
  7499. break;
  7500. }
  7501. }
  7502. }
  7503. if( result.value().type() == ParseResultType::ShortCircuitAll )
  7504. return result;
  7505. if( !tokenParsed )
  7506. return InternalParseResult::runtimeError( "Unrecognised token: " + result.value().remainingTokens()->token );
  7507. }
  7508. // !TBD Check missing required options
  7509. return result;
  7510. }
  7511. };
  7512. template<typename DerivedT>
  7513. template<typename T>
  7514. auto ComposableParserImpl<DerivedT>::operator|( T const &other ) const -> Parser {
  7515. return Parser() | static_cast<DerivedT const &>( *this ) | other;
  7516. }
  7517. } // namespace detail
  7518. // A Combined parser
  7519. using detail::Parser;
  7520. // A parser for options
  7521. using detail::Opt;
  7522. // A parser for arguments
  7523. using detail::Arg;
  7524. // Wrapper for argc, argv from main()
  7525. using detail::Args;
  7526. // Specifies the name of the executable
  7527. using detail::ExeName;
  7528. // Convenience wrapper for option parser that specifies the help option
  7529. using detail::Help;
  7530. // enum of result types from a parse
  7531. using detail::ParseResultType;
  7532. // Result type for parser operation
  7533. using detail::ParserResult;
  7534. }} // namespace Catch::clara
  7535. // end clara.hpp
  7536. #ifdef __clang__
  7537. #pragma clang diagnostic pop
  7538. #endif
  7539. // Restore Clara's value for console width, if present
  7540. #ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  7541. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  7542. #undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  7543. #endif
  7544. // end catch_clara.h
  7545. namespace Catch {
  7546. clara::Parser makeCommandLineParser( ConfigData& config );
  7547. } // end namespace Catch
  7548. // end catch_commandline.h
  7549. #include <fstream>
  7550. #include <ctime>
  7551. namespace Catch {
  7552. clara::Parser makeCommandLineParser( ConfigData& config ) {
  7553. using namespace clara;
  7554. auto const setWarning = [&]( std::string const& warning ) {
  7555. auto warningSet = [&]() {
  7556. if( warning == "NoAssertions" )
  7557. return WarnAbout::NoAssertions;
  7558. if ( warning == "NoTests" )
  7559. return WarnAbout::NoTests;
  7560. return WarnAbout::Nothing;
  7561. }();
  7562. if (warningSet == WarnAbout::Nothing)
  7563. return ParserResult::runtimeError( "Unrecognised warning: '" + warning + "'" );
  7564. config.warnings = static_cast<WarnAbout::What>( config.warnings | warningSet );
  7565. return ParserResult::ok( ParseResultType::Matched );
  7566. };
  7567. auto const loadTestNamesFromFile = [&]( std::string const& filename ) {
  7568. std::ifstream f( filename.c_str() );
  7569. if( !f.is_open() )
  7570. return ParserResult::runtimeError( "Unable to load input file: '" + filename + "'" );
  7571. std::string line;
  7572. while( std::getline( f, line ) ) {
  7573. line = trim(line);
  7574. if( !line.empty() && !startsWith( line, '#' ) ) {
  7575. if( !startsWith( line, '"' ) )
  7576. line = '"' + line + '"';
  7577. config.testsOrTags.push_back( line + ',' );
  7578. }
  7579. }
  7580. return ParserResult::ok( ParseResultType::Matched );
  7581. };
  7582. auto const setTestOrder = [&]( std::string const& order ) {
  7583. if( startsWith( "declared", order ) )
  7584. config.runOrder = RunTests::InDeclarationOrder;
  7585. else if( startsWith( "lexical", order ) )
  7586. config.runOrder = RunTests::InLexicographicalOrder;
  7587. else if( startsWith( "random", order ) )
  7588. config.runOrder = RunTests::InRandomOrder;
  7589. else
  7590. return clara::ParserResult::runtimeError( "Unrecognised ordering: '" + order + "'" );
  7591. return ParserResult::ok( ParseResultType::Matched );
  7592. };
  7593. auto const setRngSeed = [&]( std::string const& seed ) {
  7594. if( seed != "time" )
  7595. return clara::detail::convertInto( seed, config.rngSeed );
  7596. config.rngSeed = static_cast<unsigned int>( std::time(nullptr) );
  7597. return ParserResult::ok( ParseResultType::Matched );
  7598. };
  7599. auto const setColourUsage = [&]( std::string const& useColour ) {
  7600. auto mode = toLower( useColour );
  7601. if( mode == "yes" )
  7602. config.useColour = UseColour::Yes;
  7603. else if( mode == "no" )
  7604. config.useColour = UseColour::No;
  7605. else if( mode == "auto" )
  7606. config.useColour = UseColour::Auto;
  7607. else
  7608. return ParserResult::runtimeError( "colour mode must be one of: auto, yes or no. '" + useColour + "' not recognised" );
  7609. return ParserResult::ok( ParseResultType::Matched );
  7610. };
  7611. auto const setWaitForKeypress = [&]( std::string const& keypress ) {
  7612. auto keypressLc = toLower( keypress );
  7613. if( keypressLc == "start" )
  7614. config.waitForKeypress = WaitForKeypress::BeforeStart;
  7615. else if( keypressLc == "exit" )
  7616. config.waitForKeypress = WaitForKeypress::BeforeExit;
  7617. else if( keypressLc == "both" )
  7618. config.waitForKeypress = WaitForKeypress::BeforeStartAndExit;
  7619. else
  7620. return ParserResult::runtimeError( "keypress argument must be one of: start, exit or both. '" + keypress + "' not recognised" );
  7621. return ParserResult::ok( ParseResultType::Matched );
  7622. };
  7623. auto const setVerbosity = [&]( std::string const& verbosity ) {
  7624. auto lcVerbosity = toLower( verbosity );
  7625. if( lcVerbosity == "quiet" )
  7626. config.verbosity = Verbosity::Quiet;
  7627. else if( lcVerbosity == "normal" )
  7628. config.verbosity = Verbosity::Normal;
  7629. else if( lcVerbosity == "high" )
  7630. config.verbosity = Verbosity::High;
  7631. else
  7632. return ParserResult::runtimeError( "Unrecognised verbosity, '" + verbosity + "'" );
  7633. return ParserResult::ok( ParseResultType::Matched );
  7634. };
  7635. auto const setReporter = [&]( std::string const& reporter ) {
  7636. IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
  7637. auto lcReporter = toLower( reporter );
  7638. auto result = factories.find( lcReporter );
  7639. if( factories.end() != result )
  7640. config.reporterName = lcReporter;
  7641. else
  7642. return ParserResult::runtimeError( "Unrecognized reporter, '" + reporter + "'. Check available with --list-reporters" );
  7643. return ParserResult::ok( ParseResultType::Matched );
  7644. };
  7645. auto cli
  7646. = ExeName( config.processName )
  7647. | Help( config.showHelp )
  7648. | Opt( config.listTests )
  7649. ["-l"]["--list-tests"]
  7650. ( "list all/matching test cases" )
  7651. | Opt( config.listTags )
  7652. ["-t"]["--list-tags"]
  7653. ( "list all/matching tags" )
  7654. | Opt( config.showSuccessfulTests )
  7655. ["-s"]["--success"]
  7656. ( "include successful tests in output" )
  7657. | Opt( config.shouldDebugBreak )
  7658. ["-b"]["--break"]
  7659. ( "break into debugger on failure" )
  7660. | Opt( config.noThrow )
  7661. ["-e"]["--nothrow"]
  7662. ( "skip exception tests" )
  7663. | Opt( config.showInvisibles )
  7664. ["-i"]["--invisibles"]
  7665. ( "show invisibles (tabs, newlines)" )
  7666. | Opt( config.outputFilename, "filename" )
  7667. ["-o"]["--out"]
  7668. ( "output filename" )
  7669. | Opt( setReporter, "name" )
  7670. ["-r"]["--reporter"]
  7671. ( "reporter to use (defaults to console)" )
  7672. | Opt( config.name, "name" )
  7673. ["-n"]["--name"]
  7674. ( "suite name" )
  7675. | Opt( [&]( bool ){ config.abortAfter = 1; } )
  7676. ["-a"]["--abort"]
  7677. ( "abort at first failure" )
  7678. | Opt( [&]( int x ){ config.abortAfter = x; }, "no. failures" )
  7679. ["-x"]["--abortx"]
  7680. ( "abort after x failures" )
  7681. | Opt( setWarning, "warning name" )
  7682. ["-w"]["--warn"]
  7683. ( "enable warnings" )
  7684. | Opt( [&]( bool flag ) { config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never; }, "yes|no" )
  7685. ["-d"]["--durations"]
  7686. ( "show test durations" )
  7687. | Opt( loadTestNamesFromFile, "filename" )
  7688. ["-f"]["--input-file"]
  7689. ( "load test names to run from a file" )
  7690. | Opt( config.filenamesAsTags )
  7691. ["-#"]["--filenames-as-tags"]
  7692. ( "adds a tag for the filename" )
  7693. | Opt( config.sectionsToRun, "section name" )
  7694. ["-c"]["--section"]
  7695. ( "specify section to run" )
  7696. | Opt( setVerbosity, "quiet|normal|high" )
  7697. ["-v"]["--verbosity"]
  7698. ( "set output verbosity" )
  7699. | Opt( config.listTestNamesOnly )
  7700. ["--list-test-names-only"]
  7701. ( "list all/matching test cases names only" )
  7702. | Opt( config.listReporters )
  7703. ["--list-reporters"]
  7704. ( "list all reporters" )
  7705. | Opt( setTestOrder, "decl|lex|rand" )
  7706. ["--order"]
  7707. ( "test case order (defaults to decl)" )
  7708. | Opt( setRngSeed, "'time'|number" )
  7709. ["--rng-seed"]
  7710. ( "set a specific seed for random numbers" )
  7711. | Opt( setColourUsage, "yes|no" )
  7712. ["--use-colour"]
  7713. ( "should output be colourised" )
  7714. | Opt( config.libIdentify )
  7715. ["--libidentify"]
  7716. ( "report name and version according to libidentify standard" )
  7717. | Opt( setWaitForKeypress, "start|exit|both" )
  7718. ["--wait-for-keypress"]
  7719. ( "waits for a keypress before exiting" )
  7720. | Opt( config.benchmarkSamples, "samples" )
  7721. ["--benchmark-samples"]
  7722. ( "number of samples to collect (default: 100)" )
  7723. | Opt( config.benchmarkResamples, "resamples" )
  7724. ["--benchmark-resamples"]
  7725. ( "number of resamples for the bootstrap (default: 100000)" )
  7726. | Opt( config.benchmarkConfidenceInterval, "confidence interval" )
  7727. ["--benchmark-confidence-interval"]
  7728. ( "confidence interval for the bootstrap (between 0 and 1, default: 0.95)" )
  7729. | Opt( config.benchmarkNoAnalysis )
  7730. ["--benchmark-no-analysis"]
  7731. ( "perform only measurements; do not perform any analysis" )
  7732. | Arg( config.testsOrTags, "test name|pattern|tags" )
  7733. ( "which test or tests to use" );
  7734. return cli;
  7735. }
  7736. } // end namespace Catch
  7737. // end catch_commandline.cpp
  7738. // start catch_common.cpp
  7739. #include <cstring>
  7740. #include <ostream>
  7741. namespace Catch {
  7742. bool SourceLineInfo::empty() const noexcept {
  7743. return file[0] == '\0';
  7744. }
  7745. bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const noexcept {
  7746. return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0);
  7747. }
  7748. bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const noexcept {
  7749. // We can assume that the same file will usually have the same pointer.
  7750. // Thus, if the pointers are the same, there is no point in calling the strcmp
  7751. return line < other.line || ( line == other.line && file != other.file && (std::strcmp(file, other.file) < 0));
  7752. }
  7753. std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) {
  7754. #ifndef __GNUG__
  7755. os << info.file << '(' << info.line << ')';
  7756. #else
  7757. os << info.file << ':' << info.line;
  7758. #endif
  7759. return os;
  7760. }
  7761. std::string StreamEndStop::operator+() const {
  7762. return std::string();
  7763. }
  7764. NonCopyable::NonCopyable() = default;
  7765. NonCopyable::~NonCopyable() = default;
  7766. }
  7767. // end catch_common.cpp
  7768. // start catch_config.cpp
  7769. namespace Catch {
  7770. Config::Config( ConfigData const& data )
  7771. : m_data( data ),
  7772. m_stream( openStream() )
  7773. {
  7774. TestSpecParser parser(ITagAliasRegistry::get());
  7775. if (!data.testsOrTags.empty()) {
  7776. m_hasTestFilters = true;
  7777. for( auto const& testOrTags : data.testsOrTags )
  7778. parser.parse( testOrTags );
  7779. }
  7780. m_testSpec = parser.testSpec();
  7781. }
  7782. std::string const& Config::getFilename() const {
  7783. return m_data.outputFilename ;
  7784. }
  7785. bool Config::listTests() const { return m_data.listTests; }
  7786. bool Config::listTestNamesOnly() const { return m_data.listTestNamesOnly; }
  7787. bool Config::listTags() const { return m_data.listTags; }
  7788. bool Config::listReporters() const { return m_data.listReporters; }
  7789. std::string Config::getProcessName() const { return m_data.processName; }
  7790. std::string const& Config::getReporterName() const { return m_data.reporterName; }
  7791. std::vector<std::string> const& Config::getTestsOrTags() const { return m_data.testsOrTags; }
  7792. std::vector<std::string> const& Config::getSectionsToRun() const { return m_data.sectionsToRun; }
  7793. TestSpec const& Config::testSpec() const { return m_testSpec; }
  7794. bool Config::hasTestFilters() const { return m_hasTestFilters; }
  7795. bool Config::showHelp() const { return m_data.showHelp; }
  7796. // IConfig interface
  7797. bool Config::allowThrows() const { return !m_data.noThrow; }
  7798. std::ostream& Config::stream() const { return m_stream->stream(); }
  7799. std::string Config::name() const { return m_data.name.empty() ? m_data.processName : m_data.name; }
  7800. bool Config::includeSuccessfulResults() const { return m_data.showSuccessfulTests; }
  7801. bool Config::warnAboutMissingAssertions() const { return !!(m_data.warnings & WarnAbout::NoAssertions); }
  7802. bool Config::warnAboutNoTests() const { return !!(m_data.warnings & WarnAbout::NoTests); }
  7803. ShowDurations::OrNot Config::showDurations() const { return m_data.showDurations; }
  7804. RunTests::InWhatOrder Config::runOrder() const { return m_data.runOrder; }
  7805. unsigned int Config::rngSeed() const { return m_data.rngSeed; }
  7806. UseColour::YesOrNo Config::useColour() const { return m_data.useColour; }
  7807. bool Config::shouldDebugBreak() const { return m_data.shouldDebugBreak; }
  7808. int Config::abortAfter() const { return m_data.abortAfter; }
  7809. bool Config::showInvisibles() const { return m_data.showInvisibles; }
  7810. Verbosity Config::verbosity() const { return m_data.verbosity; }
  7811. bool Config::benchmarkNoAnalysis() const { return m_data.benchmarkNoAnalysis; }
  7812. int Config::benchmarkSamples() const { return m_data.benchmarkSamples; }
  7813. double Config::benchmarkConfidenceInterval() const { return m_data.benchmarkConfidenceInterval; }
  7814. unsigned int Config::benchmarkResamples() const { return m_data.benchmarkResamples; }
  7815. IStream const* Config::openStream() {
  7816. return Catch::makeStream(m_data.outputFilename);
  7817. }
  7818. } // end namespace Catch
  7819. // end catch_config.cpp
  7820. // start catch_console_colour.cpp
  7821. #if defined(__clang__)
  7822. # pragma clang diagnostic push
  7823. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  7824. #endif
  7825. // start catch_errno_guard.h
  7826. namespace Catch {
  7827. class ErrnoGuard {
  7828. public:
  7829. ErrnoGuard();
  7830. ~ErrnoGuard();
  7831. private:
  7832. int m_oldErrno;
  7833. };
  7834. }
  7835. // end catch_errno_guard.h
  7836. #include <sstream>
  7837. namespace Catch {
  7838. namespace {
  7839. struct IColourImpl {
  7840. virtual ~IColourImpl() = default;
  7841. virtual void use( Colour::Code _colourCode ) = 0;
  7842. };
  7843. struct NoColourImpl : IColourImpl {
  7844. void use( Colour::Code ) {}
  7845. static IColourImpl* instance() {
  7846. static NoColourImpl s_instance;
  7847. return &s_instance;
  7848. }
  7849. };
  7850. } // anon namespace
  7851. } // namespace Catch
  7852. #if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI )
  7853. # ifdef CATCH_PLATFORM_WINDOWS
  7854. # define CATCH_CONFIG_COLOUR_WINDOWS
  7855. # else
  7856. # define CATCH_CONFIG_COLOUR_ANSI
  7857. # endif
  7858. #endif
  7859. #if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) /////////////////////////////////////////
  7860. namespace Catch {
  7861. namespace {
  7862. class Win32ColourImpl : public IColourImpl {
  7863. public:
  7864. Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) )
  7865. {
  7866. CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
  7867. GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo );
  7868. originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY );
  7869. originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY );
  7870. }
  7871. void use( Colour::Code _colourCode ) override {
  7872. switch( _colourCode ) {
  7873. case Colour::None: return setTextAttribute( originalForegroundAttributes );
  7874. case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  7875. case Colour::Red: return setTextAttribute( FOREGROUND_RED );
  7876. case Colour::Green: return setTextAttribute( FOREGROUND_GREEN );
  7877. case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE );
  7878. case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN );
  7879. case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN );
  7880. case Colour::Grey: return setTextAttribute( 0 );
  7881. case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY );
  7882. case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED );
  7883. case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN );
  7884. case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  7885. case Colour::BrightYellow: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN );
  7886. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  7887. default:
  7888. CATCH_ERROR( "Unknown colour requested" );
  7889. }
  7890. }
  7891. private:
  7892. void setTextAttribute( WORD _textAttribute ) {
  7893. SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes );
  7894. }
  7895. HANDLE stdoutHandle;
  7896. WORD originalForegroundAttributes;
  7897. WORD originalBackgroundAttributes;
  7898. };
  7899. IColourImpl* platformColourInstance() {
  7900. static Win32ColourImpl s_instance;
  7901. IConfigPtr config = getCurrentContext().getConfig();
  7902. UseColour::YesOrNo colourMode = config
  7903. ? config->useColour()
  7904. : UseColour::Auto;
  7905. if( colourMode == UseColour::Auto )
  7906. colourMode = UseColour::Yes;
  7907. return colourMode == UseColour::Yes
  7908. ? &s_instance
  7909. : NoColourImpl::instance();
  7910. }
  7911. } // end anon namespace
  7912. } // end namespace Catch
  7913. #elif defined( CATCH_CONFIG_COLOUR_ANSI ) //////////////////////////////////////
  7914. #include <unistd.h>
  7915. namespace Catch {
  7916. namespace {
  7917. // use POSIX/ ANSI console terminal codes
  7918. // Thanks to Adam Strzelecki for original contribution
  7919. // (http://github.com/nanoant)
  7920. // https://github.com/philsquared/Catch/pull/131
  7921. class PosixColourImpl : public IColourImpl {
  7922. public:
  7923. void use( Colour::Code _colourCode ) override {
  7924. switch( _colourCode ) {
  7925. case Colour::None:
  7926. case Colour::White: return setColour( "[0m" );
  7927. case Colour::Red: return setColour( "[0;31m" );
  7928. case Colour::Green: return setColour( "[0;32m" );
  7929. case Colour::Blue: return setColour( "[0;34m" );
  7930. case Colour::Cyan: return setColour( "[0;36m" );
  7931. case Colour::Yellow: return setColour( "[0;33m" );
  7932. case Colour::Grey: return setColour( "[1;30m" );
  7933. case Colour::LightGrey: return setColour( "[0;37m" );
  7934. case Colour::BrightRed: return setColour( "[1;31m" );
  7935. case Colour::BrightGreen: return setColour( "[1;32m" );
  7936. case Colour::BrightWhite: return setColour( "[1;37m" );
  7937. case Colour::BrightYellow: return setColour( "[1;33m" );
  7938. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  7939. default: CATCH_INTERNAL_ERROR( "Unknown colour requested" );
  7940. }
  7941. }
  7942. static IColourImpl* instance() {
  7943. static PosixColourImpl s_instance;
  7944. return &s_instance;
  7945. }
  7946. private:
  7947. void setColour( const char* _escapeCode ) {
  7948. getCurrentContext().getConfig()->stream()
  7949. << '\033' << _escapeCode;
  7950. }
  7951. };
  7952. bool useColourOnPlatform() {
  7953. return
  7954. #ifdef CATCH_PLATFORM_MAC
  7955. !isDebuggerActive() &&
  7956. #endif
  7957. #if !(defined(__DJGPP__) && defined(__STRICT_ANSI__))
  7958. isatty(STDOUT_FILENO)
  7959. #else
  7960. false
  7961. #endif
  7962. ;
  7963. }
  7964. IColourImpl* platformColourInstance() {
  7965. ErrnoGuard guard;
  7966. IConfigPtr config = getCurrentContext().getConfig();
  7967. UseColour::YesOrNo colourMode = config
  7968. ? config->useColour()
  7969. : UseColour::Auto;
  7970. if( colourMode == UseColour::Auto )
  7971. colourMode = useColourOnPlatform()
  7972. ? UseColour::Yes
  7973. : UseColour::No;
  7974. return colourMode == UseColour::Yes
  7975. ? PosixColourImpl::instance()
  7976. : NoColourImpl::instance();
  7977. }
  7978. } // end anon namespace
  7979. } // end namespace Catch
  7980. #else // not Windows or ANSI ///////////////////////////////////////////////
  7981. namespace Catch {
  7982. static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); }
  7983. } // end namespace Catch
  7984. #endif // Windows/ ANSI/ None
  7985. namespace Catch {
  7986. Colour::Colour( Code _colourCode ) { use( _colourCode ); }
  7987. Colour::Colour( Colour&& rhs ) noexcept {
  7988. m_moved = rhs.m_moved;
  7989. rhs.m_moved = true;
  7990. }
  7991. Colour& Colour::operator=( Colour&& rhs ) noexcept {
  7992. m_moved = rhs.m_moved;
  7993. rhs.m_moved = true;
  7994. return *this;
  7995. }
  7996. Colour::~Colour(){ if( !m_moved ) use( None ); }
  7997. void Colour::use( Code _colourCode ) {
  7998. static IColourImpl* impl = platformColourInstance();
  7999. // Strictly speaking, this cannot possibly happen.
  8000. // However, under some conditions it does happen (see #1626),
  8001. // and this change is small enough that we can let practicality
  8002. // triumph over purity in this case.
  8003. if (impl != NULL) {
  8004. impl->use( _colourCode );
  8005. }
  8006. }
  8007. std::ostream& operator << ( std::ostream& os, Colour const& ) {
  8008. return os;
  8009. }
  8010. } // end namespace Catch
  8011. #if defined(__clang__)
  8012. # pragma clang diagnostic pop
  8013. #endif
  8014. // end catch_console_colour.cpp
  8015. // start catch_context.cpp
  8016. namespace Catch {
  8017. class Context : public IMutableContext, NonCopyable {
  8018. public: // IContext
  8019. IResultCapture* getResultCapture() override {
  8020. return m_resultCapture;
  8021. }
  8022. IRunner* getRunner() override {
  8023. return m_runner;
  8024. }
  8025. IConfigPtr const& getConfig() const override {
  8026. return m_config;
  8027. }
  8028. ~Context() override;
  8029. public: // IMutableContext
  8030. void setResultCapture( IResultCapture* resultCapture ) override {
  8031. m_resultCapture = resultCapture;
  8032. }
  8033. void setRunner( IRunner* runner ) override {
  8034. m_runner = runner;
  8035. }
  8036. void setConfig( IConfigPtr const& config ) override {
  8037. m_config = config;
  8038. }
  8039. friend IMutableContext& getCurrentMutableContext();
  8040. private:
  8041. IConfigPtr m_config;
  8042. IRunner* m_runner = nullptr;
  8043. IResultCapture* m_resultCapture = nullptr;
  8044. };
  8045. IMutableContext *IMutableContext::currentContext = nullptr;
  8046. void IMutableContext::createContext()
  8047. {
  8048. currentContext = new Context();
  8049. }
  8050. void cleanUpContext() {
  8051. delete IMutableContext::currentContext;
  8052. IMutableContext::currentContext = nullptr;
  8053. }
  8054. IContext::~IContext() = default;
  8055. IMutableContext::~IMutableContext() = default;
  8056. Context::~Context() = default;
  8057. }
  8058. // end catch_context.cpp
  8059. // start catch_debug_console.cpp
  8060. // start catch_debug_console.h
  8061. #include <string>
  8062. namespace Catch {
  8063. void writeToDebugConsole( std::string const& text );
  8064. }
  8065. // end catch_debug_console.h
  8066. #ifdef CATCH_PLATFORM_WINDOWS
  8067. namespace Catch {
  8068. void writeToDebugConsole( std::string const& text ) {
  8069. ::OutputDebugStringA( text.c_str() );
  8070. }
  8071. }
  8072. #else
  8073. namespace Catch {
  8074. void writeToDebugConsole( std::string const& text ) {
  8075. // !TBD: Need a version for Mac/ XCode and other IDEs
  8076. Catch::cout() << text;
  8077. }
  8078. }
  8079. #endif // Platform
  8080. // end catch_debug_console.cpp
  8081. // start catch_debugger.cpp
  8082. #ifdef CATCH_PLATFORM_MAC
  8083. # include <assert.h>
  8084. # include <stdbool.h>
  8085. # include <sys/types.h>
  8086. # include <unistd.h>
  8087. # include <cstddef>
  8088. # include <ostream>
  8089. #ifdef __apple_build_version__
  8090. // These headers will only compile with AppleClang (XCode)
  8091. // For other compilers (Clang, GCC, ... ) we need to exclude them
  8092. # include <sys/sysctl.h>
  8093. #endif
  8094. namespace Catch {
  8095. #ifdef __apple_build_version__
  8096. // The following function is taken directly from the following technical note:
  8097. // https://developer.apple.com/library/archive/qa/qa1361/_index.html
  8098. // Returns true if the current process is being debugged (either
  8099. // running under the debugger or has a debugger attached post facto).
  8100. bool isDebuggerActive(){
  8101. int mib[4];
  8102. struct kinfo_proc info;
  8103. std::size_t size;
  8104. // Initialize the flags so that, if sysctl fails for some bizarre
  8105. // reason, we get a predictable result.
  8106. info.kp_proc.p_flag = 0;
  8107. // Initialize mib, which tells sysctl the info we want, in this case
  8108. // we're looking for information about a specific process ID.
  8109. mib[0] = CTL_KERN;
  8110. mib[1] = KERN_PROC;
  8111. mib[2] = KERN_PROC_PID;
  8112. mib[3] = getpid();
  8113. // Call sysctl.
  8114. size = sizeof(info);
  8115. if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0) != 0 ) {
  8116. Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl;
  8117. return false;
  8118. }
  8119. // We're being debugged if the P_TRACED flag is set.
  8120. return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
  8121. }
  8122. #else
  8123. bool isDebuggerActive() {
  8124. // We need to find another way to determine this for non-appleclang compilers on macOS
  8125. return false;
  8126. }
  8127. #endif
  8128. } // namespace Catch
  8129. #elif defined(CATCH_PLATFORM_LINUX)
  8130. #include <fstream>
  8131. #include <string>
  8132. namespace Catch{
  8133. // The standard POSIX way of detecting a debugger is to attempt to
  8134. // ptrace() the process, but this needs to be done from a child and not
  8135. // this process itself to still allow attaching to this process later
  8136. // if wanted, so is rather heavy. Under Linux we have the PID of the
  8137. // "debugger" (which doesn't need to be gdb, of course, it could also
  8138. // be strace, for example) in /proc/$PID/status, so just get it from
  8139. // there instead.
  8140. bool isDebuggerActive(){
  8141. // Libstdc++ has a bug, where std::ifstream sets errno to 0
  8142. // This way our users can properly assert over errno values
  8143. ErrnoGuard guard;
  8144. std::ifstream in("/proc/self/status");
  8145. for( std::string line; std::getline(in, line); ) {
  8146. static const int PREFIX_LEN = 11;
  8147. if( line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0 ) {
  8148. // We're traced if the PID is not 0 and no other PID starts
  8149. // with 0 digit, so it's enough to check for just a single
  8150. // character.
  8151. return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0';
  8152. }
  8153. }
  8154. return false;
  8155. }
  8156. } // namespace Catch
  8157. #elif defined(_MSC_VER)
  8158. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  8159. namespace Catch {
  8160. bool isDebuggerActive() {
  8161. return IsDebuggerPresent() != 0;
  8162. }
  8163. }
  8164. #elif defined(__MINGW32__)
  8165. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  8166. namespace Catch {
  8167. bool isDebuggerActive() {
  8168. return IsDebuggerPresent() != 0;
  8169. }
  8170. }
  8171. #else
  8172. namespace Catch {
  8173. bool isDebuggerActive() { return false; }
  8174. }
  8175. #endif // Platform
  8176. // end catch_debugger.cpp
  8177. // start catch_decomposer.cpp
  8178. namespace Catch {
  8179. ITransientExpression::~ITransientExpression() = default;
  8180. void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs ) {
  8181. if( lhs.size() + rhs.size() < 40 &&
  8182. lhs.find('\n') == std::string::npos &&
  8183. rhs.find('\n') == std::string::npos )
  8184. os << lhs << " " << op << " " << rhs;
  8185. else
  8186. os << lhs << "\n" << op << "\n" << rhs;
  8187. }
  8188. }
  8189. // end catch_decomposer.cpp
  8190. // start catch_enforce.cpp
  8191. #include <stdexcept>
  8192. namespace Catch {
  8193. #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS_CUSTOM_HANDLER)
  8194. [[noreturn]]
  8195. void throw_exception(std::exception const& e) {
  8196. Catch::cerr() << "Catch will terminate because it needed to throw an exception.\n"
  8197. << "The message was: " << e.what() << '\n';
  8198. std::terminate();
  8199. }
  8200. #endif
  8201. [[noreturn]]
  8202. void throw_logic_error(std::string const& msg) {
  8203. throw_exception(std::logic_error(msg));
  8204. }
  8205. [[noreturn]]
  8206. void throw_domain_error(std::string const& msg) {
  8207. throw_exception(std::domain_error(msg));
  8208. }
  8209. [[noreturn]]
  8210. void throw_runtime_error(std::string const& msg) {
  8211. throw_exception(std::runtime_error(msg));
  8212. }
  8213. } // namespace Catch;
  8214. // end catch_enforce.cpp
  8215. // start catch_enum_values_registry.cpp
  8216. // start catch_enum_values_registry.h
  8217. #include <vector>
  8218. #include <memory>
  8219. namespace Catch {
  8220. namespace Detail {
  8221. std::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int> const& values );
  8222. class EnumValuesRegistry : public IMutableEnumValuesRegistry {
  8223. std::vector<std::unique_ptr<EnumInfo>> m_enumInfos;
  8224. EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::vector<int> const& values) override;
  8225. };
  8226. std::vector<std::string> parseEnums( StringRef enums );
  8227. } // Detail
  8228. } // Catch
  8229. // end catch_enum_values_registry.h
  8230. #include <map>
  8231. #include <cassert>
  8232. namespace Catch {
  8233. IMutableEnumValuesRegistry::~IMutableEnumValuesRegistry() {}
  8234. namespace Detail {
  8235. std::vector<std::string> parseEnums( StringRef enums ) {
  8236. auto enumValues = splitStringRef( enums, ',' );
  8237. std::vector<std::string> parsed;
  8238. parsed.reserve( enumValues.size() );
  8239. for( auto const& enumValue : enumValues ) {
  8240. auto identifiers = splitStringRef( enumValue, ':' );
  8241. parsed.push_back( Catch::trim( identifiers.back() ) );
  8242. }
  8243. return parsed;
  8244. }
  8245. EnumInfo::~EnumInfo() {}
  8246. StringRef EnumInfo::lookup( int value ) const {
  8247. for( auto const& valueToName : m_values ) {
  8248. if( valueToName.first == value )
  8249. return valueToName.second;
  8250. }
  8251. return "{** unexpected enum value **}";
  8252. }
  8253. std::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ) {
  8254. std::unique_ptr<EnumInfo> enumInfo( new EnumInfo );
  8255. enumInfo->m_name = enumName;
  8256. enumInfo->m_values.reserve( values.size() );
  8257. const auto valueNames = Catch::Detail::parseEnums( allValueNames );
  8258. assert( valueNames.size() == values.size() );
  8259. std::size_t i = 0;
  8260. for( auto value : values )
  8261. enumInfo->m_values.push_back({ value, valueNames[i++] });
  8262. return enumInfo;
  8263. }
  8264. EnumInfo const& EnumValuesRegistry::registerEnum( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ) {
  8265. auto enumInfo = makeEnumInfo( enumName, allValueNames, values );
  8266. EnumInfo* raw = enumInfo.get();
  8267. m_enumInfos.push_back( std::move( enumInfo ) );
  8268. return *raw;
  8269. }
  8270. } // Detail
  8271. } // Catch
  8272. // end catch_enum_values_registry.cpp
  8273. // start catch_errno_guard.cpp
  8274. #include <cerrno>
  8275. namespace Catch {
  8276. ErrnoGuard::ErrnoGuard():m_oldErrno(errno){}
  8277. ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; }
  8278. }
  8279. // end catch_errno_guard.cpp
  8280. // start catch_exception_translator_registry.cpp
  8281. // start catch_exception_translator_registry.h
  8282. #include <vector>
  8283. #include <string>
  8284. #include <memory>
  8285. namespace Catch {
  8286. class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry {
  8287. public:
  8288. ~ExceptionTranslatorRegistry();
  8289. virtual void registerTranslator( const IExceptionTranslator* translator );
  8290. std::string translateActiveException() const override;
  8291. std::string tryTranslators() const;
  8292. private:
  8293. std::vector<std::unique_ptr<IExceptionTranslator const>> m_translators;
  8294. };
  8295. }
  8296. // end catch_exception_translator_registry.h
  8297. #ifdef __OBJC__
  8298. #import "Foundation/Foundation.h"
  8299. #endif
  8300. namespace Catch {
  8301. ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {
  8302. }
  8303. void ExceptionTranslatorRegistry::registerTranslator( const IExceptionTranslator* translator ) {
  8304. m_translators.push_back( std::unique_ptr<const IExceptionTranslator>( translator ) );
  8305. }
  8306. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  8307. std::string ExceptionTranslatorRegistry::translateActiveException() const {
  8308. try {
  8309. #ifdef __OBJC__
  8310. // In Objective-C try objective-c exceptions first
  8311. @try {
  8312. return tryTranslators();
  8313. }
  8314. @catch (NSException *exception) {
  8315. return Catch::Detail::stringify( [exception description] );
  8316. }
  8317. #else
  8318. // Compiling a mixed mode project with MSVC means that CLR
  8319. // exceptions will be caught in (...) as well. However, these
  8320. // do not fill-in std::current_exception and thus lead to crash
  8321. // when attempting rethrow.
  8322. // /EHa switch also causes structured exceptions to be caught
  8323. // here, but they fill-in current_exception properly, so
  8324. // at worst the output should be a little weird, instead of
  8325. // causing a crash.
  8326. if (std::current_exception() == nullptr) {
  8327. return "Non C++ exception. Possibly a CLR exception.";
  8328. }
  8329. return tryTranslators();
  8330. #endif
  8331. }
  8332. catch( TestFailureException& ) {
  8333. std::rethrow_exception(std::current_exception());
  8334. }
  8335. catch( std::exception& ex ) {
  8336. return ex.what();
  8337. }
  8338. catch( std::string& msg ) {
  8339. return msg;
  8340. }
  8341. catch( const char* msg ) {
  8342. return msg;
  8343. }
  8344. catch(...) {
  8345. return "Unknown exception";
  8346. }
  8347. }
  8348. std::string ExceptionTranslatorRegistry::tryTranslators() const {
  8349. if (m_translators.empty()) {
  8350. std::rethrow_exception(std::current_exception());
  8351. } else {
  8352. return m_translators[0]->translate(m_translators.begin() + 1, m_translators.end());
  8353. }
  8354. }
  8355. #else // ^^ Exceptions are enabled // Exceptions are disabled vv
  8356. std::string ExceptionTranslatorRegistry::translateActiveException() const {
  8357. CATCH_INTERNAL_ERROR("Attempted to translate active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
  8358. }
  8359. std::string ExceptionTranslatorRegistry::tryTranslators() const {
  8360. CATCH_INTERNAL_ERROR("Attempted to use exception translators under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
  8361. }
  8362. #endif
  8363. }
  8364. // end catch_exception_translator_registry.cpp
  8365. // start catch_fatal_condition.cpp
  8366. #if defined(__GNUC__)
  8367. # pragma GCC diagnostic push
  8368. # pragma GCC diagnostic ignored "-Wmissing-field-initializers"
  8369. #endif
  8370. #if defined( CATCH_CONFIG_WINDOWS_SEH ) || defined( CATCH_CONFIG_POSIX_SIGNALS )
  8371. namespace {
  8372. // Report the error condition
  8373. void reportFatal( char const * const message ) {
  8374. Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition( message );
  8375. }
  8376. }
  8377. #endif // signals/SEH handling
  8378. #if defined( CATCH_CONFIG_WINDOWS_SEH )
  8379. namespace Catch {
  8380. struct SignalDefs { DWORD id; const char* name; };
  8381. // There is no 1-1 mapping between signals and windows exceptions.
  8382. // Windows can easily distinguish between SO and SigSegV,
  8383. // but SigInt, SigTerm, etc are handled differently.
  8384. static SignalDefs signalDefs[] = {
  8385. { static_cast<DWORD>(EXCEPTION_ILLEGAL_INSTRUCTION), "SIGILL - Illegal instruction signal" },
  8386. { static_cast<DWORD>(EXCEPTION_STACK_OVERFLOW), "SIGSEGV - Stack overflow" },
  8387. { static_cast<DWORD>(EXCEPTION_ACCESS_VIOLATION), "SIGSEGV - Segmentation violation signal" },
  8388. { static_cast<DWORD>(EXCEPTION_INT_DIVIDE_BY_ZERO), "Divide by zero error" },
  8389. };
  8390. LONG CALLBACK FatalConditionHandler::handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {
  8391. for (auto const& def : signalDefs) {
  8392. if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) {
  8393. reportFatal(def.name);
  8394. }
  8395. }
  8396. // If its not an exception we care about, pass it along.
  8397. // This stops us from eating debugger breaks etc.
  8398. return EXCEPTION_CONTINUE_SEARCH;
  8399. }
  8400. FatalConditionHandler::FatalConditionHandler() {
  8401. isSet = true;
  8402. // 32k seems enough for Catch to handle stack overflow,
  8403. // but the value was found experimentally, so there is no strong guarantee
  8404. guaranteeSize = 32 * 1024;
  8405. exceptionHandlerHandle = nullptr;
  8406. // Register as first handler in current chain
  8407. exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);
  8408. // Pass in guarantee size to be filled
  8409. SetThreadStackGuarantee(&guaranteeSize);
  8410. }
  8411. void FatalConditionHandler::reset() {
  8412. if (isSet) {
  8413. RemoveVectoredExceptionHandler(exceptionHandlerHandle);
  8414. SetThreadStackGuarantee(&guaranteeSize);
  8415. exceptionHandlerHandle = nullptr;
  8416. isSet = false;
  8417. }
  8418. }
  8419. FatalConditionHandler::~FatalConditionHandler() {
  8420. reset();
  8421. }
  8422. bool FatalConditionHandler::isSet = false;
  8423. ULONG FatalConditionHandler::guaranteeSize = 0;
  8424. PVOID FatalConditionHandler::exceptionHandlerHandle = nullptr;
  8425. } // namespace Catch
  8426. #elif defined( CATCH_CONFIG_POSIX_SIGNALS )
  8427. namespace Catch {
  8428. struct SignalDefs {
  8429. int id;
  8430. const char* name;
  8431. };
  8432. // 32kb for the alternate stack seems to be sufficient. However, this value
  8433. // is experimentally determined, so that's not guaranteed.
  8434. constexpr static std::size_t sigStackSize = 32768 >= MINSIGSTKSZ ? 32768 : MINSIGSTKSZ;
  8435. static SignalDefs signalDefs[] = {
  8436. { SIGINT, "SIGINT - Terminal interrupt signal" },
  8437. { SIGILL, "SIGILL - Illegal instruction signal" },
  8438. { SIGFPE, "SIGFPE - Floating point error signal" },
  8439. { SIGSEGV, "SIGSEGV - Segmentation violation signal" },
  8440. { SIGTERM, "SIGTERM - Termination request signal" },
  8441. { SIGABRT, "SIGABRT - Abort (abnormal termination) signal" }
  8442. };
  8443. void FatalConditionHandler::handleSignal( int sig ) {
  8444. char const * name = "<unknown signal>";
  8445. for (auto const& def : signalDefs) {
  8446. if (sig == def.id) {
  8447. name = def.name;
  8448. break;
  8449. }
  8450. }
  8451. reset();
  8452. reportFatal(name);
  8453. raise( sig );
  8454. }
  8455. FatalConditionHandler::FatalConditionHandler() {
  8456. isSet = true;
  8457. stack_t sigStack;
  8458. sigStack.ss_sp = altStackMem;
  8459. sigStack.ss_size = sigStackSize;
  8460. sigStack.ss_flags = 0;
  8461. sigaltstack(&sigStack, &oldSigStack);
  8462. struct sigaction sa = { };
  8463. sa.sa_handler = handleSignal;
  8464. sa.sa_flags = SA_ONSTACK;
  8465. for (std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i) {
  8466. sigaction(signalDefs[i].id, &sa, &oldSigActions[i]);
  8467. }
  8468. }
  8469. FatalConditionHandler::~FatalConditionHandler() {
  8470. reset();
  8471. }
  8472. void FatalConditionHandler::reset() {
  8473. if( isSet ) {
  8474. // Set signals back to previous values -- hopefully nobody overwrote them in the meantime
  8475. for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) {
  8476. sigaction(signalDefs[i].id, &oldSigActions[i], nullptr);
  8477. }
  8478. // Return the old stack
  8479. sigaltstack(&oldSigStack, nullptr);
  8480. isSet = false;
  8481. }
  8482. }
  8483. bool FatalConditionHandler::isSet = false;
  8484. struct sigaction FatalConditionHandler::oldSigActions[sizeof(signalDefs)/sizeof(SignalDefs)] = {};
  8485. stack_t FatalConditionHandler::oldSigStack = {};
  8486. char FatalConditionHandler::altStackMem[sigStackSize] = {};
  8487. } // namespace Catch
  8488. #else
  8489. namespace Catch {
  8490. void FatalConditionHandler::reset() {}
  8491. }
  8492. #endif // signals/SEH handling
  8493. #if defined(__GNUC__)
  8494. # pragma GCC diagnostic pop
  8495. #endif
  8496. // end catch_fatal_condition.cpp
  8497. // start catch_generators.cpp
  8498. // start catch_random_number_generator.h
  8499. #include <algorithm>
  8500. #include <random>
  8501. namespace Catch {
  8502. struct IConfig;
  8503. std::mt19937& rng();
  8504. void seedRng( IConfig const& config );
  8505. unsigned int rngSeed();
  8506. }
  8507. // end catch_random_number_generator.h
  8508. #include <limits>
  8509. #include <set>
  8510. namespace Catch {
  8511. IGeneratorTracker::~IGeneratorTracker() {}
  8512. const char* GeneratorException::what() const noexcept {
  8513. return m_msg;
  8514. }
  8515. namespace Generators {
  8516. GeneratorUntypedBase::~GeneratorUntypedBase() {}
  8517. auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
  8518. return getResultCapture().acquireGeneratorTracker( lineInfo );
  8519. }
  8520. } // namespace Generators
  8521. } // namespace Catch
  8522. // end catch_generators.cpp
  8523. // start catch_interfaces_capture.cpp
  8524. namespace Catch {
  8525. IResultCapture::~IResultCapture() = default;
  8526. }
  8527. // end catch_interfaces_capture.cpp
  8528. // start catch_interfaces_config.cpp
  8529. namespace Catch {
  8530. IConfig::~IConfig() = default;
  8531. }
  8532. // end catch_interfaces_config.cpp
  8533. // start catch_interfaces_exception.cpp
  8534. namespace Catch {
  8535. IExceptionTranslator::~IExceptionTranslator() = default;
  8536. IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() = default;
  8537. }
  8538. // end catch_interfaces_exception.cpp
  8539. // start catch_interfaces_registry_hub.cpp
  8540. namespace Catch {
  8541. IRegistryHub::~IRegistryHub() = default;
  8542. IMutableRegistryHub::~IMutableRegistryHub() = default;
  8543. }
  8544. // end catch_interfaces_registry_hub.cpp
  8545. // start catch_interfaces_reporter.cpp
  8546. // start catch_reporter_listening.h
  8547. namespace Catch {
  8548. class ListeningReporter : public IStreamingReporter {
  8549. using Reporters = std::vector<IStreamingReporterPtr>;
  8550. Reporters m_listeners;
  8551. IStreamingReporterPtr m_reporter = nullptr;
  8552. ReporterPreferences m_preferences;
  8553. public:
  8554. ListeningReporter();
  8555. void addListener( IStreamingReporterPtr&& listener );
  8556. void addReporter( IStreamingReporterPtr&& reporter );
  8557. public: // IStreamingReporter
  8558. ReporterPreferences getPreferences() const override;
  8559. void noMatchingTestCases( std::string const& spec ) override;
  8560. static std::set<Verbosity> getSupportedVerbosities();
  8561. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  8562. void benchmarkPreparing(std::string const& name) override;
  8563. void benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) override;
  8564. void benchmarkEnded( BenchmarkStats<> const& benchmarkStats ) override;
  8565. void benchmarkFailed(std::string const&) override;
  8566. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  8567. void testRunStarting( TestRunInfo const& testRunInfo ) override;
  8568. void testGroupStarting( GroupInfo const& groupInfo ) override;
  8569. void testCaseStarting( TestCaseInfo const& testInfo ) override;
  8570. void sectionStarting( SectionInfo const& sectionInfo ) override;
  8571. void assertionStarting( AssertionInfo const& assertionInfo ) override;
  8572. // The return value indicates if the messages buffer should be cleared:
  8573. bool assertionEnded( AssertionStats const& assertionStats ) override;
  8574. void sectionEnded( SectionStats const& sectionStats ) override;
  8575. void testCaseEnded( TestCaseStats const& testCaseStats ) override;
  8576. void testGroupEnded( TestGroupStats const& testGroupStats ) override;
  8577. void testRunEnded( TestRunStats const& testRunStats ) override;
  8578. void skipTest( TestCaseInfo const& testInfo ) override;
  8579. bool isMulti() const override;
  8580. };
  8581. } // end namespace Catch
  8582. // end catch_reporter_listening.h
  8583. namespace Catch {
  8584. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig )
  8585. : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {}
  8586. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream )
  8587. : m_stream( &_stream ), m_fullConfig( _fullConfig ) {}
  8588. std::ostream& ReporterConfig::stream() const { return *m_stream; }
  8589. IConfigPtr ReporterConfig::fullConfig() const { return m_fullConfig; }
  8590. TestRunInfo::TestRunInfo( std::string const& _name ) : name( _name ) {}
  8591. GroupInfo::GroupInfo( std::string const& _name,
  8592. std::size_t _groupIndex,
  8593. std::size_t _groupsCount )
  8594. : name( _name ),
  8595. groupIndex( _groupIndex ),
  8596. groupsCounts( _groupsCount )
  8597. {}
  8598. AssertionStats::AssertionStats( AssertionResult const& _assertionResult,
  8599. std::vector<MessageInfo> const& _infoMessages,
  8600. Totals const& _totals )
  8601. : assertionResult( _assertionResult ),
  8602. infoMessages( _infoMessages ),
  8603. totals( _totals )
  8604. {
  8605. assertionResult.m_resultData.lazyExpression.m_transientExpression = _assertionResult.m_resultData.lazyExpression.m_transientExpression;
  8606. if( assertionResult.hasMessage() ) {
  8607. // Copy message into messages list.
  8608. // !TBD This should have been done earlier, somewhere
  8609. MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() );
  8610. builder << assertionResult.getMessage();
  8611. builder.m_info.message = builder.m_stream.str();
  8612. infoMessages.push_back( builder.m_info );
  8613. }
  8614. }
  8615. AssertionStats::~AssertionStats() = default;
  8616. SectionStats::SectionStats( SectionInfo const& _sectionInfo,
  8617. Counts const& _assertions,
  8618. double _durationInSeconds,
  8619. bool _missingAssertions )
  8620. : sectionInfo( _sectionInfo ),
  8621. assertions( _assertions ),
  8622. durationInSeconds( _durationInSeconds ),
  8623. missingAssertions( _missingAssertions )
  8624. {}
  8625. SectionStats::~SectionStats() = default;
  8626. TestCaseStats::TestCaseStats( TestCaseInfo const& _testInfo,
  8627. Totals const& _totals,
  8628. std::string const& _stdOut,
  8629. std::string const& _stdErr,
  8630. bool _aborting )
  8631. : testInfo( _testInfo ),
  8632. totals( _totals ),
  8633. stdOut( _stdOut ),
  8634. stdErr( _stdErr ),
  8635. aborting( _aborting )
  8636. {}
  8637. TestCaseStats::~TestCaseStats() = default;
  8638. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo,
  8639. Totals const& _totals,
  8640. bool _aborting )
  8641. : groupInfo( _groupInfo ),
  8642. totals( _totals ),
  8643. aborting( _aborting )
  8644. {}
  8645. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo )
  8646. : groupInfo( _groupInfo ),
  8647. aborting( false )
  8648. {}
  8649. TestGroupStats::~TestGroupStats() = default;
  8650. TestRunStats::TestRunStats( TestRunInfo const& _runInfo,
  8651. Totals const& _totals,
  8652. bool _aborting )
  8653. : runInfo( _runInfo ),
  8654. totals( _totals ),
  8655. aborting( _aborting )
  8656. {}
  8657. TestRunStats::~TestRunStats() = default;
  8658. void IStreamingReporter::fatalErrorEncountered( StringRef ) {}
  8659. bool IStreamingReporter::isMulti() const { return false; }
  8660. IReporterFactory::~IReporterFactory() = default;
  8661. IReporterRegistry::~IReporterRegistry() = default;
  8662. } // end namespace Catch
  8663. // end catch_interfaces_reporter.cpp
  8664. // start catch_interfaces_runner.cpp
  8665. namespace Catch {
  8666. IRunner::~IRunner() = default;
  8667. }
  8668. // end catch_interfaces_runner.cpp
  8669. // start catch_interfaces_testcase.cpp
  8670. namespace Catch {
  8671. ITestInvoker::~ITestInvoker() = default;
  8672. ITestCaseRegistry::~ITestCaseRegistry() = default;
  8673. }
  8674. // end catch_interfaces_testcase.cpp
  8675. // start catch_leak_detector.cpp
  8676. #ifdef CATCH_CONFIG_WINDOWS_CRTDBG
  8677. #include <crtdbg.h>
  8678. namespace Catch {
  8679. LeakDetector::LeakDetector() {
  8680. int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
  8681. flag |= _CRTDBG_LEAK_CHECK_DF;
  8682. flag |= _CRTDBG_ALLOC_MEM_DF;
  8683. _CrtSetDbgFlag(flag);
  8684. _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
  8685. _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
  8686. // Change this to leaking allocation's number to break there
  8687. _CrtSetBreakAlloc(-1);
  8688. }
  8689. }
  8690. #else
  8691. Catch::LeakDetector::LeakDetector() {}
  8692. #endif
  8693. Catch::LeakDetector::~LeakDetector() {
  8694. Catch::cleanUp();
  8695. }
  8696. // end catch_leak_detector.cpp
  8697. // start catch_list.cpp
  8698. // start catch_list.h
  8699. #include <set>
  8700. namespace Catch {
  8701. std::size_t listTests( Config const& config );
  8702. std::size_t listTestsNamesOnly( Config const& config );
  8703. struct TagInfo {
  8704. void add( std::string const& spelling );
  8705. std::string all() const;
  8706. std::set<std::string> spellings;
  8707. std::size_t count = 0;
  8708. };
  8709. std::size_t listTags( Config const& config );
  8710. std::size_t listReporters();
  8711. Option<std::size_t> list( std::shared_ptr<Config> const& config );
  8712. } // end namespace Catch
  8713. // end catch_list.h
  8714. // start catch_text.h
  8715. namespace Catch {
  8716. using namespace clara::TextFlow;
  8717. }
  8718. // end catch_text.h
  8719. #include <limits>
  8720. #include <algorithm>
  8721. #include <iomanip>
  8722. namespace Catch {
  8723. std::size_t listTests( Config const& config ) {
  8724. TestSpec testSpec = config.testSpec();
  8725. if( config.hasTestFilters() )
  8726. Catch::cout() << "Matching test cases:\n";
  8727. else {
  8728. Catch::cout() << "All available test cases:\n";
  8729. }
  8730. auto matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  8731. for( auto const& testCaseInfo : matchedTestCases ) {
  8732. Colour::Code colour = testCaseInfo.isHidden()
  8733. ? Colour::SecondaryText
  8734. : Colour::None;
  8735. Colour colourGuard( colour );
  8736. Catch::cout() << Column( testCaseInfo.name ).initialIndent( 2 ).indent( 4 ) << "\n";
  8737. if( config.verbosity() >= Verbosity::High ) {
  8738. Catch::cout() << Column( Catch::Detail::stringify( testCaseInfo.lineInfo ) ).indent(4) << std::endl;
  8739. std::string description = testCaseInfo.description;
  8740. if( description.empty() )
  8741. description = "(NO DESCRIPTION)";
  8742. Catch::cout() << Column( description ).indent(4) << std::endl;
  8743. }
  8744. if( !testCaseInfo.tags.empty() )
  8745. Catch::cout() << Column( testCaseInfo.tagsAsString() ).indent( 6 ) << "\n";
  8746. }
  8747. if( !config.hasTestFilters() )
  8748. Catch::cout() << pluralise( matchedTestCases.size(), "test case" ) << '\n' << std::endl;
  8749. else
  8750. Catch::cout() << pluralise( matchedTestCases.size(), "matching test case" ) << '\n' << std::endl;
  8751. return matchedTestCases.size();
  8752. }
  8753. std::size_t listTestsNamesOnly( Config const& config ) {
  8754. TestSpec testSpec = config.testSpec();
  8755. std::size_t matchedTests = 0;
  8756. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  8757. for( auto const& testCaseInfo : matchedTestCases ) {
  8758. matchedTests++;
  8759. if( startsWith( testCaseInfo.name, '#' ) )
  8760. Catch::cout() << '"' << testCaseInfo.name << '"';
  8761. else
  8762. Catch::cout() << testCaseInfo.name;
  8763. if ( config.verbosity() >= Verbosity::High )
  8764. Catch::cout() << "\t@" << testCaseInfo.lineInfo;
  8765. Catch::cout() << std::endl;
  8766. }
  8767. return matchedTests;
  8768. }
  8769. void TagInfo::add( std::string const& spelling ) {
  8770. ++count;
  8771. spellings.insert( spelling );
  8772. }
  8773. std::string TagInfo::all() const {
  8774. std::string out;
  8775. for( auto const& spelling : spellings )
  8776. out += "[" + spelling + "]";
  8777. return out;
  8778. }
  8779. std::size_t listTags( Config const& config ) {
  8780. TestSpec testSpec = config.testSpec();
  8781. if( config.hasTestFilters() )
  8782. Catch::cout() << "Tags for matching test cases:\n";
  8783. else {
  8784. Catch::cout() << "All available tags:\n";
  8785. }
  8786. std::map<std::string, TagInfo> tagCounts;
  8787. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  8788. for( auto const& testCase : matchedTestCases ) {
  8789. for( auto const& tagName : testCase.getTestCaseInfo().tags ) {
  8790. std::string lcaseTagName = toLower( tagName );
  8791. auto countIt = tagCounts.find( lcaseTagName );
  8792. if( countIt == tagCounts.end() )
  8793. countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first;
  8794. countIt->second.add( tagName );
  8795. }
  8796. }
  8797. for( auto const& tagCount : tagCounts ) {
  8798. ReusableStringStream rss;
  8799. rss << " " << std::setw(2) << tagCount.second.count << " ";
  8800. auto str = rss.str();
  8801. auto wrapper = Column( tagCount.second.all() )
  8802. .initialIndent( 0 )
  8803. .indent( str.size() )
  8804. .width( CATCH_CONFIG_CONSOLE_WIDTH-10 );
  8805. Catch::cout() << str << wrapper << '\n';
  8806. }
  8807. Catch::cout() << pluralise( tagCounts.size(), "tag" ) << '\n' << std::endl;
  8808. return tagCounts.size();
  8809. }
  8810. std::size_t listReporters() {
  8811. Catch::cout() << "Available reporters:\n";
  8812. IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
  8813. std::size_t maxNameLen = 0;
  8814. for( auto const& factoryKvp : factories )
  8815. maxNameLen = (std::max)( maxNameLen, factoryKvp.first.size() );
  8816. for( auto const& factoryKvp : factories ) {
  8817. Catch::cout()
  8818. << Column( factoryKvp.first + ":" )
  8819. .indent(2)
  8820. .width( 5+maxNameLen )
  8821. + Column( factoryKvp.second->getDescription() )
  8822. .initialIndent(0)
  8823. .indent(2)
  8824. .width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 )
  8825. << "\n";
  8826. }
  8827. Catch::cout() << std::endl;
  8828. return factories.size();
  8829. }
  8830. Option<std::size_t> list( std::shared_ptr<Config> const& config ) {
  8831. Option<std::size_t> listedCount;
  8832. getCurrentMutableContext().setConfig( config );
  8833. if( config->listTests() )
  8834. listedCount = listedCount.valueOr(0) + listTests( *config );
  8835. if( config->listTestNamesOnly() )
  8836. listedCount = listedCount.valueOr(0) + listTestsNamesOnly( *config );
  8837. if( config->listTags() )
  8838. listedCount = listedCount.valueOr(0) + listTags( *config );
  8839. if( config->listReporters() )
  8840. listedCount = listedCount.valueOr(0) + listReporters();
  8841. return listedCount;
  8842. }
  8843. } // end namespace Catch
  8844. // end catch_list.cpp
  8845. // start catch_matchers.cpp
  8846. namespace Catch {
  8847. namespace Matchers {
  8848. namespace Impl {
  8849. std::string MatcherUntypedBase::toString() const {
  8850. if( m_cachedToString.empty() )
  8851. m_cachedToString = describe();
  8852. return m_cachedToString;
  8853. }
  8854. MatcherUntypedBase::~MatcherUntypedBase() = default;
  8855. } // namespace Impl
  8856. } // namespace Matchers
  8857. using namespace Matchers;
  8858. using Matchers::Impl::MatcherBase;
  8859. } // namespace Catch
  8860. // end catch_matchers.cpp
  8861. // start catch_matchers_floating.cpp
  8862. // start catch_polyfills.hpp
  8863. namespace Catch {
  8864. bool isnan(float f);
  8865. bool isnan(double d);
  8866. }
  8867. // end catch_polyfills.hpp
  8868. // start catch_to_string.hpp
  8869. #include <string>
  8870. namespace Catch {
  8871. template <typename T>
  8872. std::string to_string(T const& t) {
  8873. #if defined(CATCH_CONFIG_CPP11_TO_STRING)
  8874. return std::to_string(t);
  8875. #else
  8876. ReusableStringStream rss;
  8877. rss << t;
  8878. return rss.str();
  8879. #endif
  8880. }
  8881. } // end namespace Catch
  8882. // end catch_to_string.hpp
  8883. #include <cstdlib>
  8884. #include <cstdint>
  8885. #include <cstring>
  8886. #include <sstream>
  8887. #include <iomanip>
  8888. #include <limits>
  8889. namespace Catch {
  8890. namespace Matchers {
  8891. namespace Floating {
  8892. enum class FloatingPointKind : uint8_t {
  8893. Float,
  8894. Double
  8895. };
  8896. }
  8897. }
  8898. }
  8899. namespace {
  8900. template <typename T>
  8901. struct Converter;
  8902. template <>
  8903. struct Converter<float> {
  8904. static_assert(sizeof(float) == sizeof(int32_t), "Important ULP matcher assumption violated");
  8905. Converter(float f) {
  8906. std::memcpy(&i, &f, sizeof(f));
  8907. }
  8908. int32_t i;
  8909. };
  8910. template <>
  8911. struct Converter<double> {
  8912. static_assert(sizeof(double) == sizeof(int64_t), "Important ULP matcher assumption violated");
  8913. Converter(double d) {
  8914. std::memcpy(&i, &d, sizeof(d));
  8915. }
  8916. int64_t i;
  8917. };
  8918. template <typename T>
  8919. auto convert(T t) -> Converter<T> {
  8920. return Converter<T>(t);
  8921. }
  8922. template <typename FP>
  8923. bool almostEqualUlps(FP lhs, FP rhs, int maxUlpDiff) {
  8924. // Comparison with NaN should always be false.
  8925. // This way we can rule it out before getting into the ugly details
  8926. if (Catch::isnan(lhs) || Catch::isnan(rhs)) {
  8927. return false;
  8928. }
  8929. auto lc = convert(lhs);
  8930. auto rc = convert(rhs);
  8931. if ((lc.i < 0) != (rc.i < 0)) {
  8932. // Potentially we can have +0 and -0
  8933. return lhs == rhs;
  8934. }
  8935. auto ulpDiff = std::abs(lc.i - rc.i);
  8936. return ulpDiff <= maxUlpDiff;
  8937. }
  8938. template <typename FP>
  8939. FP step(FP start, FP direction, int steps) {
  8940. for (int i = 0; i < steps; ++i) {
  8941. start = std::nextafter(start, direction);
  8942. }
  8943. return start;
  8944. }
  8945. } // end anonymous namespace
  8946. namespace Catch {
  8947. namespace Matchers {
  8948. namespace Floating {
  8949. WithinAbsMatcher::WithinAbsMatcher(double target, double margin)
  8950. :m_target{ target }, m_margin{ margin } {
  8951. CATCH_ENFORCE(margin >= 0, "Invalid margin: " << margin << '.'
  8952. << " Margin has to be non-negative.");
  8953. }
  8954. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  8955. // But without the subtraction to allow for INFINITY in comparison
  8956. bool WithinAbsMatcher::match(double const& matchee) const {
  8957. return (matchee + m_margin >= m_target) && (m_target + m_margin >= matchee);
  8958. }
  8959. std::string WithinAbsMatcher::describe() const {
  8960. return "is within " + ::Catch::Detail::stringify(m_margin) + " of " + ::Catch::Detail::stringify(m_target);
  8961. }
  8962. WithinUlpsMatcher::WithinUlpsMatcher(double target, int ulps, FloatingPointKind baseType)
  8963. :m_target{ target }, m_ulps{ ulps }, m_type{ baseType } {
  8964. CATCH_ENFORCE(ulps >= 0, "Invalid ULP setting: " << ulps << '.'
  8965. << " ULPs have to be non-negative.");
  8966. }
  8967. #if defined(__clang__)
  8968. #pragma clang diagnostic push
  8969. // Clang <3.5 reports on the default branch in the switch below
  8970. #pragma clang diagnostic ignored "-Wunreachable-code"
  8971. #endif
  8972. bool WithinUlpsMatcher::match(double const& matchee) const {
  8973. switch (m_type) {
  8974. case FloatingPointKind::Float:
  8975. return almostEqualUlps<float>(static_cast<float>(matchee), static_cast<float>(m_target), m_ulps);
  8976. case FloatingPointKind::Double:
  8977. return almostEqualUlps<double>(matchee, m_target, m_ulps);
  8978. default:
  8979. CATCH_INTERNAL_ERROR( "Unknown FloatingPointKind value" );
  8980. }
  8981. }
  8982. #if defined(__clang__)
  8983. #pragma clang diagnostic pop
  8984. #endif
  8985. std::string WithinUlpsMatcher::describe() const {
  8986. std::stringstream ret;
  8987. ret << "is within " << m_ulps << " ULPs of " << ::Catch::Detail::stringify(m_target);
  8988. if (m_type == FloatingPointKind::Float) {
  8989. ret << 'f';
  8990. }
  8991. ret << " ([";
  8992. ret << std::fixed << std::setprecision(std::numeric_limits<double>::max_digits10);
  8993. if (m_type == FloatingPointKind::Double) {
  8994. ret << step(m_target, static_cast<double>(-INFINITY), m_ulps)
  8995. << ", "
  8996. << step(m_target, static_cast<double>(INFINITY), m_ulps);
  8997. } else {
  8998. ret << step<float>(static_cast<float>(m_target), -INFINITY, m_ulps)
  8999. << ", "
  9000. << step<float>(static_cast<float>(m_target), INFINITY, m_ulps);
  9001. }
  9002. ret << "])";
  9003. return ret.str();
  9004. //return "is within " + Catch::to_string(m_ulps) + " ULPs of " + ::Catch::Detail::stringify(m_target) + ((m_type == FloatingPointKind::Float)? "f" : "");
  9005. }
  9006. }// namespace Floating
  9007. Floating::WithinUlpsMatcher WithinULP(double target, int maxUlpDiff) {
  9008. return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Double);
  9009. }
  9010. Floating::WithinUlpsMatcher WithinULP(float target, int maxUlpDiff) {
  9011. return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Float);
  9012. }
  9013. Floating::WithinAbsMatcher WithinAbs(double target, double margin) {
  9014. return Floating::WithinAbsMatcher(target, margin);
  9015. }
  9016. } // namespace Matchers
  9017. } // namespace Catch
  9018. // end catch_matchers_floating.cpp
  9019. // start catch_matchers_generic.cpp
  9020. std::string Catch::Matchers::Generic::Detail::finalizeDescription(const std::string& desc) {
  9021. if (desc.empty()) {
  9022. return "matches undescribed predicate";
  9023. } else {
  9024. return "matches predicate: \"" + desc + '"';
  9025. }
  9026. }
  9027. // end catch_matchers_generic.cpp
  9028. // start catch_matchers_string.cpp
  9029. #include <regex>
  9030. namespace Catch {
  9031. namespace Matchers {
  9032. namespace StdString {
  9033. CasedString::CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity )
  9034. : m_caseSensitivity( caseSensitivity ),
  9035. m_str( adjustString( str ) )
  9036. {}
  9037. std::string CasedString::adjustString( std::string const& str ) const {
  9038. return m_caseSensitivity == CaseSensitive::No
  9039. ? toLower( str )
  9040. : str;
  9041. }
  9042. std::string CasedString::caseSensitivitySuffix() const {
  9043. return m_caseSensitivity == CaseSensitive::No
  9044. ? " (case insensitive)"
  9045. : std::string();
  9046. }
  9047. StringMatcherBase::StringMatcherBase( std::string const& operation, CasedString const& comparator )
  9048. : m_comparator( comparator ),
  9049. m_operation( operation ) {
  9050. }
  9051. std::string StringMatcherBase::describe() const {
  9052. std::string description;
  9053. description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
  9054. m_comparator.caseSensitivitySuffix().size());
  9055. description += m_operation;
  9056. description += ": \"";
  9057. description += m_comparator.m_str;
  9058. description += "\"";
  9059. description += m_comparator.caseSensitivitySuffix();
  9060. return description;
  9061. }
  9062. EqualsMatcher::EqualsMatcher( CasedString const& comparator ) : StringMatcherBase( "equals", comparator ) {}
  9063. bool EqualsMatcher::match( std::string const& source ) const {
  9064. return m_comparator.adjustString( source ) == m_comparator.m_str;
  9065. }
  9066. ContainsMatcher::ContainsMatcher( CasedString const& comparator ) : StringMatcherBase( "contains", comparator ) {}
  9067. bool ContainsMatcher::match( std::string const& source ) const {
  9068. return contains( m_comparator.adjustString( source ), m_comparator.m_str );
  9069. }
  9070. StartsWithMatcher::StartsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "starts with", comparator ) {}
  9071. bool StartsWithMatcher::match( std::string const& source ) const {
  9072. return startsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  9073. }
  9074. EndsWithMatcher::EndsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "ends with", comparator ) {}
  9075. bool EndsWithMatcher::match( std::string const& source ) const {
  9076. return endsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  9077. }
  9078. RegexMatcher::RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity): m_regex(std::move(regex)), m_caseSensitivity(caseSensitivity) {}
  9079. bool RegexMatcher::match(std::string const& matchee) const {
  9080. auto flags = std::regex::ECMAScript; // ECMAScript is the default syntax option anyway
  9081. if (m_caseSensitivity == CaseSensitive::Choice::No) {
  9082. flags |= std::regex::icase;
  9083. }
  9084. auto reg = std::regex(m_regex, flags);
  9085. return std::regex_match(matchee, reg);
  9086. }
  9087. std::string RegexMatcher::describe() const {
  9088. return "matches " + ::Catch::Detail::stringify(m_regex) + ((m_caseSensitivity == CaseSensitive::Choice::Yes)? " case sensitively" : " case insensitively");
  9089. }
  9090. } // namespace StdString
  9091. StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  9092. return StdString::EqualsMatcher( StdString::CasedString( str, caseSensitivity) );
  9093. }
  9094. StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  9095. return StdString::ContainsMatcher( StdString::CasedString( str, caseSensitivity) );
  9096. }
  9097. StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  9098. return StdString::EndsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  9099. }
  9100. StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  9101. return StdString::StartsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  9102. }
  9103. StdString::RegexMatcher Matches(std::string const& regex, CaseSensitive::Choice caseSensitivity) {
  9104. return StdString::RegexMatcher(regex, caseSensitivity);
  9105. }
  9106. } // namespace Matchers
  9107. } // namespace Catch
  9108. // end catch_matchers_string.cpp
  9109. // start catch_message.cpp
  9110. // start catch_uncaught_exceptions.h
  9111. namespace Catch {
  9112. bool uncaught_exceptions();
  9113. } // end namespace Catch
  9114. // end catch_uncaught_exceptions.h
  9115. #include <cassert>
  9116. #include <stack>
  9117. namespace Catch {
  9118. MessageInfo::MessageInfo( StringRef const& _macroName,
  9119. SourceLineInfo const& _lineInfo,
  9120. ResultWas::OfType _type )
  9121. : macroName( _macroName ),
  9122. lineInfo( _lineInfo ),
  9123. type( _type ),
  9124. sequence( ++globalCount )
  9125. {}
  9126. bool MessageInfo::operator==( MessageInfo const& other ) const {
  9127. return sequence == other.sequence;
  9128. }
  9129. bool MessageInfo::operator<( MessageInfo const& other ) const {
  9130. return sequence < other.sequence;
  9131. }
  9132. // This may need protecting if threading support is added
  9133. unsigned int MessageInfo::globalCount = 0;
  9134. ////////////////////////////////////////////////////////////////////////////
  9135. Catch::MessageBuilder::MessageBuilder( StringRef const& macroName,
  9136. SourceLineInfo const& lineInfo,
  9137. ResultWas::OfType type )
  9138. :m_info(macroName, lineInfo, type) {}
  9139. ////////////////////////////////////////////////////////////////////////////
  9140. ScopedMessage::ScopedMessage( MessageBuilder const& builder )
  9141. : m_info( builder.m_info ), m_moved()
  9142. {
  9143. m_info.message = builder.m_stream.str();
  9144. getResultCapture().pushScopedMessage( m_info );
  9145. }
  9146. ScopedMessage::ScopedMessage( ScopedMessage&& old )
  9147. : m_info( old.m_info ), m_moved()
  9148. {
  9149. old.m_moved = true;
  9150. }
  9151. ScopedMessage::~ScopedMessage() {
  9152. if ( !uncaught_exceptions() && !m_moved ){
  9153. getResultCapture().popScopedMessage(m_info);
  9154. }
  9155. }
  9156. Capturer::Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names ) {
  9157. auto trimmed = [&] (size_t start, size_t end) {
  9158. while (names[start] == ',' || isspace(names[start])) {
  9159. ++start;
  9160. }
  9161. while (names[end] == ',' || isspace(names[end])) {
  9162. --end;
  9163. }
  9164. return names.substr(start, end - start + 1);
  9165. };
  9166. auto skipq = [&] (size_t start, char quote) {
  9167. for (auto i = start + 1; i < names.size() ; ++i) {
  9168. if (names[i] == quote)
  9169. return i;
  9170. if (names[i] == '\\')
  9171. ++i;
  9172. }
  9173. CATCH_INTERNAL_ERROR("CAPTURE parsing encountered unmatched quote");
  9174. };
  9175. size_t start = 0;
  9176. std::stack<char> openings;
  9177. for (size_t pos = 0; pos < names.size(); ++pos) {
  9178. char c = names[pos];
  9179. switch (c) {
  9180. case '[':
  9181. case '{':
  9182. case '(':
  9183. // It is basically impossible to disambiguate between
  9184. // comparison and start of template args in this context
  9185. // case '<':
  9186. openings.push(c);
  9187. break;
  9188. case ']':
  9189. case '}':
  9190. case ')':
  9191. // case '>':
  9192. openings.pop();
  9193. break;
  9194. case '"':
  9195. case '\'':
  9196. pos = skipq(pos, c);
  9197. break;
  9198. case ',':
  9199. if (start != pos && openings.size() == 0) {
  9200. m_messages.emplace_back(macroName, lineInfo, resultType);
  9201. m_messages.back().message = trimmed(start, pos);
  9202. m_messages.back().message += " := ";
  9203. start = pos;
  9204. }
  9205. }
  9206. }
  9207. assert(openings.size() == 0 && "Mismatched openings");
  9208. m_messages.emplace_back(macroName, lineInfo, resultType);
  9209. m_messages.back().message = trimmed(start, names.size() - 1);
  9210. m_messages.back().message += " := ";
  9211. }
  9212. Capturer::~Capturer() {
  9213. if ( !uncaught_exceptions() ){
  9214. assert( m_captured == m_messages.size() );
  9215. for( size_t i = 0; i < m_captured; ++i )
  9216. m_resultCapture.popScopedMessage( m_messages[i] );
  9217. }
  9218. }
  9219. void Capturer::captureValue( size_t index, std::string const& value ) {
  9220. assert( index < m_messages.size() );
  9221. m_messages[index].message += value;
  9222. m_resultCapture.pushScopedMessage( m_messages[index] );
  9223. m_captured++;
  9224. }
  9225. } // end namespace Catch
  9226. // end catch_message.cpp
  9227. // start catch_output_redirect.cpp
  9228. // start catch_output_redirect.h
  9229. #ifndef TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  9230. #define TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  9231. #include <cstdio>
  9232. #include <iosfwd>
  9233. #include <string>
  9234. namespace Catch {
  9235. class RedirectedStream {
  9236. std::ostream& m_originalStream;
  9237. std::ostream& m_redirectionStream;
  9238. std::streambuf* m_prevBuf;
  9239. public:
  9240. RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream );
  9241. ~RedirectedStream();
  9242. };
  9243. class RedirectedStdOut {
  9244. ReusableStringStream m_rss;
  9245. RedirectedStream m_cout;
  9246. public:
  9247. RedirectedStdOut();
  9248. auto str() const -> std::string;
  9249. };
  9250. // StdErr has two constituent streams in C++, std::cerr and std::clog
  9251. // This means that we need to redirect 2 streams into 1 to keep proper
  9252. // order of writes
  9253. class RedirectedStdErr {
  9254. ReusableStringStream m_rss;
  9255. RedirectedStream m_cerr;
  9256. RedirectedStream m_clog;
  9257. public:
  9258. RedirectedStdErr();
  9259. auto str() const -> std::string;
  9260. };
  9261. class RedirectedStreams {
  9262. public:
  9263. RedirectedStreams(RedirectedStreams const&) = delete;
  9264. RedirectedStreams& operator=(RedirectedStreams const&) = delete;
  9265. RedirectedStreams(RedirectedStreams&&) = delete;
  9266. RedirectedStreams& operator=(RedirectedStreams&&) = delete;
  9267. RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr);
  9268. ~RedirectedStreams();
  9269. private:
  9270. std::string& m_redirectedCout;
  9271. std::string& m_redirectedCerr;
  9272. RedirectedStdOut m_redirectedStdOut;
  9273. RedirectedStdErr m_redirectedStdErr;
  9274. };
  9275. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  9276. // Windows's implementation of std::tmpfile is terrible (it tries
  9277. // to create a file inside system folder, thus requiring elevated
  9278. // privileges for the binary), so we have to use tmpnam(_s) and
  9279. // create the file ourselves there.
  9280. class TempFile {
  9281. public:
  9282. TempFile(TempFile const&) = delete;
  9283. TempFile& operator=(TempFile const&) = delete;
  9284. TempFile(TempFile&&) = delete;
  9285. TempFile& operator=(TempFile&&) = delete;
  9286. TempFile();
  9287. ~TempFile();
  9288. std::FILE* getFile();
  9289. std::string getContents();
  9290. private:
  9291. std::FILE* m_file = nullptr;
  9292. #if defined(_MSC_VER)
  9293. char m_buffer[L_tmpnam] = { 0 };
  9294. #endif
  9295. };
  9296. class OutputRedirect {
  9297. public:
  9298. OutputRedirect(OutputRedirect const&) = delete;
  9299. OutputRedirect& operator=(OutputRedirect const&) = delete;
  9300. OutputRedirect(OutputRedirect&&) = delete;
  9301. OutputRedirect& operator=(OutputRedirect&&) = delete;
  9302. OutputRedirect(std::string& stdout_dest, std::string& stderr_dest);
  9303. ~OutputRedirect();
  9304. private:
  9305. int m_originalStdout = -1;
  9306. int m_originalStderr = -1;
  9307. TempFile m_stdoutFile;
  9308. TempFile m_stderrFile;
  9309. std::string& m_stdoutDest;
  9310. std::string& m_stderrDest;
  9311. };
  9312. #endif
  9313. } // end namespace Catch
  9314. #endif // TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  9315. // end catch_output_redirect.h
  9316. #include <cstdio>
  9317. #include <cstring>
  9318. #include <fstream>
  9319. #include <sstream>
  9320. #include <stdexcept>
  9321. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  9322. #if defined(_MSC_VER)
  9323. #include <io.h> //_dup and _dup2
  9324. #define dup _dup
  9325. #define dup2 _dup2
  9326. #define fileno _fileno
  9327. #else
  9328. #include <unistd.h> // dup and dup2
  9329. #endif
  9330. #endif
  9331. namespace Catch {
  9332. RedirectedStream::RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream )
  9333. : m_originalStream( originalStream ),
  9334. m_redirectionStream( redirectionStream ),
  9335. m_prevBuf( m_originalStream.rdbuf() )
  9336. {
  9337. m_originalStream.rdbuf( m_redirectionStream.rdbuf() );
  9338. }
  9339. RedirectedStream::~RedirectedStream() {
  9340. m_originalStream.rdbuf( m_prevBuf );
  9341. }
  9342. RedirectedStdOut::RedirectedStdOut() : m_cout( Catch::cout(), m_rss.get() ) {}
  9343. auto RedirectedStdOut::str() const -> std::string { return m_rss.str(); }
  9344. RedirectedStdErr::RedirectedStdErr()
  9345. : m_cerr( Catch::cerr(), m_rss.get() ),
  9346. m_clog( Catch::clog(), m_rss.get() )
  9347. {}
  9348. auto RedirectedStdErr::str() const -> std::string { return m_rss.str(); }
  9349. RedirectedStreams::RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr)
  9350. : m_redirectedCout(redirectedCout),
  9351. m_redirectedCerr(redirectedCerr)
  9352. {}
  9353. RedirectedStreams::~RedirectedStreams() {
  9354. m_redirectedCout += m_redirectedStdOut.str();
  9355. m_redirectedCerr += m_redirectedStdErr.str();
  9356. }
  9357. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  9358. #if defined(_MSC_VER)
  9359. TempFile::TempFile() {
  9360. if (tmpnam_s(m_buffer)) {
  9361. CATCH_RUNTIME_ERROR("Could not get a temp filename");
  9362. }
  9363. if (fopen_s(&m_file, m_buffer, "w")) {
  9364. char buffer[100];
  9365. if (strerror_s(buffer, errno)) {
  9366. CATCH_RUNTIME_ERROR("Could not translate errno to a string");
  9367. }
  9368. CATCH_RUNTIME_ERROR("Could not open the temp file: '" << m_buffer << "' because: " << buffer);
  9369. }
  9370. }
  9371. #else
  9372. TempFile::TempFile() {
  9373. m_file = std::tmpfile();
  9374. if (!m_file) {
  9375. CATCH_RUNTIME_ERROR("Could not create a temp file.");
  9376. }
  9377. }
  9378. #endif
  9379. TempFile::~TempFile() {
  9380. // TBD: What to do about errors here?
  9381. std::fclose(m_file);
  9382. // We manually create the file on Windows only, on Linux
  9383. // it will be autodeleted
  9384. #if defined(_MSC_VER)
  9385. std::remove(m_buffer);
  9386. #endif
  9387. }
  9388. FILE* TempFile::getFile() {
  9389. return m_file;
  9390. }
  9391. std::string TempFile::getContents() {
  9392. std::stringstream sstr;
  9393. char buffer[100] = {};
  9394. std::rewind(m_file);
  9395. while (std::fgets(buffer, sizeof(buffer), m_file)) {
  9396. sstr << buffer;
  9397. }
  9398. return sstr.str();
  9399. }
  9400. OutputRedirect::OutputRedirect(std::string& stdout_dest, std::string& stderr_dest) :
  9401. m_originalStdout(dup(1)),
  9402. m_originalStderr(dup(2)),
  9403. m_stdoutDest(stdout_dest),
  9404. m_stderrDest(stderr_dest) {
  9405. dup2(fileno(m_stdoutFile.getFile()), 1);
  9406. dup2(fileno(m_stderrFile.getFile()), 2);
  9407. }
  9408. OutputRedirect::~OutputRedirect() {
  9409. Catch::cout() << std::flush;
  9410. fflush(stdout);
  9411. // Since we support overriding these streams, we flush cerr
  9412. // even though std::cerr is unbuffered
  9413. Catch::cerr() << std::flush;
  9414. Catch::clog() << std::flush;
  9415. fflush(stderr);
  9416. dup2(m_originalStdout, 1);
  9417. dup2(m_originalStderr, 2);
  9418. m_stdoutDest += m_stdoutFile.getContents();
  9419. m_stderrDest += m_stderrFile.getContents();
  9420. }
  9421. #endif // CATCH_CONFIG_NEW_CAPTURE
  9422. } // namespace Catch
  9423. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  9424. #if defined(_MSC_VER)
  9425. #undef dup
  9426. #undef dup2
  9427. #undef fileno
  9428. #endif
  9429. #endif
  9430. // end catch_output_redirect.cpp
  9431. // start catch_polyfills.cpp
  9432. #include <cmath>
  9433. namespace Catch {
  9434. #if !defined(CATCH_CONFIG_POLYFILL_ISNAN)
  9435. bool isnan(float f) {
  9436. return std::isnan(f);
  9437. }
  9438. bool isnan(double d) {
  9439. return std::isnan(d);
  9440. }
  9441. #else
  9442. // For now we only use this for embarcadero
  9443. bool isnan(float f) {
  9444. return std::_isnan(f);
  9445. }
  9446. bool isnan(double d) {
  9447. return std::_isnan(d);
  9448. }
  9449. #endif
  9450. } // end namespace Catch
  9451. // end catch_polyfills.cpp
  9452. // start catch_random_number_generator.cpp
  9453. namespace Catch {
  9454. std::mt19937& rng() {
  9455. static std::mt19937 s_rng;
  9456. return s_rng;
  9457. }
  9458. void seedRng( IConfig const& config ) {
  9459. if( config.rngSeed() != 0 ) {
  9460. std::srand( config.rngSeed() );
  9461. rng().seed( config.rngSeed() );
  9462. }
  9463. }
  9464. unsigned int rngSeed() {
  9465. return getCurrentContext().getConfig()->rngSeed();
  9466. }
  9467. }
  9468. // end catch_random_number_generator.cpp
  9469. // start catch_registry_hub.cpp
  9470. // start catch_test_case_registry_impl.h
  9471. #include <vector>
  9472. #include <set>
  9473. #include <algorithm>
  9474. #include <ios>
  9475. namespace Catch {
  9476. class TestCase;
  9477. struct IConfig;
  9478. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases );
  9479. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
  9480. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions );
  9481. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
  9482. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
  9483. class TestRegistry : public ITestCaseRegistry {
  9484. public:
  9485. virtual ~TestRegistry() = default;
  9486. virtual void registerTest( TestCase const& testCase );
  9487. std::vector<TestCase> const& getAllTests() const override;
  9488. std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const override;
  9489. private:
  9490. std::vector<TestCase> m_functions;
  9491. mutable RunTests::InWhatOrder m_currentSortOrder = RunTests::InDeclarationOrder;
  9492. mutable std::vector<TestCase> m_sortedFunctions;
  9493. std::size_t m_unnamedCount = 0;
  9494. std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised
  9495. };
  9496. ///////////////////////////////////////////////////////////////////////////
  9497. class TestInvokerAsFunction : public ITestInvoker {
  9498. void(*m_testAsFunction)();
  9499. public:
  9500. TestInvokerAsFunction( void(*testAsFunction)() ) noexcept;
  9501. void invoke() const override;
  9502. };
  9503. std::string extractClassName( StringRef const& classOrQualifiedMethodName );
  9504. ///////////////////////////////////////////////////////////////////////////
  9505. } // end namespace Catch
  9506. // end catch_test_case_registry_impl.h
  9507. // start catch_reporter_registry.h
  9508. #include <map>
  9509. namespace Catch {
  9510. class ReporterRegistry : public IReporterRegistry {
  9511. public:
  9512. ~ReporterRegistry() override;
  9513. IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const override;
  9514. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory );
  9515. void registerListener( IReporterFactoryPtr const& factory );
  9516. FactoryMap const& getFactories() const override;
  9517. Listeners const& getListeners() const override;
  9518. private:
  9519. FactoryMap m_factories;
  9520. Listeners m_listeners;
  9521. };
  9522. }
  9523. // end catch_reporter_registry.h
  9524. // start catch_tag_alias_registry.h
  9525. // start catch_tag_alias.h
  9526. #include <string>
  9527. namespace Catch {
  9528. struct TagAlias {
  9529. TagAlias(std::string const& _tag, SourceLineInfo _lineInfo);
  9530. std::string tag;
  9531. SourceLineInfo lineInfo;
  9532. };
  9533. } // end namespace Catch
  9534. // end catch_tag_alias.h
  9535. #include <map>
  9536. namespace Catch {
  9537. class TagAliasRegistry : public ITagAliasRegistry {
  9538. public:
  9539. ~TagAliasRegistry() override;
  9540. TagAlias const* find( std::string const& alias ) const override;
  9541. std::string expandAliases( std::string const& unexpandedTestSpec ) const override;
  9542. void add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo );
  9543. private:
  9544. std::map<std::string, TagAlias> m_registry;
  9545. };
  9546. } // end namespace Catch
  9547. // end catch_tag_alias_registry.h
  9548. // start catch_startup_exception_registry.h
  9549. #include <vector>
  9550. #include <exception>
  9551. namespace Catch {
  9552. class StartupExceptionRegistry {
  9553. public:
  9554. void add(std::exception_ptr const& exception) noexcept;
  9555. std::vector<std::exception_ptr> const& getExceptions() const noexcept;
  9556. private:
  9557. std::vector<std::exception_ptr> m_exceptions;
  9558. };
  9559. } // end namespace Catch
  9560. // end catch_startup_exception_registry.h
  9561. // start catch_singletons.hpp
  9562. namespace Catch {
  9563. struct ISingleton {
  9564. virtual ~ISingleton();
  9565. };
  9566. void addSingleton( ISingleton* singleton );
  9567. void cleanupSingletons();
  9568. template<typename SingletonImplT, typename InterfaceT = SingletonImplT, typename MutableInterfaceT = InterfaceT>
  9569. class Singleton : SingletonImplT, public ISingleton {
  9570. static auto getInternal() -> Singleton* {
  9571. static Singleton* s_instance = nullptr;
  9572. if( !s_instance ) {
  9573. s_instance = new Singleton;
  9574. addSingleton( s_instance );
  9575. }
  9576. return s_instance;
  9577. }
  9578. public:
  9579. static auto get() -> InterfaceT const& {
  9580. return *getInternal();
  9581. }
  9582. static auto getMutable() -> MutableInterfaceT& {
  9583. return *getInternal();
  9584. }
  9585. };
  9586. } // namespace Catch
  9587. // end catch_singletons.hpp
  9588. namespace Catch {
  9589. namespace {
  9590. class RegistryHub : public IRegistryHub, public IMutableRegistryHub,
  9591. private NonCopyable {
  9592. public: // IRegistryHub
  9593. RegistryHub() = default;
  9594. IReporterRegistry const& getReporterRegistry() const override {
  9595. return m_reporterRegistry;
  9596. }
  9597. ITestCaseRegistry const& getTestCaseRegistry() const override {
  9598. return m_testCaseRegistry;
  9599. }
  9600. IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const override {
  9601. return m_exceptionTranslatorRegistry;
  9602. }
  9603. ITagAliasRegistry const& getTagAliasRegistry() const override {
  9604. return m_tagAliasRegistry;
  9605. }
  9606. StartupExceptionRegistry const& getStartupExceptionRegistry() const override {
  9607. return m_exceptionRegistry;
  9608. }
  9609. public: // IMutableRegistryHub
  9610. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) override {
  9611. m_reporterRegistry.registerReporter( name, factory );
  9612. }
  9613. void registerListener( IReporterFactoryPtr const& factory ) override {
  9614. m_reporterRegistry.registerListener( factory );
  9615. }
  9616. void registerTest( TestCase const& testInfo ) override {
  9617. m_testCaseRegistry.registerTest( testInfo );
  9618. }
  9619. void registerTranslator( const IExceptionTranslator* translator ) override {
  9620. m_exceptionTranslatorRegistry.registerTranslator( translator );
  9621. }
  9622. void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) override {
  9623. m_tagAliasRegistry.add( alias, tag, lineInfo );
  9624. }
  9625. void registerStartupException() noexcept override {
  9626. m_exceptionRegistry.add(std::current_exception());
  9627. }
  9628. IMutableEnumValuesRegistry& getMutableEnumValuesRegistry() override {
  9629. return m_enumValuesRegistry;
  9630. }
  9631. private:
  9632. TestRegistry m_testCaseRegistry;
  9633. ReporterRegistry m_reporterRegistry;
  9634. ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
  9635. TagAliasRegistry m_tagAliasRegistry;
  9636. StartupExceptionRegistry m_exceptionRegistry;
  9637. Detail::EnumValuesRegistry m_enumValuesRegistry;
  9638. };
  9639. }
  9640. using RegistryHubSingleton = Singleton<RegistryHub, IRegistryHub, IMutableRegistryHub>;
  9641. IRegistryHub const& getRegistryHub() {
  9642. return RegistryHubSingleton::get();
  9643. }
  9644. IMutableRegistryHub& getMutableRegistryHub() {
  9645. return RegistryHubSingleton::getMutable();
  9646. }
  9647. void cleanUp() {
  9648. cleanupSingletons();
  9649. cleanUpContext();
  9650. }
  9651. std::string translateActiveException() {
  9652. return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException();
  9653. }
  9654. } // end namespace Catch
  9655. // end catch_registry_hub.cpp
  9656. // start catch_reporter_registry.cpp
  9657. namespace Catch {
  9658. ReporterRegistry::~ReporterRegistry() = default;
  9659. IStreamingReporterPtr ReporterRegistry::create( std::string const& name, IConfigPtr const& config ) const {
  9660. auto it = m_factories.find( name );
  9661. if( it == m_factories.end() )
  9662. return nullptr;
  9663. return it->second->create( ReporterConfig( config ) );
  9664. }
  9665. void ReporterRegistry::registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) {
  9666. m_factories.emplace(name, factory);
  9667. }
  9668. void ReporterRegistry::registerListener( IReporterFactoryPtr const& factory ) {
  9669. m_listeners.push_back( factory );
  9670. }
  9671. IReporterRegistry::FactoryMap const& ReporterRegistry::getFactories() const {
  9672. return m_factories;
  9673. }
  9674. IReporterRegistry::Listeners const& ReporterRegistry::getListeners() const {
  9675. return m_listeners;
  9676. }
  9677. }
  9678. // end catch_reporter_registry.cpp
  9679. // start catch_result_type.cpp
  9680. namespace Catch {
  9681. bool isOk( ResultWas::OfType resultType ) {
  9682. return ( resultType & ResultWas::FailureBit ) == 0;
  9683. }
  9684. bool isJustInfo( int flags ) {
  9685. return flags == ResultWas::Info;
  9686. }
  9687. ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) {
  9688. return static_cast<ResultDisposition::Flags>( static_cast<int>( lhs ) | static_cast<int>( rhs ) );
  9689. }
  9690. bool shouldContinueOnFailure( int flags ) { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; }
  9691. bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; }
  9692. } // end namespace Catch
  9693. // end catch_result_type.cpp
  9694. // start catch_run_context.cpp
  9695. #include <cassert>
  9696. #include <algorithm>
  9697. #include <sstream>
  9698. namespace Catch {
  9699. namespace Generators {
  9700. struct GeneratorTracker : TestCaseTracking::TrackerBase, IGeneratorTracker {
  9701. GeneratorBasePtr m_generator;
  9702. GeneratorTracker( TestCaseTracking::NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  9703. : TrackerBase( nameAndLocation, ctx, parent )
  9704. {}
  9705. ~GeneratorTracker();
  9706. static GeneratorTracker& acquire( TrackerContext& ctx, TestCaseTracking::NameAndLocation const& nameAndLocation ) {
  9707. std::shared_ptr<GeneratorTracker> tracker;
  9708. ITracker& currentTracker = ctx.currentTracker();
  9709. if( TestCaseTracking::ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  9710. assert( childTracker );
  9711. assert( childTracker->isGeneratorTracker() );
  9712. tracker = std::static_pointer_cast<GeneratorTracker>( childTracker );
  9713. }
  9714. else {
  9715. tracker = std::make_shared<GeneratorTracker>( nameAndLocation, ctx, &currentTracker );
  9716. currentTracker.addChild( tracker );
  9717. }
  9718. if( !ctx.completedCycle() && !tracker->isComplete() ) {
  9719. tracker->open();
  9720. }
  9721. return *tracker;
  9722. }
  9723. // TrackerBase interface
  9724. bool isGeneratorTracker() const override { return true; }
  9725. auto hasGenerator() const -> bool override {
  9726. return !!m_generator;
  9727. }
  9728. void close() override {
  9729. TrackerBase::close();
  9730. // Generator interface only finds out if it has another item on atual move
  9731. if (m_runState == CompletedSuccessfully && m_generator->next()) {
  9732. m_children.clear();
  9733. m_runState = Executing;
  9734. }
  9735. }
  9736. // IGeneratorTracker interface
  9737. auto getGenerator() const -> GeneratorBasePtr const& override {
  9738. return m_generator;
  9739. }
  9740. void setGenerator( GeneratorBasePtr&& generator ) override {
  9741. m_generator = std::move( generator );
  9742. }
  9743. };
  9744. GeneratorTracker::~GeneratorTracker() {}
  9745. }
  9746. RunContext::RunContext(IConfigPtr const& _config, IStreamingReporterPtr&& reporter)
  9747. : m_runInfo(_config->name()),
  9748. m_context(getCurrentMutableContext()),
  9749. m_config(_config),
  9750. m_reporter(std::move(reporter)),
  9751. m_lastAssertionInfo{ StringRef(), SourceLineInfo("",0), StringRef(), ResultDisposition::Normal },
  9752. m_includeSuccessfulResults( m_config->includeSuccessfulResults() || m_reporter->getPreferences().shouldReportAllAssertions )
  9753. {
  9754. m_context.setRunner(this);
  9755. m_context.setConfig(m_config);
  9756. m_context.setResultCapture(this);
  9757. m_reporter->testRunStarting(m_runInfo);
  9758. }
  9759. RunContext::~RunContext() {
  9760. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting()));
  9761. }
  9762. void RunContext::testGroupStarting(std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount) {
  9763. m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount));
  9764. }
  9765. void RunContext::testGroupEnded(std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount) {
  9766. m_reporter->testGroupEnded(TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting()));
  9767. }
  9768. Totals RunContext::runTest(TestCase const& testCase) {
  9769. Totals prevTotals = m_totals;
  9770. std::string redirectedCout;
  9771. std::string redirectedCerr;
  9772. auto const& testInfo = testCase.getTestCaseInfo();
  9773. m_reporter->testCaseStarting(testInfo);
  9774. m_activeTestCase = &testCase;
  9775. ITracker& rootTracker = m_trackerContext.startRun();
  9776. assert(rootTracker.isSectionTracker());
  9777. static_cast<SectionTracker&>(rootTracker).addInitialFilters(m_config->getSectionsToRun());
  9778. do {
  9779. m_trackerContext.startCycle();
  9780. m_testCaseTracker = &SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo));
  9781. runCurrentTest(redirectedCout, redirectedCerr);
  9782. } while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting());
  9783. Totals deltaTotals = m_totals.delta(prevTotals);
  9784. if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) {
  9785. deltaTotals.assertions.failed++;
  9786. deltaTotals.testCases.passed--;
  9787. deltaTotals.testCases.failed++;
  9788. }
  9789. m_totals.testCases += deltaTotals.testCases;
  9790. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  9791. deltaTotals,
  9792. redirectedCout,
  9793. redirectedCerr,
  9794. aborting()));
  9795. m_activeTestCase = nullptr;
  9796. m_testCaseTracker = nullptr;
  9797. return deltaTotals;
  9798. }
  9799. IConfigPtr RunContext::config() const {
  9800. return m_config;
  9801. }
  9802. IStreamingReporter& RunContext::reporter() const {
  9803. return *m_reporter;
  9804. }
  9805. void RunContext::assertionEnded(AssertionResult const & result) {
  9806. if (result.getResultType() == ResultWas::Ok) {
  9807. m_totals.assertions.passed++;
  9808. m_lastAssertionPassed = true;
  9809. } else if (!result.isOk()) {
  9810. m_lastAssertionPassed = false;
  9811. if( m_activeTestCase->getTestCaseInfo().okToFail() )
  9812. m_totals.assertions.failedButOk++;
  9813. else
  9814. m_totals.assertions.failed++;
  9815. }
  9816. else {
  9817. m_lastAssertionPassed = true;
  9818. }
  9819. // We have no use for the return value (whether messages should be cleared), because messages were made scoped
  9820. // and should be let to clear themselves out.
  9821. static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals)));
  9822. if (result.getResultType() != ResultWas::Warning)
  9823. m_messageScopes.clear();
  9824. // Reset working state
  9825. resetAssertionInfo();
  9826. m_lastResult = result;
  9827. }
  9828. void RunContext::resetAssertionInfo() {
  9829. m_lastAssertionInfo.macroName = StringRef();
  9830. m_lastAssertionInfo.capturedExpression = "{Unknown expression after the reported line}"_sr;
  9831. }
  9832. bool RunContext::sectionStarted(SectionInfo const & sectionInfo, Counts & assertions) {
  9833. ITracker& sectionTracker = SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(sectionInfo.name, sectionInfo.lineInfo));
  9834. if (!sectionTracker.isOpen())
  9835. return false;
  9836. m_activeSections.push_back(&sectionTracker);
  9837. m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;
  9838. m_reporter->sectionStarting(sectionInfo);
  9839. assertions = m_totals.assertions;
  9840. return true;
  9841. }
  9842. auto RunContext::acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
  9843. using namespace Generators;
  9844. GeneratorTracker& tracker = GeneratorTracker::acquire( m_trackerContext, TestCaseTracking::NameAndLocation( "generator", lineInfo ) );
  9845. assert( tracker.isOpen() );
  9846. m_lastAssertionInfo.lineInfo = lineInfo;
  9847. return tracker;
  9848. }
  9849. bool RunContext::testForMissingAssertions(Counts& assertions) {
  9850. if (assertions.total() != 0)
  9851. return false;
  9852. if (!m_config->warnAboutMissingAssertions())
  9853. return false;
  9854. if (m_trackerContext.currentTracker().hasChildren())
  9855. return false;
  9856. m_totals.assertions.failed++;
  9857. assertions.failed++;
  9858. return true;
  9859. }
  9860. void RunContext::sectionEnded(SectionEndInfo const & endInfo) {
  9861. Counts assertions = m_totals.assertions - endInfo.prevAssertions;
  9862. bool missingAssertions = testForMissingAssertions(assertions);
  9863. if (!m_activeSections.empty()) {
  9864. m_activeSections.back()->close();
  9865. m_activeSections.pop_back();
  9866. }
  9867. m_reporter->sectionEnded(SectionStats(endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions));
  9868. m_messages.clear();
  9869. m_messageScopes.clear();
  9870. }
  9871. void RunContext::sectionEndedEarly(SectionEndInfo const & endInfo) {
  9872. if (m_unfinishedSections.empty())
  9873. m_activeSections.back()->fail();
  9874. else
  9875. m_activeSections.back()->close();
  9876. m_activeSections.pop_back();
  9877. m_unfinishedSections.push_back(endInfo);
  9878. }
  9879. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  9880. void RunContext::benchmarkPreparing(std::string const& name) {
  9881. m_reporter->benchmarkPreparing(name);
  9882. }
  9883. void RunContext::benchmarkStarting( BenchmarkInfo const& info ) {
  9884. m_reporter->benchmarkStarting( info );
  9885. }
  9886. void RunContext::benchmarkEnded( BenchmarkStats<> const& stats ) {
  9887. m_reporter->benchmarkEnded( stats );
  9888. }
  9889. void RunContext::benchmarkFailed(std::string const & error) {
  9890. m_reporter->benchmarkFailed(error);
  9891. }
  9892. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  9893. void RunContext::pushScopedMessage(MessageInfo const & message) {
  9894. m_messages.push_back(message);
  9895. }
  9896. void RunContext::popScopedMessage(MessageInfo const & message) {
  9897. m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end());
  9898. }
  9899. void RunContext::emplaceUnscopedMessage( MessageBuilder const& builder ) {
  9900. m_messageScopes.emplace_back( builder );
  9901. }
  9902. std::string RunContext::getCurrentTestName() const {
  9903. return m_activeTestCase
  9904. ? m_activeTestCase->getTestCaseInfo().name
  9905. : std::string();
  9906. }
  9907. const AssertionResult * RunContext::getLastResult() const {
  9908. return &(*m_lastResult);
  9909. }
  9910. void RunContext::exceptionEarlyReported() {
  9911. m_shouldReportUnexpected = false;
  9912. }
  9913. void RunContext::handleFatalErrorCondition( StringRef message ) {
  9914. // First notify reporter that bad things happened
  9915. m_reporter->fatalErrorEncountered(message);
  9916. // Don't rebuild the result -- the stringification itself can cause more fatal errors
  9917. // Instead, fake a result data.
  9918. AssertionResultData tempResult( ResultWas::FatalErrorCondition, { false } );
  9919. tempResult.message = message;
  9920. AssertionResult result(m_lastAssertionInfo, tempResult);
  9921. assertionEnded(result);
  9922. handleUnfinishedSections();
  9923. // Recreate section for test case (as we will lose the one that was in scope)
  9924. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  9925. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
  9926. Counts assertions;
  9927. assertions.failed = 1;
  9928. SectionStats testCaseSectionStats(testCaseSection, assertions, 0, false);
  9929. m_reporter->sectionEnded(testCaseSectionStats);
  9930. auto const& testInfo = m_activeTestCase->getTestCaseInfo();
  9931. Totals deltaTotals;
  9932. deltaTotals.testCases.failed = 1;
  9933. deltaTotals.assertions.failed = 1;
  9934. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  9935. deltaTotals,
  9936. std::string(),
  9937. std::string(),
  9938. false));
  9939. m_totals.testCases.failed++;
  9940. testGroupEnded(std::string(), m_totals, 1, 1);
  9941. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, false));
  9942. }
  9943. bool RunContext::lastAssertionPassed() {
  9944. return m_lastAssertionPassed;
  9945. }
  9946. void RunContext::assertionPassed() {
  9947. m_lastAssertionPassed = true;
  9948. ++m_totals.assertions.passed;
  9949. resetAssertionInfo();
  9950. m_messageScopes.clear();
  9951. }
  9952. bool RunContext::aborting() const {
  9953. return m_totals.assertions.failed >= static_cast<std::size_t>(m_config->abortAfter());
  9954. }
  9955. void RunContext::runCurrentTest(std::string & redirectedCout, std::string & redirectedCerr) {
  9956. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  9957. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
  9958. m_reporter->sectionStarting(testCaseSection);
  9959. Counts prevAssertions = m_totals.assertions;
  9960. double duration = 0;
  9961. m_shouldReportUnexpected = true;
  9962. m_lastAssertionInfo = { "TEST_CASE"_sr, testCaseInfo.lineInfo, StringRef(), ResultDisposition::Normal };
  9963. seedRng(*m_config);
  9964. Timer timer;
  9965. CATCH_TRY {
  9966. if (m_reporter->getPreferences().shouldRedirectStdOut) {
  9967. #if !defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
  9968. RedirectedStreams redirectedStreams(redirectedCout, redirectedCerr);
  9969. timer.start();
  9970. invokeActiveTestCase();
  9971. #else
  9972. OutputRedirect r(redirectedCout, redirectedCerr);
  9973. timer.start();
  9974. invokeActiveTestCase();
  9975. #endif
  9976. } else {
  9977. timer.start();
  9978. invokeActiveTestCase();
  9979. }
  9980. duration = timer.getElapsedSeconds();
  9981. } CATCH_CATCH_ANON (TestFailureException&) {
  9982. // This just means the test was aborted due to failure
  9983. } CATCH_CATCH_ALL {
  9984. // Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under REQUIRE assertions
  9985. // are reported without translation at the point of origin.
  9986. if( m_shouldReportUnexpected ) {
  9987. AssertionReaction dummyReaction;
  9988. handleUnexpectedInflightException( m_lastAssertionInfo, translateActiveException(), dummyReaction );
  9989. }
  9990. }
  9991. Counts assertions = m_totals.assertions - prevAssertions;
  9992. bool missingAssertions = testForMissingAssertions(assertions);
  9993. m_testCaseTracker->close();
  9994. handleUnfinishedSections();
  9995. m_messages.clear();
  9996. m_messageScopes.clear();
  9997. SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions);
  9998. m_reporter->sectionEnded(testCaseSectionStats);
  9999. }
  10000. void RunContext::invokeActiveTestCase() {
  10001. FatalConditionHandler fatalConditionHandler; // Handle signals
  10002. m_activeTestCase->invoke();
  10003. fatalConditionHandler.reset();
  10004. }
  10005. void RunContext::handleUnfinishedSections() {
  10006. // If sections ended prematurely due to an exception we stored their
  10007. // infos here so we can tear them down outside the unwind process.
  10008. for (auto it = m_unfinishedSections.rbegin(),
  10009. itEnd = m_unfinishedSections.rend();
  10010. it != itEnd;
  10011. ++it)
  10012. sectionEnded(*it);
  10013. m_unfinishedSections.clear();
  10014. }
  10015. void RunContext::handleExpr(
  10016. AssertionInfo const& info,
  10017. ITransientExpression const& expr,
  10018. AssertionReaction& reaction
  10019. ) {
  10020. m_reporter->assertionStarting( info );
  10021. bool negated = isFalseTest( info.resultDisposition );
  10022. bool result = expr.getResult() != negated;
  10023. if( result ) {
  10024. if (!m_includeSuccessfulResults) {
  10025. assertionPassed();
  10026. }
  10027. else {
  10028. reportExpr(info, ResultWas::Ok, &expr, negated);
  10029. }
  10030. }
  10031. else {
  10032. reportExpr(info, ResultWas::ExpressionFailed, &expr, negated );
  10033. populateReaction( reaction );
  10034. }
  10035. }
  10036. void RunContext::reportExpr(
  10037. AssertionInfo const &info,
  10038. ResultWas::OfType resultType,
  10039. ITransientExpression const *expr,
  10040. bool negated ) {
  10041. m_lastAssertionInfo = info;
  10042. AssertionResultData data( resultType, LazyExpression( negated ) );
  10043. AssertionResult assertionResult{ info, data };
  10044. assertionResult.m_resultData.lazyExpression.m_transientExpression = expr;
  10045. assertionEnded( assertionResult );
  10046. }
  10047. void RunContext::handleMessage(
  10048. AssertionInfo const& info,
  10049. ResultWas::OfType resultType,
  10050. StringRef const& message,
  10051. AssertionReaction& reaction
  10052. ) {
  10053. m_reporter->assertionStarting( info );
  10054. m_lastAssertionInfo = info;
  10055. AssertionResultData data( resultType, LazyExpression( false ) );
  10056. data.message = message;
  10057. AssertionResult assertionResult{ m_lastAssertionInfo, data };
  10058. assertionEnded( assertionResult );
  10059. if( !assertionResult.isOk() )
  10060. populateReaction( reaction );
  10061. }
  10062. void RunContext::handleUnexpectedExceptionNotThrown(
  10063. AssertionInfo const& info,
  10064. AssertionReaction& reaction
  10065. ) {
  10066. handleNonExpr(info, Catch::ResultWas::DidntThrowException, reaction);
  10067. }
  10068. void RunContext::handleUnexpectedInflightException(
  10069. AssertionInfo const& info,
  10070. std::string const& message,
  10071. AssertionReaction& reaction
  10072. ) {
  10073. m_lastAssertionInfo = info;
  10074. AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
  10075. data.message = message;
  10076. AssertionResult assertionResult{ info, data };
  10077. assertionEnded( assertionResult );
  10078. populateReaction( reaction );
  10079. }
  10080. void RunContext::populateReaction( AssertionReaction& reaction ) {
  10081. reaction.shouldDebugBreak = m_config->shouldDebugBreak();
  10082. reaction.shouldThrow = aborting() || (m_lastAssertionInfo.resultDisposition & ResultDisposition::Normal);
  10083. }
  10084. void RunContext::handleIncomplete(
  10085. AssertionInfo const& info
  10086. ) {
  10087. m_lastAssertionInfo = info;
  10088. AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
  10089. data.message = "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE";
  10090. AssertionResult assertionResult{ info, data };
  10091. assertionEnded( assertionResult );
  10092. }
  10093. void RunContext::handleNonExpr(
  10094. AssertionInfo const &info,
  10095. ResultWas::OfType resultType,
  10096. AssertionReaction &reaction
  10097. ) {
  10098. m_lastAssertionInfo = info;
  10099. AssertionResultData data( resultType, LazyExpression( false ) );
  10100. AssertionResult assertionResult{ info, data };
  10101. assertionEnded( assertionResult );
  10102. if( !assertionResult.isOk() )
  10103. populateReaction( reaction );
  10104. }
  10105. IResultCapture& getResultCapture() {
  10106. if (auto* capture = getCurrentContext().getResultCapture())
  10107. return *capture;
  10108. else
  10109. CATCH_INTERNAL_ERROR("No result capture instance");
  10110. }
  10111. }
  10112. // end catch_run_context.cpp
  10113. // start catch_section.cpp
  10114. namespace Catch {
  10115. Section::Section( SectionInfo const& info )
  10116. : m_info( info ),
  10117. m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) )
  10118. {
  10119. m_timer.start();
  10120. }
  10121. Section::~Section() {
  10122. if( m_sectionIncluded ) {
  10123. SectionEndInfo endInfo{ m_info, m_assertions, m_timer.getElapsedSeconds() };
  10124. if( uncaught_exceptions() )
  10125. getResultCapture().sectionEndedEarly( endInfo );
  10126. else
  10127. getResultCapture().sectionEnded( endInfo );
  10128. }
  10129. }
  10130. // This indicates whether the section should be executed or not
  10131. Section::operator bool() const {
  10132. return m_sectionIncluded;
  10133. }
  10134. } // end namespace Catch
  10135. // end catch_section.cpp
  10136. // start catch_section_info.cpp
  10137. namespace Catch {
  10138. SectionInfo::SectionInfo
  10139. ( SourceLineInfo const& _lineInfo,
  10140. std::string const& _name )
  10141. : name( _name ),
  10142. lineInfo( _lineInfo )
  10143. {}
  10144. } // end namespace Catch
  10145. // end catch_section_info.cpp
  10146. // start catch_session.cpp
  10147. // start catch_session.h
  10148. #include <memory>
  10149. namespace Catch {
  10150. class Session : NonCopyable {
  10151. public:
  10152. Session();
  10153. ~Session() override;
  10154. void showHelp() const;
  10155. void libIdentify();
  10156. int applyCommandLine( int argc, char const * const * argv );
  10157. #if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(UNICODE)
  10158. int applyCommandLine( int argc, wchar_t const * const * argv );
  10159. #endif
  10160. void useConfigData( ConfigData const& configData );
  10161. template<typename CharT>
  10162. int run(int argc, CharT const * const argv[]) {
  10163. if (m_startupExceptions)
  10164. return 1;
  10165. int returnCode = applyCommandLine(argc, argv);
  10166. if (returnCode == 0)
  10167. returnCode = run();
  10168. return returnCode;
  10169. }
  10170. int run();
  10171. clara::Parser const& cli() const;
  10172. void cli( clara::Parser const& newParser );
  10173. ConfigData& configData();
  10174. Config& config();
  10175. private:
  10176. int runInternal();
  10177. clara::Parser m_cli;
  10178. ConfigData m_configData;
  10179. std::shared_ptr<Config> m_config;
  10180. bool m_startupExceptions = false;
  10181. };
  10182. } // end namespace Catch
  10183. // end catch_session.h
  10184. // start catch_version.h
  10185. #include <iosfwd>
  10186. namespace Catch {
  10187. // Versioning information
  10188. struct Version {
  10189. Version( Version const& ) = delete;
  10190. Version& operator=( Version const& ) = delete;
  10191. Version( unsigned int _majorVersion,
  10192. unsigned int _minorVersion,
  10193. unsigned int _patchNumber,
  10194. char const * const _branchName,
  10195. unsigned int _buildNumber );
  10196. unsigned int const majorVersion;
  10197. unsigned int const minorVersion;
  10198. unsigned int const patchNumber;
  10199. // buildNumber is only used if branchName is not null
  10200. char const * const branchName;
  10201. unsigned int const buildNumber;
  10202. friend std::ostream& operator << ( std::ostream& os, Version const& version );
  10203. };
  10204. Version const& libraryVersion();
  10205. }
  10206. // end catch_version.h
  10207. #include <cstdlib>
  10208. #include <iomanip>
  10209. namespace Catch {
  10210. namespace {
  10211. const int MaxExitCode = 255;
  10212. IStreamingReporterPtr createReporter(std::string const& reporterName, IConfigPtr const& config) {
  10213. auto reporter = Catch::getRegistryHub().getReporterRegistry().create(reporterName, config);
  10214. CATCH_ENFORCE(reporter, "No reporter registered with name: '" << reporterName << "'");
  10215. return reporter;
  10216. }
  10217. IStreamingReporterPtr makeReporter(std::shared_ptr<Config> const& config) {
  10218. if (Catch::getRegistryHub().getReporterRegistry().getListeners().empty()) {
  10219. return createReporter(config->getReporterName(), config);
  10220. }
  10221. // On older platforms, returning std::unique_ptr<ListeningReporter>
  10222. // when the return type is std::unique_ptr<IStreamingReporter>
  10223. // doesn't compile without a std::move call. However, this causes
  10224. // a warning on newer platforms. Thus, we have to work around
  10225. // it a bit and downcast the pointer manually.
  10226. auto ret = std::unique_ptr<IStreamingReporter>(new ListeningReporter);
  10227. auto& multi = static_cast<ListeningReporter&>(*ret);
  10228. auto const& listeners = Catch::getRegistryHub().getReporterRegistry().getListeners();
  10229. for (auto const& listener : listeners) {
  10230. multi.addListener(listener->create(Catch::ReporterConfig(config)));
  10231. }
  10232. multi.addReporter(createReporter(config->getReporterName(), config));
  10233. return ret;
  10234. }
  10235. Catch::Totals runTests(std::shared_ptr<Config> const& config) {
  10236. auto reporter = makeReporter(config);
  10237. RunContext context(config, std::move(reporter));
  10238. Totals totals;
  10239. context.testGroupStarting(config->name(), 1, 1);
  10240. TestSpec testSpec = config->testSpec();
  10241. auto const& allTestCases = getAllTestCasesSorted(*config);
  10242. for (auto const& testCase : allTestCases) {
  10243. bool matching = (!testSpec.hasFilters() && !testCase.isHidden()) ||
  10244. (testSpec.hasFilters() && matchTest(testCase, testSpec, *config));
  10245. if (!context.aborting() && matching)
  10246. totals += context.runTest(testCase);
  10247. else
  10248. context.reporter().skipTest(testCase);
  10249. }
  10250. if (config->warnAboutNoTests() && totals.testCases.total() == 0) {
  10251. ReusableStringStream testConfig;
  10252. bool first = true;
  10253. for (const auto& input : config->getTestsOrTags()) {
  10254. if (!first) { testConfig << ' '; }
  10255. first = false;
  10256. testConfig << input;
  10257. }
  10258. context.reporter().noMatchingTestCases(testConfig.str());
  10259. totals.error = -1;
  10260. }
  10261. context.testGroupEnded(config->name(), totals, 1, 1);
  10262. return totals;
  10263. }
  10264. void applyFilenamesAsTags(Catch::IConfig const& config) {
  10265. auto& tests = const_cast<std::vector<TestCase>&>(getAllTestCasesSorted(config));
  10266. for (auto& testCase : tests) {
  10267. auto tags = testCase.tags;
  10268. std::string filename = testCase.lineInfo.file;
  10269. auto lastSlash = filename.find_last_of("\\/");
  10270. if (lastSlash != std::string::npos) {
  10271. filename.erase(0, lastSlash);
  10272. filename[0] = '#';
  10273. }
  10274. auto lastDot = filename.find_last_of('.');
  10275. if (lastDot != std::string::npos) {
  10276. filename.erase(lastDot);
  10277. }
  10278. tags.push_back(std::move(filename));
  10279. setTags(testCase, tags);
  10280. }
  10281. }
  10282. } // anon namespace
  10283. Session::Session() {
  10284. static bool alreadyInstantiated = false;
  10285. if( alreadyInstantiated ) {
  10286. CATCH_TRY { CATCH_INTERNAL_ERROR( "Only one instance of Catch::Session can ever be used" ); }
  10287. CATCH_CATCH_ALL { getMutableRegistryHub().registerStartupException(); }
  10288. }
  10289. // There cannot be exceptions at startup in no-exception mode.
  10290. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  10291. const auto& exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions();
  10292. if ( !exceptions.empty() ) {
  10293. config();
  10294. getCurrentMutableContext().setConfig(m_config);
  10295. m_startupExceptions = true;
  10296. Colour colourGuard( Colour::Red );
  10297. Catch::cerr() << "Errors occurred during startup!" << '\n';
  10298. // iterate over all exceptions and notify user
  10299. for ( const auto& ex_ptr : exceptions ) {
  10300. try {
  10301. std::rethrow_exception(ex_ptr);
  10302. } catch ( std::exception const& ex ) {
  10303. Catch::cerr() << Column( ex.what() ).indent(2) << '\n';
  10304. }
  10305. }
  10306. }
  10307. #endif
  10308. alreadyInstantiated = true;
  10309. m_cli = makeCommandLineParser( m_configData );
  10310. }
  10311. Session::~Session() {
  10312. Catch::cleanUp();
  10313. }
  10314. void Session::showHelp() const {
  10315. Catch::cout()
  10316. << "\nCatch v" << libraryVersion() << "\n"
  10317. << m_cli << std::endl
  10318. << "For more detailed usage please see the project docs\n" << std::endl;
  10319. }
  10320. void Session::libIdentify() {
  10321. Catch::cout()
  10322. << std::left << std::setw(16) << "description: " << "A Catch test executable\n"
  10323. << std::left << std::setw(16) << "category: " << "testframework\n"
  10324. << std::left << std::setw(16) << "framework: " << "Catch Test\n"
  10325. << std::left << std::setw(16) << "version: " << libraryVersion() << std::endl;
  10326. }
  10327. int Session::applyCommandLine( int argc, char const * const * argv ) {
  10328. if( m_startupExceptions )
  10329. return 1;
  10330. auto result = m_cli.parse( clara::Args( argc, argv ) );
  10331. if( !result ) {
  10332. config();
  10333. getCurrentMutableContext().setConfig(m_config);
  10334. Catch::cerr()
  10335. << Colour( Colour::Red )
  10336. << "\nError(s) in input:\n"
  10337. << Column( result.errorMessage() ).indent( 2 )
  10338. << "\n\n";
  10339. Catch::cerr() << "Run with -? for usage\n" << std::endl;
  10340. return MaxExitCode;
  10341. }
  10342. if( m_configData.showHelp )
  10343. showHelp();
  10344. if( m_configData.libIdentify )
  10345. libIdentify();
  10346. m_config.reset();
  10347. return 0;
  10348. }
  10349. #if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(UNICODE)
  10350. int Session::applyCommandLine( int argc, wchar_t const * const * argv ) {
  10351. char **utf8Argv = new char *[ argc ];
  10352. for ( int i = 0; i < argc; ++i ) {
  10353. int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, NULL, 0, NULL, NULL );
  10354. utf8Argv[ i ] = new char[ bufSize ];
  10355. WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, NULL, NULL );
  10356. }
  10357. int returnCode = applyCommandLine( argc, utf8Argv );
  10358. for ( int i = 0; i < argc; ++i )
  10359. delete [] utf8Argv[ i ];
  10360. delete [] utf8Argv;
  10361. return returnCode;
  10362. }
  10363. #endif
  10364. void Session::useConfigData( ConfigData const& configData ) {
  10365. m_configData = configData;
  10366. m_config.reset();
  10367. }
  10368. int Session::run() {
  10369. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeStart ) != 0 ) {
  10370. Catch::cout() << "...waiting for enter/ return before starting" << std::endl;
  10371. static_cast<void>(std::getchar());
  10372. }
  10373. int exitCode = runInternal();
  10374. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeExit ) != 0 ) {
  10375. Catch::cout() << "...waiting for enter/ return before exiting, with code: " << exitCode << std::endl;
  10376. static_cast<void>(std::getchar());
  10377. }
  10378. return exitCode;
  10379. }
  10380. clara::Parser const& Session::cli() const {
  10381. return m_cli;
  10382. }
  10383. void Session::cli( clara::Parser const& newParser ) {
  10384. m_cli = newParser;
  10385. }
  10386. ConfigData& Session::configData() {
  10387. return m_configData;
  10388. }
  10389. Config& Session::config() {
  10390. if( !m_config )
  10391. m_config = std::make_shared<Config>( m_configData );
  10392. return *m_config;
  10393. }
  10394. int Session::runInternal() {
  10395. if( m_startupExceptions )
  10396. return 1;
  10397. if (m_configData.showHelp || m_configData.libIdentify) {
  10398. return 0;
  10399. }
  10400. CATCH_TRY {
  10401. config(); // Force config to be constructed
  10402. seedRng( *m_config );
  10403. if( m_configData.filenamesAsTags )
  10404. applyFilenamesAsTags( *m_config );
  10405. // Handle list request
  10406. if( Option<std::size_t> listed = list( m_config ) )
  10407. return static_cast<int>( *listed );
  10408. auto totals = runTests( m_config );
  10409. // Note that on unices only the lower 8 bits are usually used, clamping
  10410. // the return value to 255 prevents false negative when some multiple
  10411. // of 256 tests has failed
  10412. return (std::min) (MaxExitCode, (std::max) (totals.error, static_cast<int>(totals.assertions.failed)));
  10413. }
  10414. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  10415. catch( std::exception& ex ) {
  10416. Catch::cerr() << ex.what() << std::endl;
  10417. return MaxExitCode;
  10418. }
  10419. #endif
  10420. }
  10421. } // end namespace Catch
  10422. // end catch_session.cpp
  10423. // start catch_singletons.cpp
  10424. #include <vector>
  10425. namespace Catch {
  10426. namespace {
  10427. static auto getSingletons() -> std::vector<ISingleton*>*& {
  10428. static std::vector<ISingleton*>* g_singletons = nullptr;
  10429. if( !g_singletons )
  10430. g_singletons = new std::vector<ISingleton*>();
  10431. return g_singletons;
  10432. }
  10433. }
  10434. ISingleton::~ISingleton() {}
  10435. void addSingleton(ISingleton* singleton ) {
  10436. getSingletons()->push_back( singleton );
  10437. }
  10438. void cleanupSingletons() {
  10439. auto& singletons = getSingletons();
  10440. for( auto singleton : *singletons )
  10441. delete singleton;
  10442. delete singletons;
  10443. singletons = nullptr;
  10444. }
  10445. } // namespace Catch
  10446. // end catch_singletons.cpp
  10447. // start catch_startup_exception_registry.cpp
  10448. namespace Catch {
  10449. void StartupExceptionRegistry::add( std::exception_ptr const& exception ) noexcept {
  10450. CATCH_TRY {
  10451. m_exceptions.push_back(exception);
  10452. } CATCH_CATCH_ALL {
  10453. // If we run out of memory during start-up there's really not a lot more we can do about it
  10454. std::terminate();
  10455. }
  10456. }
  10457. std::vector<std::exception_ptr> const& StartupExceptionRegistry::getExceptions() const noexcept {
  10458. return m_exceptions;
  10459. }
  10460. } // end namespace Catch
  10461. // end catch_startup_exception_registry.cpp
  10462. // start catch_stream.cpp
  10463. #include <cstdio>
  10464. #include <iostream>
  10465. #include <fstream>
  10466. #include <sstream>
  10467. #include <vector>
  10468. #include <memory>
  10469. namespace Catch {
  10470. Catch::IStream::~IStream() = default;
  10471. namespace Detail { namespace {
  10472. template<typename WriterF, std::size_t bufferSize=256>
  10473. class StreamBufImpl : public std::streambuf {
  10474. char data[bufferSize];
  10475. WriterF m_writer;
  10476. public:
  10477. StreamBufImpl() {
  10478. setp( data, data + sizeof(data) );
  10479. }
  10480. ~StreamBufImpl() noexcept {
  10481. StreamBufImpl::sync();
  10482. }
  10483. private:
  10484. int overflow( int c ) override {
  10485. sync();
  10486. if( c != EOF ) {
  10487. if( pbase() == epptr() )
  10488. m_writer( std::string( 1, static_cast<char>( c ) ) );
  10489. else
  10490. sputc( static_cast<char>( c ) );
  10491. }
  10492. return 0;
  10493. }
  10494. int sync() override {
  10495. if( pbase() != pptr() ) {
  10496. m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) );
  10497. setp( pbase(), epptr() );
  10498. }
  10499. return 0;
  10500. }
  10501. };
  10502. ///////////////////////////////////////////////////////////////////////////
  10503. struct OutputDebugWriter {
  10504. void operator()( std::string const&str ) {
  10505. writeToDebugConsole( str );
  10506. }
  10507. };
  10508. ///////////////////////////////////////////////////////////////////////////
  10509. class FileStream : public IStream {
  10510. mutable std::ofstream m_ofs;
  10511. public:
  10512. FileStream( StringRef filename ) {
  10513. m_ofs.open( filename.c_str() );
  10514. CATCH_ENFORCE( !m_ofs.fail(), "Unable to open file: '" << filename << "'" );
  10515. }
  10516. ~FileStream() override = default;
  10517. public: // IStream
  10518. std::ostream& stream() const override {
  10519. return m_ofs;
  10520. }
  10521. };
  10522. ///////////////////////////////////////////////////////////////////////////
  10523. class CoutStream : public IStream {
  10524. mutable std::ostream m_os;
  10525. public:
  10526. // Store the streambuf from cout up-front because
  10527. // cout may get redirected when running tests
  10528. CoutStream() : m_os( Catch::cout().rdbuf() ) {}
  10529. ~CoutStream() override = default;
  10530. public: // IStream
  10531. std::ostream& stream() const override { return m_os; }
  10532. };
  10533. ///////////////////////////////////////////////////////////////////////////
  10534. class DebugOutStream : public IStream {
  10535. std::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf;
  10536. mutable std::ostream m_os;
  10537. public:
  10538. DebugOutStream()
  10539. : m_streamBuf( new StreamBufImpl<OutputDebugWriter>() ),
  10540. m_os( m_streamBuf.get() )
  10541. {}
  10542. ~DebugOutStream() override = default;
  10543. public: // IStream
  10544. std::ostream& stream() const override { return m_os; }
  10545. };
  10546. }} // namespace anon::detail
  10547. ///////////////////////////////////////////////////////////////////////////
  10548. auto makeStream( StringRef const &filename ) -> IStream const* {
  10549. if( filename.empty() )
  10550. return new Detail::CoutStream();
  10551. else if( filename[0] == '%' ) {
  10552. if( filename == "%debug" )
  10553. return new Detail::DebugOutStream();
  10554. else
  10555. CATCH_ERROR( "Unrecognised stream: '" << filename << "'" );
  10556. }
  10557. else
  10558. return new Detail::FileStream( filename );
  10559. }
  10560. // This class encapsulates the idea of a pool of ostringstreams that can be reused.
  10561. struct StringStreams {
  10562. std::vector<std::unique_ptr<std::ostringstream>> m_streams;
  10563. std::vector<std::size_t> m_unused;
  10564. std::ostringstream m_referenceStream; // Used for copy state/ flags from
  10565. auto add() -> std::size_t {
  10566. if( m_unused.empty() ) {
  10567. m_streams.push_back( std::unique_ptr<std::ostringstream>( new std::ostringstream ) );
  10568. return m_streams.size()-1;
  10569. }
  10570. else {
  10571. auto index = m_unused.back();
  10572. m_unused.pop_back();
  10573. return index;
  10574. }
  10575. }
  10576. void release( std::size_t index ) {
  10577. m_streams[index]->copyfmt( m_referenceStream ); // Restore initial flags and other state
  10578. m_unused.push_back(index);
  10579. }
  10580. };
  10581. ReusableStringStream::ReusableStringStream()
  10582. : m_index( Singleton<StringStreams>::getMutable().add() ),
  10583. m_oss( Singleton<StringStreams>::getMutable().m_streams[m_index].get() )
  10584. {}
  10585. ReusableStringStream::~ReusableStringStream() {
  10586. static_cast<std::ostringstream*>( m_oss )->str("");
  10587. m_oss->clear();
  10588. Singleton<StringStreams>::getMutable().release( m_index );
  10589. }
  10590. auto ReusableStringStream::str() const -> std::string {
  10591. return static_cast<std::ostringstream*>( m_oss )->str();
  10592. }
  10593. ///////////////////////////////////////////////////////////////////////////
  10594. #ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions
  10595. std::ostream& cout() { return std::cout; }
  10596. std::ostream& cerr() { return std::cerr; }
  10597. std::ostream& clog() { return std::clog; }
  10598. #endif
  10599. }
  10600. // end catch_stream.cpp
  10601. // start catch_string_manip.cpp
  10602. #include <algorithm>
  10603. #include <ostream>
  10604. #include <cstring>
  10605. #include <cctype>
  10606. #include <vector>
  10607. namespace Catch {
  10608. namespace {
  10609. char toLowerCh(char c) {
  10610. return static_cast<char>( std::tolower( c ) );
  10611. }
  10612. }
  10613. bool startsWith( std::string const& s, std::string const& prefix ) {
  10614. return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
  10615. }
  10616. bool startsWith( std::string const& s, char prefix ) {
  10617. return !s.empty() && s[0] == prefix;
  10618. }
  10619. bool endsWith( std::string const& s, std::string const& suffix ) {
  10620. return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
  10621. }
  10622. bool endsWith( std::string const& s, char suffix ) {
  10623. return !s.empty() && s[s.size()-1] == suffix;
  10624. }
  10625. bool contains( std::string const& s, std::string const& infix ) {
  10626. return s.find( infix ) != std::string::npos;
  10627. }
  10628. void toLowerInPlace( std::string& s ) {
  10629. std::transform( s.begin(), s.end(), s.begin(), toLowerCh );
  10630. }
  10631. std::string toLower( std::string const& s ) {
  10632. std::string lc = s;
  10633. toLowerInPlace( lc );
  10634. return lc;
  10635. }
  10636. std::string trim( std::string const& str ) {
  10637. static char const* whitespaceChars = "\n\r\t ";
  10638. std::string::size_type start = str.find_first_not_of( whitespaceChars );
  10639. std::string::size_type end = str.find_last_not_of( whitespaceChars );
  10640. return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string();
  10641. }
  10642. bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) {
  10643. bool replaced = false;
  10644. std::size_t i = str.find( replaceThis );
  10645. while( i != std::string::npos ) {
  10646. replaced = true;
  10647. str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() );
  10648. if( i < str.size()-withThis.size() )
  10649. i = str.find( replaceThis, i+withThis.size() );
  10650. else
  10651. i = std::string::npos;
  10652. }
  10653. return replaced;
  10654. }
  10655. std::vector<StringRef> splitStringRef( StringRef str, char delimiter ) {
  10656. std::vector<StringRef> subStrings;
  10657. std::size_t start = 0;
  10658. for(std::size_t pos = 0; pos < str.size(); ++pos ) {
  10659. if( str[pos] == delimiter ) {
  10660. if( pos - start > 1 )
  10661. subStrings.push_back( str.substr( start, pos-start ) );
  10662. start = pos+1;
  10663. }
  10664. }
  10665. if( start < str.size() )
  10666. subStrings.push_back( str.substr( start, str.size()-start ) );
  10667. return subStrings;
  10668. }
  10669. pluralise::pluralise( std::size_t count, std::string const& label )
  10670. : m_count( count ),
  10671. m_label( label )
  10672. {}
  10673. std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) {
  10674. os << pluraliser.m_count << ' ' << pluraliser.m_label;
  10675. if( pluraliser.m_count != 1 )
  10676. os << 's';
  10677. return os;
  10678. }
  10679. }
  10680. // end catch_string_manip.cpp
  10681. // start catch_stringref.cpp
  10682. #if defined(__clang__)
  10683. # pragma clang diagnostic push
  10684. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  10685. #endif
  10686. #include <ostream>
  10687. #include <cstring>
  10688. #include <cstdint>
  10689. namespace {
  10690. const uint32_t byte_2_lead = 0xC0;
  10691. const uint32_t byte_3_lead = 0xE0;
  10692. const uint32_t byte_4_lead = 0xF0;
  10693. }
  10694. namespace Catch {
  10695. StringRef::StringRef( char const* rawChars ) noexcept
  10696. : StringRef( rawChars, static_cast<StringRef::size_type>(std::strlen(rawChars) ) )
  10697. {}
  10698. StringRef::operator std::string() const {
  10699. return std::string( m_start, m_size );
  10700. }
  10701. void StringRef::swap( StringRef& other ) noexcept {
  10702. std::swap( m_start, other.m_start );
  10703. std::swap( m_size, other.m_size );
  10704. std::swap( m_data, other.m_data );
  10705. }
  10706. auto StringRef::c_str() const -> char const* {
  10707. if( !isSubstring() )
  10708. return m_start;
  10709. const_cast<StringRef *>( this )->takeOwnership();
  10710. return m_data;
  10711. }
  10712. auto StringRef::currentData() const noexcept -> char const* {
  10713. return m_start;
  10714. }
  10715. auto StringRef::isOwned() const noexcept -> bool {
  10716. return m_data != nullptr;
  10717. }
  10718. auto StringRef::isSubstring() const noexcept -> bool {
  10719. return m_start[m_size] != '\0';
  10720. }
  10721. void StringRef::takeOwnership() {
  10722. if( !isOwned() ) {
  10723. m_data = new char[m_size+1];
  10724. memcpy( m_data, m_start, m_size );
  10725. m_data[m_size] = '\0';
  10726. }
  10727. }
  10728. auto StringRef::substr( size_type start, size_type size ) const noexcept -> StringRef {
  10729. if( start < m_size )
  10730. return StringRef( m_start+start, size );
  10731. else
  10732. return StringRef();
  10733. }
  10734. auto StringRef::operator == ( StringRef const& other ) const noexcept -> bool {
  10735. return
  10736. size() == other.size() &&
  10737. (std::strncmp( m_start, other.m_start, size() ) == 0);
  10738. }
  10739. auto StringRef::operator != ( StringRef const& other ) const noexcept -> bool {
  10740. return !operator==( other );
  10741. }
  10742. auto StringRef::operator[](size_type index) const noexcept -> char {
  10743. return m_start[index];
  10744. }
  10745. auto StringRef::numberOfCharacters() const noexcept -> size_type {
  10746. size_type noChars = m_size;
  10747. // Make adjustments for uft encodings
  10748. for( size_type i=0; i < m_size; ++i ) {
  10749. char c = m_start[i];
  10750. if( ( c & byte_2_lead ) == byte_2_lead ) {
  10751. noChars--;
  10752. if (( c & byte_3_lead ) == byte_3_lead )
  10753. noChars--;
  10754. if( ( c & byte_4_lead ) == byte_4_lead )
  10755. noChars--;
  10756. }
  10757. }
  10758. return noChars;
  10759. }
  10760. auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string {
  10761. std::string str;
  10762. str.reserve( lhs.size() + rhs.size() );
  10763. str += lhs;
  10764. str += rhs;
  10765. return str;
  10766. }
  10767. auto operator + ( StringRef const& lhs, const char* rhs ) -> std::string {
  10768. return std::string( lhs ) + std::string( rhs );
  10769. }
  10770. auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string {
  10771. return std::string( lhs ) + std::string( rhs );
  10772. }
  10773. auto operator << ( std::ostream& os, StringRef const& str ) -> std::ostream& {
  10774. return os.write(str.currentData(), str.size());
  10775. }
  10776. auto operator+=( std::string& lhs, StringRef const& rhs ) -> std::string& {
  10777. lhs.append(rhs.currentData(), rhs.size());
  10778. return lhs;
  10779. }
  10780. } // namespace Catch
  10781. #if defined(__clang__)
  10782. # pragma clang diagnostic pop
  10783. #endif
  10784. // end catch_stringref.cpp
  10785. // start catch_tag_alias.cpp
  10786. namespace Catch {
  10787. TagAlias::TagAlias(std::string const & _tag, SourceLineInfo _lineInfo): tag(_tag), lineInfo(_lineInfo) {}
  10788. }
  10789. // end catch_tag_alias.cpp
  10790. // start catch_tag_alias_autoregistrar.cpp
  10791. namespace Catch {
  10792. RegistrarForTagAliases::RegistrarForTagAliases(char const* alias, char const* tag, SourceLineInfo const& lineInfo) {
  10793. CATCH_TRY {
  10794. getMutableRegistryHub().registerTagAlias(alias, tag, lineInfo);
  10795. } CATCH_CATCH_ALL {
  10796. // Do not throw when constructing global objects, instead register the exception to be processed later
  10797. getMutableRegistryHub().registerStartupException();
  10798. }
  10799. }
  10800. }
  10801. // end catch_tag_alias_autoregistrar.cpp
  10802. // start catch_tag_alias_registry.cpp
  10803. #include <sstream>
  10804. namespace Catch {
  10805. TagAliasRegistry::~TagAliasRegistry() {}
  10806. TagAlias const* TagAliasRegistry::find( std::string const& alias ) const {
  10807. auto it = m_registry.find( alias );
  10808. if( it != m_registry.end() )
  10809. return &(it->second);
  10810. else
  10811. return nullptr;
  10812. }
  10813. std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const {
  10814. std::string expandedTestSpec = unexpandedTestSpec;
  10815. for( auto const& registryKvp : m_registry ) {
  10816. std::size_t pos = expandedTestSpec.find( registryKvp.first );
  10817. if( pos != std::string::npos ) {
  10818. expandedTestSpec = expandedTestSpec.substr( 0, pos ) +
  10819. registryKvp.second.tag +
  10820. expandedTestSpec.substr( pos + registryKvp.first.size() );
  10821. }
  10822. }
  10823. return expandedTestSpec;
  10824. }
  10825. void TagAliasRegistry::add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) {
  10826. CATCH_ENFORCE( startsWith(alias, "[@") && endsWith(alias, ']'),
  10827. "error: tag alias, '" << alias << "' is not of the form [@alias name].\n" << lineInfo );
  10828. CATCH_ENFORCE( m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second,
  10829. "error: tag alias, '" << alias << "' already registered.\n"
  10830. << "\tFirst seen at: " << find(alias)->lineInfo << "\n"
  10831. << "\tRedefined at: " << lineInfo );
  10832. }
  10833. ITagAliasRegistry::~ITagAliasRegistry() {}
  10834. ITagAliasRegistry const& ITagAliasRegistry::get() {
  10835. return getRegistryHub().getTagAliasRegistry();
  10836. }
  10837. } // end namespace Catch
  10838. // end catch_tag_alias_registry.cpp
  10839. // start catch_test_case_info.cpp
  10840. #include <cctype>
  10841. #include <exception>
  10842. #include <algorithm>
  10843. #include <sstream>
  10844. namespace Catch {
  10845. namespace {
  10846. TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) {
  10847. if( startsWith( tag, '.' ) ||
  10848. tag == "!hide" )
  10849. return TestCaseInfo::IsHidden;
  10850. else if( tag == "!throws" )
  10851. return TestCaseInfo::Throws;
  10852. else if( tag == "!shouldfail" )
  10853. return TestCaseInfo::ShouldFail;
  10854. else if( tag == "!mayfail" )
  10855. return TestCaseInfo::MayFail;
  10856. else if( tag == "!nonportable" )
  10857. return TestCaseInfo::NonPortable;
  10858. else if( tag == "!benchmark" )
  10859. return static_cast<TestCaseInfo::SpecialProperties>( TestCaseInfo::Benchmark | TestCaseInfo::IsHidden );
  10860. else
  10861. return TestCaseInfo::None;
  10862. }
  10863. bool isReservedTag( std::string const& tag ) {
  10864. return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !std::isalnum( static_cast<unsigned char>(tag[0]) );
  10865. }
  10866. void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) {
  10867. CATCH_ENFORCE( !isReservedTag(tag),
  10868. "Tag name: [" << tag << "] is not allowed.\n"
  10869. << "Tag names starting with non alphanumeric characters are reserved\n"
  10870. << _lineInfo );
  10871. }
  10872. }
  10873. TestCase makeTestCase( ITestInvoker* _testCase,
  10874. std::string const& _className,
  10875. NameAndTags const& nameAndTags,
  10876. SourceLineInfo const& _lineInfo )
  10877. {
  10878. bool isHidden = false;
  10879. // Parse out tags
  10880. std::vector<std::string> tags;
  10881. std::string desc, tag;
  10882. bool inTag = false;
  10883. std::string _descOrTags = nameAndTags.tags;
  10884. for (char c : _descOrTags) {
  10885. if( !inTag ) {
  10886. if( c == '[' )
  10887. inTag = true;
  10888. else
  10889. desc += c;
  10890. }
  10891. else {
  10892. if( c == ']' ) {
  10893. TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag );
  10894. if( ( prop & TestCaseInfo::IsHidden ) != 0 )
  10895. isHidden = true;
  10896. else if( prop == TestCaseInfo::None )
  10897. enforceNotReservedTag( tag, _lineInfo );
  10898. // Merged hide tags like `[.approvals]` should be added as
  10899. // `[.][approvals]`. The `[.]` is added at later point, so
  10900. // we only strip the prefix
  10901. if (startsWith(tag, '.') && tag.size() > 1) {
  10902. tag.erase(0, 1);
  10903. }
  10904. tags.push_back( tag );
  10905. tag.clear();
  10906. inTag = false;
  10907. }
  10908. else
  10909. tag += c;
  10910. }
  10911. }
  10912. if( isHidden ) {
  10913. tags.push_back( "." );
  10914. }
  10915. TestCaseInfo info( nameAndTags.name, _className, desc, tags, _lineInfo );
  10916. return TestCase( _testCase, std::move(info) );
  10917. }
  10918. void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags ) {
  10919. std::sort(begin(tags), end(tags));
  10920. tags.erase(std::unique(begin(tags), end(tags)), end(tags));
  10921. testCaseInfo.lcaseTags.clear();
  10922. for( auto const& tag : tags ) {
  10923. std::string lcaseTag = toLower( tag );
  10924. testCaseInfo.properties = static_cast<TestCaseInfo::SpecialProperties>( testCaseInfo.properties | parseSpecialTag( lcaseTag ) );
  10925. testCaseInfo.lcaseTags.push_back( lcaseTag );
  10926. }
  10927. testCaseInfo.tags = std::move(tags);
  10928. }
  10929. TestCaseInfo::TestCaseInfo( std::string const& _name,
  10930. std::string const& _className,
  10931. std::string const& _description,
  10932. std::vector<std::string> const& _tags,
  10933. SourceLineInfo const& _lineInfo )
  10934. : name( _name ),
  10935. className( _className ),
  10936. description( _description ),
  10937. lineInfo( _lineInfo ),
  10938. properties( None )
  10939. {
  10940. setTags( *this, _tags );
  10941. }
  10942. bool TestCaseInfo::isHidden() const {
  10943. return ( properties & IsHidden ) != 0;
  10944. }
  10945. bool TestCaseInfo::throws() const {
  10946. return ( properties & Throws ) != 0;
  10947. }
  10948. bool TestCaseInfo::okToFail() const {
  10949. return ( properties & (ShouldFail | MayFail ) ) != 0;
  10950. }
  10951. bool TestCaseInfo::expectedToFail() const {
  10952. return ( properties & (ShouldFail ) ) != 0;
  10953. }
  10954. std::string TestCaseInfo::tagsAsString() const {
  10955. std::string ret;
  10956. // '[' and ']' per tag
  10957. std::size_t full_size = 2 * tags.size();
  10958. for (const auto& tag : tags) {
  10959. full_size += tag.size();
  10960. }
  10961. ret.reserve(full_size);
  10962. for (const auto& tag : tags) {
  10963. ret.push_back('[');
  10964. ret.append(tag);
  10965. ret.push_back(']');
  10966. }
  10967. return ret;
  10968. }
  10969. TestCase::TestCase( ITestInvoker* testCase, TestCaseInfo&& info ) : TestCaseInfo( std::move(info) ), test( testCase ) {}
  10970. TestCase TestCase::withName( std::string const& _newName ) const {
  10971. TestCase other( *this );
  10972. other.name = _newName;
  10973. return other;
  10974. }
  10975. void TestCase::invoke() const {
  10976. test->invoke();
  10977. }
  10978. bool TestCase::operator == ( TestCase const& other ) const {
  10979. return test.get() == other.test.get() &&
  10980. name == other.name &&
  10981. className == other.className;
  10982. }
  10983. bool TestCase::operator < ( TestCase const& other ) const {
  10984. return name < other.name;
  10985. }
  10986. TestCaseInfo const& TestCase::getTestCaseInfo() const
  10987. {
  10988. return *this;
  10989. }
  10990. } // end namespace Catch
  10991. // end catch_test_case_info.cpp
  10992. // start catch_test_case_registry_impl.cpp
  10993. #include <sstream>
  10994. namespace Catch {
  10995. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases ) {
  10996. std::vector<TestCase> sorted = unsortedTestCases;
  10997. switch( config.runOrder() ) {
  10998. case RunTests::InLexicographicalOrder:
  10999. std::sort( sorted.begin(), sorted.end() );
  11000. break;
  11001. case RunTests::InRandomOrder:
  11002. seedRng( config );
  11003. std::shuffle( sorted.begin(), sorted.end(), rng() );
  11004. break;
  11005. case RunTests::InDeclarationOrder:
  11006. // already in declaration order
  11007. break;
  11008. }
  11009. return sorted;
  11010. }
  11011. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ) {
  11012. return testSpec.matches( testCase ) && ( config.allowThrows() || !testCase.throws() );
  11013. }
  11014. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions ) {
  11015. std::set<TestCase> seenFunctions;
  11016. for( auto const& function : functions ) {
  11017. auto prev = seenFunctions.insert( function );
  11018. CATCH_ENFORCE( prev.second,
  11019. "error: TEST_CASE( \"" << function.name << "\" ) already defined.\n"
  11020. << "\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo << "\n"
  11021. << "\tRedefined at " << function.getTestCaseInfo().lineInfo );
  11022. }
  11023. }
  11024. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config ) {
  11025. std::vector<TestCase> filtered;
  11026. filtered.reserve( testCases.size() );
  11027. for (auto const& testCase : testCases) {
  11028. if ((!testSpec.hasFilters() && !testCase.isHidden()) ||
  11029. (testSpec.hasFilters() && matchTest(testCase, testSpec, config))) {
  11030. filtered.push_back(testCase);
  11031. }
  11032. }
  11033. return filtered;
  11034. }
  11035. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config ) {
  11036. return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config );
  11037. }
  11038. void TestRegistry::registerTest( TestCase const& testCase ) {
  11039. std::string name = testCase.getTestCaseInfo().name;
  11040. if( name.empty() ) {
  11041. ReusableStringStream rss;
  11042. rss << "Anonymous test case " << ++m_unnamedCount;
  11043. return registerTest( testCase.withName( rss.str() ) );
  11044. }
  11045. m_functions.push_back( testCase );
  11046. }
  11047. std::vector<TestCase> const& TestRegistry::getAllTests() const {
  11048. return m_functions;
  11049. }
  11050. std::vector<TestCase> const& TestRegistry::getAllTestsSorted( IConfig const& config ) const {
  11051. if( m_sortedFunctions.empty() )
  11052. enforceNoDuplicateTestCases( m_functions );
  11053. if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) {
  11054. m_sortedFunctions = sortTests( config, m_functions );
  11055. m_currentSortOrder = config.runOrder();
  11056. }
  11057. return m_sortedFunctions;
  11058. }
  11059. ///////////////////////////////////////////////////////////////////////////
  11060. TestInvokerAsFunction::TestInvokerAsFunction( void(*testAsFunction)() ) noexcept : m_testAsFunction( testAsFunction ) {}
  11061. void TestInvokerAsFunction::invoke() const {
  11062. m_testAsFunction();
  11063. }
  11064. std::string extractClassName( StringRef const& classOrQualifiedMethodName ) {
  11065. std::string className = classOrQualifiedMethodName;
  11066. if( startsWith( className, '&' ) )
  11067. {
  11068. std::size_t lastColons = className.rfind( "::" );
  11069. std::size_t penultimateColons = className.rfind( "::", lastColons-1 );
  11070. if( penultimateColons == std::string::npos )
  11071. penultimateColons = 1;
  11072. className = className.substr( penultimateColons, lastColons-penultimateColons );
  11073. }
  11074. return className;
  11075. }
  11076. } // end namespace Catch
  11077. // end catch_test_case_registry_impl.cpp
  11078. // start catch_test_case_tracker.cpp
  11079. #include <algorithm>
  11080. #include <cassert>
  11081. #include <stdexcept>
  11082. #include <memory>
  11083. #include <sstream>
  11084. #if defined(__clang__)
  11085. # pragma clang diagnostic push
  11086. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  11087. #endif
  11088. namespace Catch {
  11089. namespace TestCaseTracking {
  11090. NameAndLocation::NameAndLocation( std::string const& _name, SourceLineInfo const& _location )
  11091. : name( _name ),
  11092. location( _location )
  11093. {}
  11094. ITracker::~ITracker() = default;
  11095. ITracker& TrackerContext::startRun() {
  11096. m_rootTracker = std::make_shared<SectionTracker>( NameAndLocation( "{root}", CATCH_INTERNAL_LINEINFO ), *this, nullptr );
  11097. m_currentTracker = nullptr;
  11098. m_runState = Executing;
  11099. return *m_rootTracker;
  11100. }
  11101. void TrackerContext::endRun() {
  11102. m_rootTracker.reset();
  11103. m_currentTracker = nullptr;
  11104. m_runState = NotStarted;
  11105. }
  11106. void TrackerContext::startCycle() {
  11107. m_currentTracker = m_rootTracker.get();
  11108. m_runState = Executing;
  11109. }
  11110. void TrackerContext::completeCycle() {
  11111. m_runState = CompletedCycle;
  11112. }
  11113. bool TrackerContext::completedCycle() const {
  11114. return m_runState == CompletedCycle;
  11115. }
  11116. ITracker& TrackerContext::currentTracker() {
  11117. return *m_currentTracker;
  11118. }
  11119. void TrackerContext::setCurrentTracker( ITracker* tracker ) {
  11120. m_currentTracker = tracker;
  11121. }
  11122. TrackerBase::TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  11123. : m_nameAndLocation( nameAndLocation ),
  11124. m_ctx( ctx ),
  11125. m_parent( parent )
  11126. {}
  11127. NameAndLocation const& TrackerBase::nameAndLocation() const {
  11128. return m_nameAndLocation;
  11129. }
  11130. bool TrackerBase::isComplete() const {
  11131. return m_runState == CompletedSuccessfully || m_runState == Failed;
  11132. }
  11133. bool TrackerBase::isSuccessfullyCompleted() const {
  11134. return m_runState == CompletedSuccessfully;
  11135. }
  11136. bool TrackerBase::isOpen() const {
  11137. return m_runState != NotStarted && !isComplete();
  11138. }
  11139. bool TrackerBase::hasChildren() const {
  11140. return !m_children.empty();
  11141. }
  11142. void TrackerBase::addChild( ITrackerPtr const& child ) {
  11143. m_children.push_back( child );
  11144. }
  11145. ITrackerPtr TrackerBase::findChild( NameAndLocation const& nameAndLocation ) {
  11146. auto it = std::find_if( m_children.begin(), m_children.end(),
  11147. [&nameAndLocation]( ITrackerPtr const& tracker ){
  11148. return
  11149. tracker->nameAndLocation().location == nameAndLocation.location &&
  11150. tracker->nameAndLocation().name == nameAndLocation.name;
  11151. } );
  11152. return( it != m_children.end() )
  11153. ? *it
  11154. : nullptr;
  11155. }
  11156. ITracker& TrackerBase::parent() {
  11157. assert( m_parent ); // Should always be non-null except for root
  11158. return *m_parent;
  11159. }
  11160. void TrackerBase::openChild() {
  11161. if( m_runState != ExecutingChildren ) {
  11162. m_runState = ExecutingChildren;
  11163. if( m_parent )
  11164. m_parent->openChild();
  11165. }
  11166. }
  11167. bool TrackerBase::isSectionTracker() const { return false; }
  11168. bool TrackerBase::isGeneratorTracker() const { return false; }
  11169. void TrackerBase::open() {
  11170. m_runState = Executing;
  11171. moveToThis();
  11172. if( m_parent )
  11173. m_parent->openChild();
  11174. }
  11175. void TrackerBase::close() {
  11176. // Close any still open children (e.g. generators)
  11177. while( &m_ctx.currentTracker() != this )
  11178. m_ctx.currentTracker().close();
  11179. switch( m_runState ) {
  11180. case NeedsAnotherRun:
  11181. break;
  11182. case Executing:
  11183. m_runState = CompletedSuccessfully;
  11184. break;
  11185. case ExecutingChildren:
  11186. if( m_children.empty() || m_children.back()->isComplete() )
  11187. m_runState = CompletedSuccessfully;
  11188. break;
  11189. case NotStarted:
  11190. case CompletedSuccessfully:
  11191. case Failed:
  11192. CATCH_INTERNAL_ERROR( "Illogical state: " << m_runState );
  11193. default:
  11194. CATCH_INTERNAL_ERROR( "Unknown state: " << m_runState );
  11195. }
  11196. moveToParent();
  11197. m_ctx.completeCycle();
  11198. }
  11199. void TrackerBase::fail() {
  11200. m_runState = Failed;
  11201. if( m_parent )
  11202. m_parent->markAsNeedingAnotherRun();
  11203. moveToParent();
  11204. m_ctx.completeCycle();
  11205. }
  11206. void TrackerBase::markAsNeedingAnotherRun() {
  11207. m_runState = NeedsAnotherRun;
  11208. }
  11209. void TrackerBase::moveToParent() {
  11210. assert( m_parent );
  11211. m_ctx.setCurrentTracker( m_parent );
  11212. }
  11213. void TrackerBase::moveToThis() {
  11214. m_ctx.setCurrentTracker( this );
  11215. }
  11216. SectionTracker::SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  11217. : TrackerBase( nameAndLocation, ctx, parent )
  11218. {
  11219. if( parent ) {
  11220. while( !parent->isSectionTracker() )
  11221. parent = &parent->parent();
  11222. SectionTracker& parentSection = static_cast<SectionTracker&>( *parent );
  11223. addNextFilters( parentSection.m_filters );
  11224. }
  11225. }
  11226. bool SectionTracker::isComplete() const {
  11227. bool complete = true;
  11228. if ((m_filters.empty() || m_filters[0] == "") ||
  11229. std::find(m_filters.begin(), m_filters.end(),
  11230. m_nameAndLocation.name) != m_filters.end())
  11231. complete = TrackerBase::isComplete();
  11232. return complete;
  11233. }
  11234. bool SectionTracker::isSectionTracker() const { return true; }
  11235. SectionTracker& SectionTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ) {
  11236. std::shared_ptr<SectionTracker> section;
  11237. ITracker& currentTracker = ctx.currentTracker();
  11238. if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  11239. assert( childTracker );
  11240. assert( childTracker->isSectionTracker() );
  11241. section = std::static_pointer_cast<SectionTracker>( childTracker );
  11242. }
  11243. else {
  11244. section = std::make_shared<SectionTracker>( nameAndLocation, ctx, &currentTracker );
  11245. currentTracker.addChild( section );
  11246. }
  11247. if( !ctx.completedCycle() )
  11248. section->tryOpen();
  11249. return *section;
  11250. }
  11251. void SectionTracker::tryOpen() {
  11252. if( !isComplete() && (m_filters.empty() || m_filters[0].empty() || m_filters[0] == m_nameAndLocation.name ) )
  11253. open();
  11254. }
  11255. void SectionTracker::addInitialFilters( std::vector<std::string> const& filters ) {
  11256. if( !filters.empty() ) {
  11257. m_filters.push_back(""); // Root - should never be consulted
  11258. m_filters.push_back(""); // Test Case - not a section filter
  11259. m_filters.insert( m_filters.end(), filters.begin(), filters.end() );
  11260. }
  11261. }
  11262. void SectionTracker::addNextFilters( std::vector<std::string> const& filters ) {
  11263. if( filters.size() > 1 )
  11264. m_filters.insert( m_filters.end(), ++filters.begin(), filters.end() );
  11265. }
  11266. } // namespace TestCaseTracking
  11267. using TestCaseTracking::ITracker;
  11268. using TestCaseTracking::TrackerContext;
  11269. using TestCaseTracking::SectionTracker;
  11270. } // namespace Catch
  11271. #if defined(__clang__)
  11272. # pragma clang diagnostic pop
  11273. #endif
  11274. // end catch_test_case_tracker.cpp
  11275. // start catch_test_registry.cpp
  11276. namespace Catch {
  11277. auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker* {
  11278. return new(std::nothrow) TestInvokerAsFunction( testAsFunction );
  11279. }
  11280. NameAndTags::NameAndTags( StringRef const& name_ , StringRef const& tags_ ) noexcept : name( name_ ), tags( tags_ ) {}
  11281. AutoReg::AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept {
  11282. CATCH_TRY {
  11283. getMutableRegistryHub()
  11284. .registerTest(
  11285. makeTestCase(
  11286. invoker,
  11287. extractClassName( classOrMethod ),
  11288. nameAndTags,
  11289. lineInfo));
  11290. } CATCH_CATCH_ALL {
  11291. // Do not throw when constructing global objects, instead register the exception to be processed later
  11292. getMutableRegistryHub().registerStartupException();
  11293. }
  11294. }
  11295. AutoReg::~AutoReg() = default;
  11296. }
  11297. // end catch_test_registry.cpp
  11298. // start catch_test_spec.cpp
  11299. #include <algorithm>
  11300. #include <string>
  11301. #include <vector>
  11302. #include <memory>
  11303. namespace Catch {
  11304. TestSpec::Pattern::~Pattern() = default;
  11305. TestSpec::NamePattern::~NamePattern() = default;
  11306. TestSpec::TagPattern::~TagPattern() = default;
  11307. TestSpec::ExcludedPattern::~ExcludedPattern() = default;
  11308. TestSpec::NamePattern::NamePattern( std::string const& name )
  11309. : m_wildcardPattern( toLower( name ), CaseSensitive::No )
  11310. {}
  11311. bool TestSpec::NamePattern::matches( TestCaseInfo const& testCase ) const {
  11312. return m_wildcardPattern.matches( toLower( testCase.name ) );
  11313. }
  11314. TestSpec::TagPattern::TagPattern( std::string const& tag ) : m_tag( toLower( tag ) ) {}
  11315. bool TestSpec::TagPattern::matches( TestCaseInfo const& testCase ) const {
  11316. return std::find(begin(testCase.lcaseTags),
  11317. end(testCase.lcaseTags),
  11318. m_tag) != end(testCase.lcaseTags);
  11319. }
  11320. TestSpec::ExcludedPattern::ExcludedPattern( PatternPtr const& underlyingPattern ) : m_underlyingPattern( underlyingPattern ) {}
  11321. bool TestSpec::ExcludedPattern::matches( TestCaseInfo const& testCase ) const { return !m_underlyingPattern->matches( testCase ); }
  11322. bool TestSpec::Filter::matches( TestCaseInfo const& testCase ) const {
  11323. // All patterns in a filter must match for the filter to be a match
  11324. for( auto const& pattern : m_patterns ) {
  11325. if( !pattern->matches( testCase ) )
  11326. return false;
  11327. }
  11328. return true;
  11329. }
  11330. bool TestSpec::hasFilters() const {
  11331. return !m_filters.empty();
  11332. }
  11333. bool TestSpec::matches( TestCaseInfo const& testCase ) const {
  11334. // A TestSpec matches if any filter matches
  11335. for( auto const& filter : m_filters )
  11336. if( filter.matches( testCase ) )
  11337. return true;
  11338. return false;
  11339. }
  11340. }
  11341. // end catch_test_spec.cpp
  11342. // start catch_test_spec_parser.cpp
  11343. namespace Catch {
  11344. TestSpecParser::TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {}
  11345. TestSpecParser& TestSpecParser::parse( std::string const& arg ) {
  11346. m_mode = None;
  11347. m_exclusion = false;
  11348. m_start = std::string::npos;
  11349. m_arg = m_tagAliases->expandAliases( arg );
  11350. m_escapeChars.clear();
  11351. for( m_pos = 0; m_pos < m_arg.size(); ++m_pos )
  11352. visitChar( m_arg[m_pos] );
  11353. if( m_mode == Name )
  11354. addPattern<TestSpec::NamePattern>();
  11355. return *this;
  11356. }
  11357. TestSpec TestSpecParser::testSpec() {
  11358. addFilter();
  11359. return m_testSpec;
  11360. }
  11361. void TestSpecParser::visitChar( char c ) {
  11362. if( m_mode == None ) {
  11363. switch( c ) {
  11364. case ' ': return;
  11365. case '~': m_exclusion = true; return;
  11366. case '[': return startNewMode( Tag, ++m_pos );
  11367. case '"': return startNewMode( QuotedName, ++m_pos );
  11368. case '\\': return escape();
  11369. default: startNewMode( Name, m_pos ); break;
  11370. }
  11371. }
  11372. if( m_mode == Name ) {
  11373. if( c == ',' ) {
  11374. addPattern<TestSpec::NamePattern>();
  11375. addFilter();
  11376. }
  11377. else if( c == '[' ) {
  11378. if( subString() == "exclude:" )
  11379. m_exclusion = true;
  11380. else
  11381. addPattern<TestSpec::NamePattern>();
  11382. startNewMode( Tag, ++m_pos );
  11383. }
  11384. else if( c == '\\' )
  11385. escape();
  11386. }
  11387. else if( m_mode == EscapedName )
  11388. m_mode = Name;
  11389. else if( m_mode == QuotedName && c == '"' )
  11390. addPattern<TestSpec::NamePattern>();
  11391. else if( m_mode == Tag && c == ']' )
  11392. addPattern<TestSpec::TagPattern>();
  11393. }
  11394. void TestSpecParser::startNewMode( Mode mode, std::size_t start ) {
  11395. m_mode = mode;
  11396. m_start = start;
  11397. }
  11398. void TestSpecParser::escape() {
  11399. if( m_mode == None )
  11400. m_start = m_pos;
  11401. m_mode = EscapedName;
  11402. m_escapeChars.push_back( m_pos );
  11403. }
  11404. std::string TestSpecParser::subString() const { return m_arg.substr( m_start, m_pos - m_start ); }
  11405. void TestSpecParser::addFilter() {
  11406. if( !m_currentFilter.m_patterns.empty() ) {
  11407. m_testSpec.m_filters.push_back( m_currentFilter );
  11408. m_currentFilter = TestSpec::Filter();
  11409. }
  11410. }
  11411. TestSpec parseTestSpec( std::string const& arg ) {
  11412. return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec();
  11413. }
  11414. } // namespace Catch
  11415. // end catch_test_spec_parser.cpp
  11416. // start catch_timer.cpp
  11417. #include <chrono>
  11418. static const uint64_t nanosecondsInSecond = 1000000000;
  11419. namespace Catch {
  11420. auto getCurrentNanosecondsSinceEpoch() -> uint64_t {
  11421. return std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::high_resolution_clock::now().time_since_epoch() ).count();
  11422. }
  11423. namespace {
  11424. auto estimateClockResolution() -> uint64_t {
  11425. uint64_t sum = 0;
  11426. static const uint64_t iterations = 1000000;
  11427. auto startTime = getCurrentNanosecondsSinceEpoch();
  11428. for( std::size_t i = 0; i < iterations; ++i ) {
  11429. uint64_t ticks;
  11430. uint64_t baseTicks = getCurrentNanosecondsSinceEpoch();
  11431. do {
  11432. ticks = getCurrentNanosecondsSinceEpoch();
  11433. } while( ticks == baseTicks );
  11434. auto delta = ticks - baseTicks;
  11435. sum += delta;
  11436. // If we have been calibrating for over 3 seconds -- the clock
  11437. // is terrible and we should move on.
  11438. // TBD: How to signal that the measured resolution is probably wrong?
  11439. if (ticks > startTime + 3 * nanosecondsInSecond) {
  11440. return sum / ( i + 1u );
  11441. }
  11442. }
  11443. // We're just taking the mean, here. To do better we could take the std. dev and exclude outliers
  11444. // - and potentially do more iterations if there's a high variance.
  11445. return sum/iterations;
  11446. }
  11447. }
  11448. auto getEstimatedClockResolution() -> uint64_t {
  11449. static auto s_resolution = estimateClockResolution();
  11450. return s_resolution;
  11451. }
  11452. void Timer::start() {
  11453. m_nanoseconds = getCurrentNanosecondsSinceEpoch();
  11454. }
  11455. auto Timer::getElapsedNanoseconds() const -> uint64_t {
  11456. return getCurrentNanosecondsSinceEpoch() - m_nanoseconds;
  11457. }
  11458. auto Timer::getElapsedMicroseconds() const -> uint64_t {
  11459. return getElapsedNanoseconds()/1000;
  11460. }
  11461. auto Timer::getElapsedMilliseconds() const -> unsigned int {
  11462. return static_cast<unsigned int>(getElapsedMicroseconds()/1000);
  11463. }
  11464. auto Timer::getElapsedSeconds() const -> double {
  11465. return getElapsedMicroseconds()/1000000.0;
  11466. }
  11467. } // namespace Catch
  11468. // end catch_timer.cpp
  11469. // start catch_tostring.cpp
  11470. #if defined(__clang__)
  11471. # pragma clang diagnostic push
  11472. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  11473. # pragma clang diagnostic ignored "-Wglobal-constructors"
  11474. #endif
  11475. // Enable specific decls locally
  11476. #if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  11477. #define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  11478. #endif
  11479. #include <cmath>
  11480. #include <iomanip>
  11481. namespace Catch {
  11482. namespace Detail {
  11483. const std::string unprintableString = "{?}";
  11484. namespace {
  11485. const int hexThreshold = 255;
  11486. struct Endianness {
  11487. enum Arch { Big, Little };
  11488. static Arch which() {
  11489. union _{
  11490. int asInt;
  11491. char asChar[sizeof (int)];
  11492. } u;
  11493. u.asInt = 1;
  11494. return ( u.asChar[sizeof(int)-1] == 1 ) ? Big : Little;
  11495. }
  11496. };
  11497. }
  11498. std::string rawMemoryToString( const void *object, std::size_t size ) {
  11499. // Reverse order for little endian architectures
  11500. int i = 0, end = static_cast<int>( size ), inc = 1;
  11501. if( Endianness::which() == Endianness::Little ) {
  11502. i = end-1;
  11503. end = inc = -1;
  11504. }
  11505. unsigned char const *bytes = static_cast<unsigned char const *>(object);
  11506. ReusableStringStream rss;
  11507. rss << "0x" << std::setfill('0') << std::hex;
  11508. for( ; i != end; i += inc )
  11509. rss << std::setw(2) << static_cast<unsigned>(bytes[i]);
  11510. return rss.str();
  11511. }
  11512. }
  11513. template<typename T>
  11514. std::string fpToString( T value, int precision ) {
  11515. if (Catch::isnan(value)) {
  11516. return "nan";
  11517. }
  11518. ReusableStringStream rss;
  11519. rss << std::setprecision( precision )
  11520. << std::fixed
  11521. << value;
  11522. std::string d = rss.str();
  11523. std::size_t i = d.find_last_not_of( '0' );
  11524. if( i != std::string::npos && i != d.size()-1 ) {
  11525. if( d[i] == '.' )
  11526. i++;
  11527. d = d.substr( 0, i+1 );
  11528. }
  11529. return d;
  11530. }
  11531. //// ======================================================= ////
  11532. //
  11533. // Out-of-line defs for full specialization of StringMaker
  11534. //
  11535. //// ======================================================= ////
  11536. std::string StringMaker<std::string>::convert(const std::string& str) {
  11537. if (!getCurrentContext().getConfig()->showInvisibles()) {
  11538. return '"' + str + '"';
  11539. }
  11540. std::string s("\"");
  11541. for (char c : str) {
  11542. switch (c) {
  11543. case '\n':
  11544. s.append("\\n");
  11545. break;
  11546. case '\t':
  11547. s.append("\\t");
  11548. break;
  11549. default:
  11550. s.push_back(c);
  11551. break;
  11552. }
  11553. }
  11554. s.append("\"");
  11555. return s;
  11556. }
  11557. #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  11558. std::string StringMaker<std::string_view>::convert(std::string_view str) {
  11559. return ::Catch::Detail::stringify(std::string{ str });
  11560. }
  11561. #endif
  11562. std::string StringMaker<char const*>::convert(char const* str) {
  11563. if (str) {
  11564. return ::Catch::Detail::stringify(std::string{ str });
  11565. } else {
  11566. return{ "{null string}" };
  11567. }
  11568. }
  11569. std::string StringMaker<char*>::convert(char* str) {
  11570. if (str) {
  11571. return ::Catch::Detail::stringify(std::string{ str });
  11572. } else {
  11573. return{ "{null string}" };
  11574. }
  11575. }
  11576. #ifdef CATCH_CONFIG_WCHAR
  11577. std::string StringMaker<std::wstring>::convert(const std::wstring& wstr) {
  11578. std::string s;
  11579. s.reserve(wstr.size());
  11580. for (auto c : wstr) {
  11581. s += (c <= 0xff) ? static_cast<char>(c) : '?';
  11582. }
  11583. return ::Catch::Detail::stringify(s);
  11584. }
  11585. # ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  11586. std::string StringMaker<std::wstring_view>::convert(std::wstring_view str) {
  11587. return StringMaker<std::wstring>::convert(std::wstring(str));
  11588. }
  11589. # endif
  11590. std::string StringMaker<wchar_t const*>::convert(wchar_t const * str) {
  11591. if (str) {
  11592. return ::Catch::Detail::stringify(std::wstring{ str });
  11593. } else {
  11594. return{ "{null string}" };
  11595. }
  11596. }
  11597. std::string StringMaker<wchar_t *>::convert(wchar_t * str) {
  11598. if (str) {
  11599. return ::Catch::Detail::stringify(std::wstring{ str });
  11600. } else {
  11601. return{ "{null string}" };
  11602. }
  11603. }
  11604. #endif
  11605. std::string StringMaker<int>::convert(int value) {
  11606. return ::Catch::Detail::stringify(static_cast<long long>(value));
  11607. }
  11608. std::string StringMaker<long>::convert(long value) {
  11609. return ::Catch::Detail::stringify(static_cast<long long>(value));
  11610. }
  11611. std::string StringMaker<long long>::convert(long long value) {
  11612. ReusableStringStream rss;
  11613. rss << value;
  11614. if (value > Detail::hexThreshold) {
  11615. rss << " (0x" << std::hex << value << ')';
  11616. }
  11617. return rss.str();
  11618. }
  11619. std::string StringMaker<unsigned int>::convert(unsigned int value) {
  11620. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  11621. }
  11622. std::string StringMaker<unsigned long>::convert(unsigned long value) {
  11623. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  11624. }
  11625. std::string StringMaker<unsigned long long>::convert(unsigned long long value) {
  11626. ReusableStringStream rss;
  11627. rss << value;
  11628. if (value > Detail::hexThreshold) {
  11629. rss << " (0x" << std::hex << value << ')';
  11630. }
  11631. return rss.str();
  11632. }
  11633. std::string StringMaker<bool>::convert(bool b) {
  11634. return b ? "true" : "false";
  11635. }
  11636. std::string StringMaker<signed char>::convert(signed char value) {
  11637. if (value == '\r') {
  11638. return "'\\r'";
  11639. } else if (value == '\f') {
  11640. return "'\\f'";
  11641. } else if (value == '\n') {
  11642. return "'\\n'";
  11643. } else if (value == '\t') {
  11644. return "'\\t'";
  11645. } else if ('\0' <= value && value < ' ') {
  11646. return ::Catch::Detail::stringify(static_cast<unsigned int>(value));
  11647. } else {
  11648. char chstr[] = "' '";
  11649. chstr[1] = value;
  11650. return chstr;
  11651. }
  11652. }
  11653. std::string StringMaker<char>::convert(char c) {
  11654. return ::Catch::Detail::stringify(static_cast<signed char>(c));
  11655. }
  11656. std::string StringMaker<unsigned char>::convert(unsigned char c) {
  11657. return ::Catch::Detail::stringify(static_cast<char>(c));
  11658. }
  11659. std::string StringMaker<std::nullptr_t>::convert(std::nullptr_t) {
  11660. return "nullptr";
  11661. }
  11662. int StringMaker<float>::precision = 5;
  11663. std::string StringMaker<float>::convert(float value) {
  11664. return fpToString(value, precision) + 'f';
  11665. }
  11666. int StringMaker<double>::precision = 10;
  11667. std::string StringMaker<double>::convert(double value) {
  11668. return fpToString(value, precision);
  11669. }
  11670. std::string ratio_string<std::atto>::symbol() { return "a"; }
  11671. std::string ratio_string<std::femto>::symbol() { return "f"; }
  11672. std::string ratio_string<std::pico>::symbol() { return "p"; }
  11673. std::string ratio_string<std::nano>::symbol() { return "n"; }
  11674. std::string ratio_string<std::micro>::symbol() { return "u"; }
  11675. std::string ratio_string<std::milli>::symbol() { return "m"; }
  11676. } // end namespace Catch
  11677. #if defined(__clang__)
  11678. # pragma clang diagnostic pop
  11679. #endif
  11680. // end catch_tostring.cpp
  11681. // start catch_totals.cpp
  11682. namespace Catch {
  11683. Counts Counts::operator - ( Counts const& other ) const {
  11684. Counts diff;
  11685. diff.passed = passed - other.passed;
  11686. diff.failed = failed - other.failed;
  11687. diff.failedButOk = failedButOk - other.failedButOk;
  11688. return diff;
  11689. }
  11690. Counts& Counts::operator += ( Counts const& other ) {
  11691. passed += other.passed;
  11692. failed += other.failed;
  11693. failedButOk += other.failedButOk;
  11694. return *this;
  11695. }
  11696. std::size_t Counts::total() const {
  11697. return passed + failed + failedButOk;
  11698. }
  11699. bool Counts::allPassed() const {
  11700. return failed == 0 && failedButOk == 0;
  11701. }
  11702. bool Counts::allOk() const {
  11703. return failed == 0;
  11704. }
  11705. Totals Totals::operator - ( Totals const& other ) const {
  11706. Totals diff;
  11707. diff.assertions = assertions - other.assertions;
  11708. diff.testCases = testCases - other.testCases;
  11709. return diff;
  11710. }
  11711. Totals& Totals::operator += ( Totals const& other ) {
  11712. assertions += other.assertions;
  11713. testCases += other.testCases;
  11714. return *this;
  11715. }
  11716. Totals Totals::delta( Totals const& prevTotals ) const {
  11717. Totals diff = *this - prevTotals;
  11718. if( diff.assertions.failed > 0 )
  11719. ++diff.testCases.failed;
  11720. else if( diff.assertions.failedButOk > 0 )
  11721. ++diff.testCases.failedButOk;
  11722. else
  11723. ++diff.testCases.passed;
  11724. return diff;
  11725. }
  11726. }
  11727. // end catch_totals.cpp
  11728. // start catch_uncaught_exceptions.cpp
  11729. #include <exception>
  11730. namespace Catch {
  11731. bool uncaught_exceptions() {
  11732. #if defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
  11733. return std::uncaught_exceptions() > 0;
  11734. #else
  11735. return std::uncaught_exception();
  11736. #endif
  11737. }
  11738. } // end namespace Catch
  11739. // end catch_uncaught_exceptions.cpp
  11740. // start catch_version.cpp
  11741. #include <ostream>
  11742. namespace Catch {
  11743. Version::Version
  11744. ( unsigned int _majorVersion,
  11745. unsigned int _minorVersion,
  11746. unsigned int _patchNumber,
  11747. char const * const _branchName,
  11748. unsigned int _buildNumber )
  11749. : majorVersion( _majorVersion ),
  11750. minorVersion( _minorVersion ),
  11751. patchNumber( _patchNumber ),
  11752. branchName( _branchName ),
  11753. buildNumber( _buildNumber )
  11754. {}
  11755. std::ostream& operator << ( std::ostream& os, Version const& version ) {
  11756. os << version.majorVersion << '.'
  11757. << version.minorVersion << '.'
  11758. << version.patchNumber;
  11759. // branchName is never null -> 0th char is \0 if it is empty
  11760. if (version.branchName[0]) {
  11761. os << '-' << version.branchName
  11762. << '.' << version.buildNumber;
  11763. }
  11764. return os;
  11765. }
  11766. Version const& libraryVersion() {
  11767. static Version version( 2, 9, 0, "", 0 );
  11768. return version;
  11769. }
  11770. }
  11771. // end catch_version.cpp
  11772. // start catch_wildcard_pattern.cpp
  11773. #include <sstream>
  11774. namespace Catch {
  11775. WildcardPattern::WildcardPattern( std::string const& pattern,
  11776. CaseSensitive::Choice caseSensitivity )
  11777. : m_caseSensitivity( caseSensitivity ),
  11778. m_pattern( adjustCase( pattern ) )
  11779. {
  11780. if( startsWith( m_pattern, '*' ) ) {
  11781. m_pattern = m_pattern.substr( 1 );
  11782. m_wildcard = WildcardAtStart;
  11783. }
  11784. if( endsWith( m_pattern, '*' ) ) {
  11785. m_pattern = m_pattern.substr( 0, m_pattern.size()-1 );
  11786. m_wildcard = static_cast<WildcardPosition>( m_wildcard | WildcardAtEnd );
  11787. }
  11788. }
  11789. bool WildcardPattern::matches( std::string const& str ) const {
  11790. switch( m_wildcard ) {
  11791. case NoWildcard:
  11792. return m_pattern == adjustCase( str );
  11793. case WildcardAtStart:
  11794. return endsWith( adjustCase( str ), m_pattern );
  11795. case WildcardAtEnd:
  11796. return startsWith( adjustCase( str ), m_pattern );
  11797. case WildcardAtBothEnds:
  11798. return contains( adjustCase( str ), m_pattern );
  11799. default:
  11800. CATCH_INTERNAL_ERROR( "Unknown enum" );
  11801. }
  11802. }
  11803. std::string WildcardPattern::adjustCase( std::string const& str ) const {
  11804. return m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str;
  11805. }
  11806. }
  11807. // end catch_wildcard_pattern.cpp
  11808. // start catch_xmlwriter.cpp
  11809. #include <iomanip>
  11810. using uchar = unsigned char;
  11811. namespace Catch {
  11812. namespace {
  11813. size_t trailingBytes(unsigned char c) {
  11814. if ((c & 0xE0) == 0xC0) {
  11815. return 2;
  11816. }
  11817. if ((c & 0xF0) == 0xE0) {
  11818. return 3;
  11819. }
  11820. if ((c & 0xF8) == 0xF0) {
  11821. return 4;
  11822. }
  11823. CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
  11824. }
  11825. uint32_t headerValue(unsigned char c) {
  11826. if ((c & 0xE0) == 0xC0) {
  11827. return c & 0x1F;
  11828. }
  11829. if ((c & 0xF0) == 0xE0) {
  11830. return c & 0x0F;
  11831. }
  11832. if ((c & 0xF8) == 0xF0) {
  11833. return c & 0x07;
  11834. }
  11835. CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
  11836. }
  11837. void hexEscapeChar(std::ostream& os, unsigned char c) {
  11838. std::ios_base::fmtflags f(os.flags());
  11839. os << "\\x"
  11840. << std::uppercase << std::hex << std::setfill('0') << std::setw(2)
  11841. << static_cast<int>(c);
  11842. os.flags(f);
  11843. }
  11844. } // anonymous namespace
  11845. XmlEncode::XmlEncode( std::string const& str, ForWhat forWhat )
  11846. : m_str( str ),
  11847. m_forWhat( forWhat )
  11848. {}
  11849. void XmlEncode::encodeTo( std::ostream& os ) const {
  11850. // Apostrophe escaping not necessary if we always use " to write attributes
  11851. // (see: http://www.w3.org/TR/xml/#syntax)
  11852. for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) {
  11853. uchar c = m_str[idx];
  11854. switch (c) {
  11855. case '<': os << "&lt;"; break;
  11856. case '&': os << "&amp;"; break;
  11857. case '>':
  11858. // See: http://www.w3.org/TR/xml/#syntax
  11859. if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']')
  11860. os << "&gt;";
  11861. else
  11862. os << c;
  11863. break;
  11864. case '\"':
  11865. if (m_forWhat == ForAttributes)
  11866. os << "&quot;";
  11867. else
  11868. os << c;
  11869. break;
  11870. default:
  11871. // Check for control characters and invalid utf-8
  11872. // Escape control characters in standard ascii
  11873. // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0
  11874. if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) {
  11875. hexEscapeChar(os, c);
  11876. break;
  11877. }
  11878. // Plain ASCII: Write it to stream
  11879. if (c < 0x7F) {
  11880. os << c;
  11881. break;
  11882. }
  11883. // UTF-8 territory
  11884. // Check if the encoding is valid and if it is not, hex escape bytes.
  11885. // Important: We do not check the exact decoded values for validity, only the encoding format
  11886. // First check that this bytes is a valid lead byte:
  11887. // This means that it is not encoded as 1111 1XXX
  11888. // Or as 10XX XXXX
  11889. if (c < 0xC0 ||
  11890. c >= 0xF8) {
  11891. hexEscapeChar(os, c);
  11892. break;
  11893. }
  11894. auto encBytes = trailingBytes(c);
  11895. // Are there enough bytes left to avoid accessing out-of-bounds memory?
  11896. if (idx + encBytes - 1 >= m_str.size()) {
  11897. hexEscapeChar(os, c);
  11898. break;
  11899. }
  11900. // The header is valid, check data
  11901. // The next encBytes bytes must together be a valid utf-8
  11902. // This means: bitpattern 10XX XXXX and the extracted value is sane (ish)
  11903. bool valid = true;
  11904. uint32_t value = headerValue(c);
  11905. for (std::size_t n = 1; n < encBytes; ++n) {
  11906. uchar nc = m_str[idx + n];
  11907. valid &= ((nc & 0xC0) == 0x80);
  11908. value = (value << 6) | (nc & 0x3F);
  11909. }
  11910. if (
  11911. // Wrong bit pattern of following bytes
  11912. (!valid) ||
  11913. // Overlong encodings
  11914. (value < 0x80) ||
  11915. (0x80 <= value && value < 0x800 && encBytes > 2) ||
  11916. (0x800 < value && value < 0x10000 && encBytes > 3) ||
  11917. // Encoded value out of range
  11918. (value >= 0x110000)
  11919. ) {
  11920. hexEscapeChar(os, c);
  11921. break;
  11922. }
  11923. // If we got here, this is in fact a valid(ish) utf-8 sequence
  11924. for (std::size_t n = 0; n < encBytes; ++n) {
  11925. os << m_str[idx + n];
  11926. }
  11927. idx += encBytes - 1;
  11928. break;
  11929. }
  11930. }
  11931. }
  11932. std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) {
  11933. xmlEncode.encodeTo( os );
  11934. return os;
  11935. }
  11936. XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer )
  11937. : m_writer( writer )
  11938. {}
  11939. XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept
  11940. : m_writer( other.m_writer ){
  11941. other.m_writer = nullptr;
  11942. }
  11943. XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) noexcept {
  11944. if ( m_writer ) {
  11945. m_writer->endElement();
  11946. }
  11947. m_writer = other.m_writer;
  11948. other.m_writer = nullptr;
  11949. return *this;
  11950. }
  11951. XmlWriter::ScopedElement::~ScopedElement() {
  11952. if( m_writer )
  11953. m_writer->endElement();
  11954. }
  11955. XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string const& text, bool indent ) {
  11956. m_writer->writeText( text, indent );
  11957. return *this;
  11958. }
  11959. XmlWriter::XmlWriter( std::ostream& os ) : m_os( os )
  11960. {
  11961. writeDeclaration();
  11962. }
  11963. XmlWriter::~XmlWriter() {
  11964. while( !m_tags.empty() )
  11965. endElement();
  11966. }
  11967. XmlWriter& XmlWriter::startElement( std::string const& name ) {
  11968. ensureTagClosed();
  11969. newlineIfNecessary();
  11970. m_os << m_indent << '<' << name;
  11971. m_tags.push_back( name );
  11972. m_indent += " ";
  11973. m_tagIsOpen = true;
  11974. return *this;
  11975. }
  11976. XmlWriter::ScopedElement XmlWriter::scopedElement( std::string const& name ) {
  11977. ScopedElement scoped( this );
  11978. startElement( name );
  11979. return scoped;
  11980. }
  11981. XmlWriter& XmlWriter::endElement() {
  11982. newlineIfNecessary();
  11983. m_indent = m_indent.substr( 0, m_indent.size()-2 );
  11984. if( m_tagIsOpen ) {
  11985. m_os << "/>";
  11986. m_tagIsOpen = false;
  11987. }
  11988. else {
  11989. m_os << m_indent << "</" << m_tags.back() << ">";
  11990. }
  11991. m_os << std::endl;
  11992. m_tags.pop_back();
  11993. return *this;
  11994. }
  11995. XmlWriter& XmlWriter::writeAttribute( std::string const& name, std::string const& attribute ) {
  11996. if( !name.empty() && !attribute.empty() )
  11997. m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"';
  11998. return *this;
  11999. }
  12000. XmlWriter& XmlWriter::writeAttribute( std::string const& name, bool attribute ) {
  12001. m_os << ' ' << name << "=\"" << ( attribute ? "true" : "false" ) << '"';
  12002. return *this;
  12003. }
  12004. XmlWriter& XmlWriter::writeText( std::string const& text, bool indent ) {
  12005. if( !text.empty() ){
  12006. bool tagWasOpen = m_tagIsOpen;
  12007. ensureTagClosed();
  12008. if( tagWasOpen && indent )
  12009. m_os << m_indent;
  12010. m_os << XmlEncode( text );
  12011. m_needsNewline = true;
  12012. }
  12013. return *this;
  12014. }
  12015. XmlWriter& XmlWriter::writeComment( std::string const& text ) {
  12016. ensureTagClosed();
  12017. m_os << m_indent << "<!--" << text << "-->";
  12018. m_needsNewline = true;
  12019. return *this;
  12020. }
  12021. void XmlWriter::writeStylesheetRef( std::string const& url ) {
  12022. m_os << "<?xml-stylesheet type=\"text/xsl\" href=\"" << url << "\"?>\n";
  12023. }
  12024. XmlWriter& XmlWriter::writeBlankLine() {
  12025. ensureTagClosed();
  12026. m_os << '\n';
  12027. return *this;
  12028. }
  12029. void XmlWriter::ensureTagClosed() {
  12030. if( m_tagIsOpen ) {
  12031. m_os << ">" << std::endl;
  12032. m_tagIsOpen = false;
  12033. }
  12034. }
  12035. void XmlWriter::writeDeclaration() {
  12036. m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
  12037. }
  12038. void XmlWriter::newlineIfNecessary() {
  12039. if( m_needsNewline ) {
  12040. m_os << std::endl;
  12041. m_needsNewline = false;
  12042. }
  12043. }
  12044. }
  12045. // end catch_xmlwriter.cpp
  12046. // start catch_reporter_bases.cpp
  12047. #include <cstring>
  12048. #include <cfloat>
  12049. #include <cstdio>
  12050. #include <cassert>
  12051. #include <memory>
  12052. namespace Catch {
  12053. void prepareExpandedExpression(AssertionResult& result) {
  12054. result.getExpandedExpression();
  12055. }
  12056. // Because formatting using c++ streams is stateful, drop down to C is required
  12057. // Alternatively we could use stringstream, but its performance is... not good.
  12058. std::string getFormattedDuration( double duration ) {
  12059. // Max exponent + 1 is required to represent the whole part
  12060. // + 1 for decimal point
  12061. // + 3 for the 3 decimal places
  12062. // + 1 for null terminator
  12063. const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1;
  12064. char buffer[maxDoubleSize];
  12065. // Save previous errno, to prevent sprintf from overwriting it
  12066. ErrnoGuard guard;
  12067. #ifdef _MSC_VER
  12068. sprintf_s(buffer, "%.3f", duration);
  12069. #else
  12070. std::sprintf(buffer, "%.3f", duration);
  12071. #endif
  12072. return std::string(buffer);
  12073. }
  12074. std::string serializeFilters( std::vector<std::string> const& container ) {
  12075. ReusableStringStream oss;
  12076. bool first = true;
  12077. for (auto&& filter : container)
  12078. {
  12079. if (!first)
  12080. oss << ' ';
  12081. else
  12082. first = false;
  12083. oss << filter;
  12084. }
  12085. return oss.str();
  12086. }
  12087. TestEventListenerBase::TestEventListenerBase(ReporterConfig const & _config)
  12088. :StreamingReporterBase(_config) {}
  12089. std::set<Verbosity> TestEventListenerBase::getSupportedVerbosities() {
  12090. return { Verbosity::Quiet, Verbosity::Normal, Verbosity::High };
  12091. }
  12092. void TestEventListenerBase::assertionStarting(AssertionInfo const &) {}
  12093. bool TestEventListenerBase::assertionEnded(AssertionStats const &) {
  12094. return false;
  12095. }
  12096. } // end namespace Catch
  12097. // end catch_reporter_bases.cpp
  12098. // start catch_reporter_compact.cpp
  12099. namespace {
  12100. #ifdef CATCH_PLATFORM_MAC
  12101. const char* failedString() { return "FAILED"; }
  12102. const char* passedString() { return "PASSED"; }
  12103. #else
  12104. const char* failedString() { return "failed"; }
  12105. const char* passedString() { return "passed"; }
  12106. #endif
  12107. // Colour::LightGrey
  12108. Catch::Colour::Code dimColour() { return Catch::Colour::FileName; }
  12109. std::string bothOrAll( std::size_t count ) {
  12110. return count == 1 ? std::string() :
  12111. count == 2 ? "both " : "all " ;
  12112. }
  12113. } // anon namespace
  12114. namespace Catch {
  12115. namespace {
  12116. // Colour, message variants:
  12117. // - white: No tests ran.
  12118. // - red: Failed [both/all] N test cases, failed [both/all] M assertions.
  12119. // - white: Passed [both/all] N test cases (no assertions).
  12120. // - red: Failed N tests cases, failed M assertions.
  12121. // - green: Passed [both/all] N tests cases with M assertions.
  12122. void printTotals(std::ostream& out, const Totals& totals) {
  12123. if (totals.testCases.total() == 0) {
  12124. out << "No tests ran.";
  12125. } else if (totals.testCases.failed == totals.testCases.total()) {
  12126. Colour colour(Colour::ResultError);
  12127. const std::string qualify_assertions_failed =
  12128. totals.assertions.failed == totals.assertions.total() ?
  12129. bothOrAll(totals.assertions.failed) : std::string();
  12130. out <<
  12131. "Failed " << bothOrAll(totals.testCases.failed)
  12132. << pluralise(totals.testCases.failed, "test case") << ", "
  12133. "failed " << qualify_assertions_failed <<
  12134. pluralise(totals.assertions.failed, "assertion") << '.';
  12135. } else if (totals.assertions.total() == 0) {
  12136. out <<
  12137. "Passed " << bothOrAll(totals.testCases.total())
  12138. << pluralise(totals.testCases.total(), "test case")
  12139. << " (no assertions).";
  12140. } else if (totals.assertions.failed) {
  12141. Colour colour(Colour::ResultError);
  12142. out <<
  12143. "Failed " << pluralise(totals.testCases.failed, "test case") << ", "
  12144. "failed " << pluralise(totals.assertions.failed, "assertion") << '.';
  12145. } else {
  12146. Colour colour(Colour::ResultSuccess);
  12147. out <<
  12148. "Passed " << bothOrAll(totals.testCases.passed)
  12149. << pluralise(totals.testCases.passed, "test case") <<
  12150. " with " << pluralise(totals.assertions.passed, "assertion") << '.';
  12151. }
  12152. }
  12153. // Implementation of CompactReporter formatting
  12154. class AssertionPrinter {
  12155. public:
  12156. AssertionPrinter& operator= (AssertionPrinter const&) = delete;
  12157. AssertionPrinter(AssertionPrinter const&) = delete;
  12158. AssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
  12159. : stream(_stream)
  12160. , result(_stats.assertionResult)
  12161. , messages(_stats.infoMessages)
  12162. , itMessage(_stats.infoMessages.begin())
  12163. , printInfoMessages(_printInfoMessages) {}
  12164. void print() {
  12165. printSourceInfo();
  12166. itMessage = messages.begin();
  12167. switch (result.getResultType()) {
  12168. case ResultWas::Ok:
  12169. printResultType(Colour::ResultSuccess, passedString());
  12170. printOriginalExpression();
  12171. printReconstructedExpression();
  12172. if (!result.hasExpression())
  12173. printRemainingMessages(Colour::None);
  12174. else
  12175. printRemainingMessages();
  12176. break;
  12177. case ResultWas::ExpressionFailed:
  12178. if (result.isOk())
  12179. printResultType(Colour::ResultSuccess, failedString() + std::string(" - but was ok"));
  12180. else
  12181. printResultType(Colour::Error, failedString());
  12182. printOriginalExpression();
  12183. printReconstructedExpression();
  12184. printRemainingMessages();
  12185. break;
  12186. case ResultWas::ThrewException:
  12187. printResultType(Colour::Error, failedString());
  12188. printIssue("unexpected exception with message:");
  12189. printMessage();
  12190. printExpressionWas();
  12191. printRemainingMessages();
  12192. break;
  12193. case ResultWas::FatalErrorCondition:
  12194. printResultType(Colour::Error, failedString());
  12195. printIssue("fatal error condition with message:");
  12196. printMessage();
  12197. printExpressionWas();
  12198. printRemainingMessages();
  12199. break;
  12200. case ResultWas::DidntThrowException:
  12201. printResultType(Colour::Error, failedString());
  12202. printIssue("expected exception, got none");
  12203. printExpressionWas();
  12204. printRemainingMessages();
  12205. break;
  12206. case ResultWas::Info:
  12207. printResultType(Colour::None, "info");
  12208. printMessage();
  12209. printRemainingMessages();
  12210. break;
  12211. case ResultWas::Warning:
  12212. printResultType(Colour::None, "warning");
  12213. printMessage();
  12214. printRemainingMessages();
  12215. break;
  12216. case ResultWas::ExplicitFailure:
  12217. printResultType(Colour::Error, failedString());
  12218. printIssue("explicitly");
  12219. printRemainingMessages(Colour::None);
  12220. break;
  12221. // These cases are here to prevent compiler warnings
  12222. case ResultWas::Unknown:
  12223. case ResultWas::FailureBit:
  12224. case ResultWas::Exception:
  12225. printResultType(Colour::Error, "** internal error **");
  12226. break;
  12227. }
  12228. }
  12229. private:
  12230. void printSourceInfo() const {
  12231. Colour colourGuard(Colour::FileName);
  12232. stream << result.getSourceInfo() << ':';
  12233. }
  12234. void printResultType(Colour::Code colour, std::string const& passOrFail) const {
  12235. if (!passOrFail.empty()) {
  12236. {
  12237. Colour colourGuard(colour);
  12238. stream << ' ' << passOrFail;
  12239. }
  12240. stream << ':';
  12241. }
  12242. }
  12243. void printIssue(std::string const& issue) const {
  12244. stream << ' ' << issue;
  12245. }
  12246. void printExpressionWas() {
  12247. if (result.hasExpression()) {
  12248. stream << ';';
  12249. {
  12250. Colour colour(dimColour());
  12251. stream << " expression was:";
  12252. }
  12253. printOriginalExpression();
  12254. }
  12255. }
  12256. void printOriginalExpression() const {
  12257. if (result.hasExpression()) {
  12258. stream << ' ' << result.getExpression();
  12259. }
  12260. }
  12261. void printReconstructedExpression() const {
  12262. if (result.hasExpandedExpression()) {
  12263. {
  12264. Colour colour(dimColour());
  12265. stream << " for: ";
  12266. }
  12267. stream << result.getExpandedExpression();
  12268. }
  12269. }
  12270. void printMessage() {
  12271. if (itMessage != messages.end()) {
  12272. stream << " '" << itMessage->message << '\'';
  12273. ++itMessage;
  12274. }
  12275. }
  12276. void printRemainingMessages(Colour::Code colour = dimColour()) {
  12277. if (itMessage == messages.end())
  12278. return;
  12279. // using messages.end() directly yields (or auto) compilation error:
  12280. std::vector<MessageInfo>::const_iterator itEnd = messages.end();
  12281. const std::size_t N = static_cast<std::size_t>(std::distance(itMessage, itEnd));
  12282. {
  12283. Colour colourGuard(colour);
  12284. stream << " with " << pluralise(N, "message") << ':';
  12285. }
  12286. for (; itMessage != itEnd; ) {
  12287. // If this assertion is a warning ignore any INFO messages
  12288. if (printInfoMessages || itMessage->type != ResultWas::Info) {
  12289. stream << " '" << itMessage->message << '\'';
  12290. if (++itMessage != itEnd) {
  12291. Colour colourGuard(dimColour());
  12292. stream << " and";
  12293. }
  12294. }
  12295. }
  12296. }
  12297. private:
  12298. std::ostream& stream;
  12299. AssertionResult const& result;
  12300. std::vector<MessageInfo> messages;
  12301. std::vector<MessageInfo>::const_iterator itMessage;
  12302. bool printInfoMessages;
  12303. };
  12304. } // anon namespace
  12305. std::string CompactReporter::getDescription() {
  12306. return "Reports test results on a single line, suitable for IDEs";
  12307. }
  12308. ReporterPreferences CompactReporter::getPreferences() const {
  12309. return m_reporterPrefs;
  12310. }
  12311. void CompactReporter::noMatchingTestCases( std::string const& spec ) {
  12312. stream << "No test cases matched '" << spec << '\'' << std::endl;
  12313. }
  12314. void CompactReporter::assertionStarting( AssertionInfo const& ) {}
  12315. bool CompactReporter::assertionEnded( AssertionStats const& _assertionStats ) {
  12316. AssertionResult const& result = _assertionStats.assertionResult;
  12317. bool printInfoMessages = true;
  12318. // Drop out if result was successful and we're not printing those
  12319. if( !m_config->includeSuccessfulResults() && result.isOk() ) {
  12320. if( result.getResultType() != ResultWas::Warning )
  12321. return false;
  12322. printInfoMessages = false;
  12323. }
  12324. AssertionPrinter printer( stream, _assertionStats, printInfoMessages );
  12325. printer.print();
  12326. stream << std::endl;
  12327. return true;
  12328. }
  12329. void CompactReporter::sectionEnded(SectionStats const& _sectionStats) {
  12330. if (m_config->showDurations() == ShowDurations::Always) {
  12331. stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  12332. }
  12333. }
  12334. void CompactReporter::testRunEnded( TestRunStats const& _testRunStats ) {
  12335. printTotals( stream, _testRunStats.totals );
  12336. stream << '\n' << std::endl;
  12337. StreamingReporterBase::testRunEnded( _testRunStats );
  12338. }
  12339. CompactReporter::~CompactReporter() {}
  12340. CATCH_REGISTER_REPORTER( "compact", CompactReporter )
  12341. } // end namespace Catch
  12342. // end catch_reporter_compact.cpp
  12343. // start catch_reporter_console.cpp
  12344. #include <cfloat>
  12345. #include <cstdio>
  12346. #if defined(_MSC_VER)
  12347. #pragma warning(push)
  12348. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  12349. // Note that 4062 (not all labels are handled and default is missing) is enabled
  12350. #endif
  12351. #if defined(__clang__)
  12352. # pragma clang diagnostic push
  12353. // For simplicity, benchmarking-only helpers are always enabled
  12354. # pragma clang diagnostic ignored "-Wunused-function"
  12355. #endif
  12356. namespace Catch {
  12357. namespace {
  12358. // Formatter impl for ConsoleReporter
  12359. class ConsoleAssertionPrinter {
  12360. public:
  12361. ConsoleAssertionPrinter& operator= (ConsoleAssertionPrinter const&) = delete;
  12362. ConsoleAssertionPrinter(ConsoleAssertionPrinter const&) = delete;
  12363. ConsoleAssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
  12364. : stream(_stream),
  12365. stats(_stats),
  12366. result(_stats.assertionResult),
  12367. colour(Colour::None),
  12368. message(result.getMessage()),
  12369. messages(_stats.infoMessages),
  12370. printInfoMessages(_printInfoMessages) {
  12371. switch (result.getResultType()) {
  12372. case ResultWas::Ok:
  12373. colour = Colour::Success;
  12374. passOrFail = "PASSED";
  12375. //if( result.hasMessage() )
  12376. if (_stats.infoMessages.size() == 1)
  12377. messageLabel = "with message";
  12378. if (_stats.infoMessages.size() > 1)
  12379. messageLabel = "with messages";
  12380. break;
  12381. case ResultWas::ExpressionFailed:
  12382. if (result.isOk()) {
  12383. colour = Colour::Success;
  12384. passOrFail = "FAILED - but was ok";
  12385. } else {
  12386. colour = Colour::Error;
  12387. passOrFail = "FAILED";
  12388. }
  12389. if (_stats.infoMessages.size() == 1)
  12390. messageLabel = "with message";
  12391. if (_stats.infoMessages.size() > 1)
  12392. messageLabel = "with messages";
  12393. break;
  12394. case ResultWas::ThrewException:
  12395. colour = Colour::Error;
  12396. passOrFail = "FAILED";
  12397. messageLabel = "due to unexpected exception with ";
  12398. if (_stats.infoMessages.size() == 1)
  12399. messageLabel += "message";
  12400. if (_stats.infoMessages.size() > 1)
  12401. messageLabel += "messages";
  12402. break;
  12403. case ResultWas::FatalErrorCondition:
  12404. colour = Colour::Error;
  12405. passOrFail = "FAILED";
  12406. messageLabel = "due to a fatal error condition";
  12407. break;
  12408. case ResultWas::DidntThrowException:
  12409. colour = Colour::Error;
  12410. passOrFail = "FAILED";
  12411. messageLabel = "because no exception was thrown where one was expected";
  12412. break;
  12413. case ResultWas::Info:
  12414. messageLabel = "info";
  12415. break;
  12416. case ResultWas::Warning:
  12417. messageLabel = "warning";
  12418. break;
  12419. case ResultWas::ExplicitFailure:
  12420. passOrFail = "FAILED";
  12421. colour = Colour::Error;
  12422. if (_stats.infoMessages.size() == 1)
  12423. messageLabel = "explicitly with message";
  12424. if (_stats.infoMessages.size() > 1)
  12425. messageLabel = "explicitly with messages";
  12426. break;
  12427. // These cases are here to prevent compiler warnings
  12428. case ResultWas::Unknown:
  12429. case ResultWas::FailureBit:
  12430. case ResultWas::Exception:
  12431. passOrFail = "** internal error **";
  12432. colour = Colour::Error;
  12433. break;
  12434. }
  12435. }
  12436. void print() const {
  12437. printSourceInfo();
  12438. if (stats.totals.assertions.total() > 0) {
  12439. printResultType();
  12440. printOriginalExpression();
  12441. printReconstructedExpression();
  12442. } else {
  12443. stream << '\n';
  12444. }
  12445. printMessage();
  12446. }
  12447. private:
  12448. void printResultType() const {
  12449. if (!passOrFail.empty()) {
  12450. Colour colourGuard(colour);
  12451. stream << passOrFail << ":\n";
  12452. }
  12453. }
  12454. void printOriginalExpression() const {
  12455. if (result.hasExpression()) {
  12456. Colour colourGuard(Colour::OriginalExpression);
  12457. stream << " ";
  12458. stream << result.getExpressionInMacro();
  12459. stream << '\n';
  12460. }
  12461. }
  12462. void printReconstructedExpression() const {
  12463. if (result.hasExpandedExpression()) {
  12464. stream << "with expansion:\n";
  12465. Colour colourGuard(Colour::ReconstructedExpression);
  12466. stream << Column(result.getExpandedExpression()).indent(2) << '\n';
  12467. }
  12468. }
  12469. void printMessage() const {
  12470. if (!messageLabel.empty())
  12471. stream << messageLabel << ':' << '\n';
  12472. for (auto const& msg : messages) {
  12473. // If this assertion is a warning ignore any INFO messages
  12474. if (printInfoMessages || msg.type != ResultWas::Info)
  12475. stream << Column(msg.message).indent(2) << '\n';
  12476. }
  12477. }
  12478. void printSourceInfo() const {
  12479. Colour colourGuard(Colour::FileName);
  12480. stream << result.getSourceInfo() << ": ";
  12481. }
  12482. std::ostream& stream;
  12483. AssertionStats const& stats;
  12484. AssertionResult const& result;
  12485. Colour::Code colour;
  12486. std::string passOrFail;
  12487. std::string messageLabel;
  12488. std::string message;
  12489. std::vector<MessageInfo> messages;
  12490. bool printInfoMessages;
  12491. };
  12492. std::size_t makeRatio(std::size_t number, std::size_t total) {
  12493. std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0;
  12494. return (ratio == 0 && number > 0) ? 1 : ratio;
  12495. }
  12496. std::size_t& findMax(std::size_t& i, std::size_t& j, std::size_t& k) {
  12497. if (i > j && i > k)
  12498. return i;
  12499. else if (j > k)
  12500. return j;
  12501. else
  12502. return k;
  12503. }
  12504. struct ColumnInfo {
  12505. enum Justification { Left, Right };
  12506. std::string name;
  12507. int width;
  12508. Justification justification;
  12509. };
  12510. struct ColumnBreak {};
  12511. struct RowBreak {};
  12512. class Duration {
  12513. enum class Unit {
  12514. Auto,
  12515. Nanoseconds,
  12516. Microseconds,
  12517. Milliseconds,
  12518. Seconds,
  12519. Minutes
  12520. };
  12521. static const uint64_t s_nanosecondsInAMicrosecond = 1000;
  12522. static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond;
  12523. static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond;
  12524. static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond;
  12525. uint64_t m_inNanoseconds;
  12526. Unit m_units;
  12527. public:
  12528. explicit Duration(double inNanoseconds, Unit units = Unit::Auto)
  12529. : Duration(static_cast<uint64_t>(inNanoseconds), units) {
  12530. }
  12531. explicit Duration(uint64_t inNanoseconds, Unit units = Unit::Auto)
  12532. : m_inNanoseconds(inNanoseconds),
  12533. m_units(units) {
  12534. if (m_units == Unit::Auto) {
  12535. if (m_inNanoseconds < s_nanosecondsInAMicrosecond)
  12536. m_units = Unit::Nanoseconds;
  12537. else if (m_inNanoseconds < s_nanosecondsInAMillisecond)
  12538. m_units = Unit::Microseconds;
  12539. else if (m_inNanoseconds < s_nanosecondsInASecond)
  12540. m_units = Unit::Milliseconds;
  12541. else if (m_inNanoseconds < s_nanosecondsInAMinute)
  12542. m_units = Unit::Seconds;
  12543. else
  12544. m_units = Unit::Minutes;
  12545. }
  12546. }
  12547. auto value() const -> double {
  12548. switch (m_units) {
  12549. case Unit::Microseconds:
  12550. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMicrosecond);
  12551. case Unit::Milliseconds:
  12552. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMillisecond);
  12553. case Unit::Seconds:
  12554. return m_inNanoseconds / static_cast<double>(s_nanosecondsInASecond);
  12555. case Unit::Minutes:
  12556. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMinute);
  12557. default:
  12558. return static_cast<double>(m_inNanoseconds);
  12559. }
  12560. }
  12561. auto unitsAsString() const -> std::string {
  12562. switch (m_units) {
  12563. case Unit::Nanoseconds:
  12564. return "ns";
  12565. case Unit::Microseconds:
  12566. return "us";
  12567. case Unit::Milliseconds:
  12568. return "ms";
  12569. case Unit::Seconds:
  12570. return "s";
  12571. case Unit::Minutes:
  12572. return "m";
  12573. default:
  12574. return "** internal error **";
  12575. }
  12576. }
  12577. friend auto operator << (std::ostream& os, Duration const& duration) -> std::ostream& {
  12578. return os << duration.value() << " " << duration.unitsAsString();
  12579. }
  12580. };
  12581. } // end anon namespace
  12582. class TablePrinter {
  12583. std::ostream& m_os;
  12584. std::vector<ColumnInfo> m_columnInfos;
  12585. std::ostringstream m_oss;
  12586. int m_currentColumn = -1;
  12587. bool m_isOpen = false;
  12588. public:
  12589. TablePrinter( std::ostream& os, std::vector<ColumnInfo> columnInfos )
  12590. : m_os( os ),
  12591. m_columnInfos( std::move( columnInfos ) ) {}
  12592. auto columnInfos() const -> std::vector<ColumnInfo> const& {
  12593. return m_columnInfos;
  12594. }
  12595. void open() {
  12596. if (!m_isOpen) {
  12597. m_isOpen = true;
  12598. *this << RowBreak();
  12599. Columns headerCols;
  12600. Spacer spacer(2);
  12601. for (auto const& info : m_columnInfos) {
  12602. headerCols += Column(info.name).width(static_cast<std::size_t>(info.width - 2));
  12603. headerCols += spacer;
  12604. }
  12605. m_os << headerCols << "\n";
  12606. m_os << Catch::getLineOfChars<'-'>() << "\n";
  12607. }
  12608. }
  12609. void close() {
  12610. if (m_isOpen) {
  12611. *this << RowBreak();
  12612. m_os << std::endl;
  12613. m_isOpen = false;
  12614. }
  12615. }
  12616. template<typename T>
  12617. friend TablePrinter& operator << (TablePrinter& tp, T const& value) {
  12618. tp.m_oss << value;
  12619. return tp;
  12620. }
  12621. friend TablePrinter& operator << (TablePrinter& tp, ColumnBreak) {
  12622. auto colStr = tp.m_oss.str();
  12623. // This takes account of utf8 encodings
  12624. auto strSize = Catch::StringRef(colStr).numberOfCharacters();
  12625. tp.m_oss.str("");
  12626. tp.open();
  12627. if (tp.m_currentColumn == static_cast<int>(tp.m_columnInfos.size() - 1)) {
  12628. tp.m_currentColumn = -1;
  12629. tp.m_os << "\n";
  12630. }
  12631. tp.m_currentColumn++;
  12632. auto colInfo = tp.m_columnInfos[tp.m_currentColumn];
  12633. auto padding = (strSize + 2 < static_cast<std::size_t>(colInfo.width))
  12634. ? std::string(colInfo.width - (strSize + 2), ' ')
  12635. : std::string();
  12636. if (colInfo.justification == ColumnInfo::Left)
  12637. tp.m_os << colStr << padding << " ";
  12638. else
  12639. tp.m_os << padding << colStr << " ";
  12640. return tp;
  12641. }
  12642. friend TablePrinter& operator << (TablePrinter& tp, RowBreak) {
  12643. if (tp.m_currentColumn > 0) {
  12644. tp.m_os << "\n";
  12645. tp.m_currentColumn = -1;
  12646. }
  12647. return tp;
  12648. }
  12649. };
  12650. ConsoleReporter::ConsoleReporter(ReporterConfig const& config)
  12651. : StreamingReporterBase(config),
  12652. m_tablePrinter(new TablePrinter(config.stream(),
  12653. {
  12654. { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 32, ColumnInfo::Left },
  12655. { "samples mean std dev", 14, ColumnInfo::Right },
  12656. { "iterations low mean low std dev", 14, ColumnInfo::Right },
  12657. { "estimated high mean high std dev", 14, ColumnInfo::Right }
  12658. })) {}
  12659. ConsoleReporter::~ConsoleReporter() = default;
  12660. std::string ConsoleReporter::getDescription() {
  12661. return "Reports test results as plain lines of text";
  12662. }
  12663. void ConsoleReporter::noMatchingTestCases(std::string const& spec) {
  12664. stream << "No test cases matched '" << spec << '\'' << std::endl;
  12665. }
  12666. void ConsoleReporter::assertionStarting(AssertionInfo const&) {}
  12667. bool ConsoleReporter::assertionEnded(AssertionStats const& _assertionStats) {
  12668. AssertionResult const& result = _assertionStats.assertionResult;
  12669. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  12670. // Drop out if result was successful but we're not printing them.
  12671. if (!includeResults && result.getResultType() != ResultWas::Warning)
  12672. return false;
  12673. lazyPrint();
  12674. ConsoleAssertionPrinter printer(stream, _assertionStats, includeResults);
  12675. printer.print();
  12676. stream << std::endl;
  12677. return true;
  12678. }
  12679. void ConsoleReporter::sectionStarting(SectionInfo const& _sectionInfo) {
  12680. m_tablePrinter->close();
  12681. m_headerPrinted = false;
  12682. StreamingReporterBase::sectionStarting(_sectionInfo);
  12683. }
  12684. void ConsoleReporter::sectionEnded(SectionStats const& _sectionStats) {
  12685. m_tablePrinter->close();
  12686. if (_sectionStats.missingAssertions) {
  12687. lazyPrint();
  12688. Colour colour(Colour::ResultError);
  12689. if (m_sectionStack.size() > 1)
  12690. stream << "\nNo assertions in section";
  12691. else
  12692. stream << "\nNo assertions in test case";
  12693. stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl;
  12694. }
  12695. if (m_config->showDurations() == ShowDurations::Always) {
  12696. stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  12697. }
  12698. if (m_headerPrinted) {
  12699. m_headerPrinted = false;
  12700. }
  12701. StreamingReporterBase::sectionEnded(_sectionStats);
  12702. }
  12703. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  12704. void ConsoleReporter::benchmarkPreparing(std::string const& name) {
  12705. lazyPrintWithoutClosingBenchmarkTable();
  12706. auto nameCol = Column(name).width(static_cast<std::size_t>(m_tablePrinter->columnInfos()[0].width - 2));
  12707. bool firstLine = true;
  12708. for (auto line : nameCol) {
  12709. if (!firstLine)
  12710. (*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak();
  12711. else
  12712. firstLine = false;
  12713. (*m_tablePrinter) << line << ColumnBreak();
  12714. }
  12715. }
  12716. void ConsoleReporter::benchmarkStarting(BenchmarkInfo const& info) {
  12717. (*m_tablePrinter) << info.samples << ColumnBreak()
  12718. << info.iterations << ColumnBreak()
  12719. << Duration(info.estimatedDuration) << ColumnBreak();
  12720. }
  12721. void ConsoleReporter::benchmarkEnded(BenchmarkStats<> const& stats) {
  12722. (*m_tablePrinter) << ColumnBreak()
  12723. << Duration(stats.mean.point.count()) << ColumnBreak()
  12724. << Duration(stats.mean.lower_bound.count()) << ColumnBreak()
  12725. << Duration(stats.mean.upper_bound.count()) << ColumnBreak() << ColumnBreak()
  12726. << Duration(stats.standardDeviation.point.count()) << ColumnBreak()
  12727. << Duration(stats.standardDeviation.lower_bound.count()) << ColumnBreak()
  12728. << Duration(stats.standardDeviation.upper_bound.count()) << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak();
  12729. }
  12730. void ConsoleReporter::benchmarkFailed(std::string const& error) {
  12731. Colour colour(Colour::Red);
  12732. (*m_tablePrinter)
  12733. << "Benchmark failed (" << error << ")"
  12734. << ColumnBreak() << RowBreak();
  12735. }
  12736. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  12737. void ConsoleReporter::testCaseEnded(TestCaseStats const& _testCaseStats) {
  12738. m_tablePrinter->close();
  12739. StreamingReporterBase::testCaseEnded(_testCaseStats);
  12740. m_headerPrinted = false;
  12741. }
  12742. void ConsoleReporter::testGroupEnded(TestGroupStats const& _testGroupStats) {
  12743. if (currentGroupInfo.used) {
  12744. printSummaryDivider();
  12745. stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n";
  12746. printTotals(_testGroupStats.totals);
  12747. stream << '\n' << std::endl;
  12748. }
  12749. StreamingReporterBase::testGroupEnded(_testGroupStats);
  12750. }
  12751. void ConsoleReporter::testRunEnded(TestRunStats const& _testRunStats) {
  12752. printTotalsDivider(_testRunStats.totals);
  12753. printTotals(_testRunStats.totals);
  12754. stream << std::endl;
  12755. StreamingReporterBase::testRunEnded(_testRunStats);
  12756. }
  12757. void ConsoleReporter::testRunStarting(TestRunInfo const& _testInfo) {
  12758. StreamingReporterBase::testRunStarting(_testInfo);
  12759. printTestFilters();
  12760. }
  12761. void ConsoleReporter::lazyPrint() {
  12762. m_tablePrinter->close();
  12763. lazyPrintWithoutClosingBenchmarkTable();
  12764. }
  12765. void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() {
  12766. if (!currentTestRunInfo.used)
  12767. lazyPrintRunInfo();
  12768. if (!currentGroupInfo.used)
  12769. lazyPrintGroupInfo();
  12770. if (!m_headerPrinted) {
  12771. printTestCaseAndSectionHeader();
  12772. m_headerPrinted = true;
  12773. }
  12774. }
  12775. void ConsoleReporter::lazyPrintRunInfo() {
  12776. stream << '\n' << getLineOfChars<'~'>() << '\n';
  12777. Colour colour(Colour::SecondaryText);
  12778. stream << currentTestRunInfo->name
  12779. << " is a Catch v" << libraryVersion() << " host application.\n"
  12780. << "Run with -? for options\n\n";
  12781. if (m_config->rngSeed() != 0)
  12782. stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n";
  12783. currentTestRunInfo.used = true;
  12784. }
  12785. void ConsoleReporter::lazyPrintGroupInfo() {
  12786. if (!currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1) {
  12787. printClosedHeader("Group: " + currentGroupInfo->name);
  12788. currentGroupInfo.used = true;
  12789. }
  12790. }
  12791. void ConsoleReporter::printTestCaseAndSectionHeader() {
  12792. assert(!m_sectionStack.empty());
  12793. printOpenHeader(currentTestCaseInfo->name);
  12794. if (m_sectionStack.size() > 1) {
  12795. Colour colourGuard(Colour::Headers);
  12796. auto
  12797. it = m_sectionStack.begin() + 1, // Skip first section (test case)
  12798. itEnd = m_sectionStack.end();
  12799. for (; it != itEnd; ++it)
  12800. printHeaderString(it->name, 2);
  12801. }
  12802. SourceLineInfo lineInfo = m_sectionStack.back().lineInfo;
  12803. if (!lineInfo.empty()) {
  12804. stream << getLineOfChars<'-'>() << '\n';
  12805. Colour colourGuard(Colour::FileName);
  12806. stream << lineInfo << '\n';
  12807. }
  12808. stream << getLineOfChars<'.'>() << '\n' << std::endl;
  12809. }
  12810. void ConsoleReporter::printClosedHeader(std::string const& _name) {
  12811. printOpenHeader(_name);
  12812. stream << getLineOfChars<'.'>() << '\n';
  12813. }
  12814. void ConsoleReporter::printOpenHeader(std::string const& _name) {
  12815. stream << getLineOfChars<'-'>() << '\n';
  12816. {
  12817. Colour colourGuard(Colour::Headers);
  12818. printHeaderString(_name);
  12819. }
  12820. }
  12821. // if string has a : in first line will set indent to follow it on
  12822. // subsequent lines
  12823. void ConsoleReporter::printHeaderString(std::string const& _string, std::size_t indent) {
  12824. std::size_t i = _string.find(": ");
  12825. if (i != std::string::npos)
  12826. i += 2;
  12827. else
  12828. i = 0;
  12829. stream << Column(_string).indent(indent + i).initialIndent(indent) << '\n';
  12830. }
  12831. struct SummaryColumn {
  12832. SummaryColumn( std::string _label, Colour::Code _colour )
  12833. : label( std::move( _label ) ),
  12834. colour( _colour ) {}
  12835. SummaryColumn addRow( std::size_t count ) {
  12836. ReusableStringStream rss;
  12837. rss << count;
  12838. std::string row = rss.str();
  12839. for (auto& oldRow : rows) {
  12840. while (oldRow.size() < row.size())
  12841. oldRow = ' ' + oldRow;
  12842. while (oldRow.size() > row.size())
  12843. row = ' ' + row;
  12844. }
  12845. rows.push_back(row);
  12846. return *this;
  12847. }
  12848. std::string label;
  12849. Colour::Code colour;
  12850. std::vector<std::string> rows;
  12851. };
  12852. void ConsoleReporter::printTotals( Totals const& totals ) {
  12853. if (totals.testCases.total() == 0) {
  12854. stream << Colour(Colour::Warning) << "No tests ran\n";
  12855. } else if (totals.assertions.total() > 0 && totals.testCases.allPassed()) {
  12856. stream << Colour(Colour::ResultSuccess) << "All tests passed";
  12857. stream << " ("
  12858. << pluralise(totals.assertions.passed, "assertion") << " in "
  12859. << pluralise(totals.testCases.passed, "test case") << ')'
  12860. << '\n';
  12861. } else {
  12862. std::vector<SummaryColumn> columns;
  12863. columns.push_back(SummaryColumn("", Colour::None)
  12864. .addRow(totals.testCases.total())
  12865. .addRow(totals.assertions.total()));
  12866. columns.push_back(SummaryColumn("passed", Colour::Success)
  12867. .addRow(totals.testCases.passed)
  12868. .addRow(totals.assertions.passed));
  12869. columns.push_back(SummaryColumn("failed", Colour::ResultError)
  12870. .addRow(totals.testCases.failed)
  12871. .addRow(totals.assertions.failed));
  12872. columns.push_back(SummaryColumn("failed as expected", Colour::ResultExpectedFailure)
  12873. .addRow(totals.testCases.failedButOk)
  12874. .addRow(totals.assertions.failedButOk));
  12875. printSummaryRow("test cases", columns, 0);
  12876. printSummaryRow("assertions", columns, 1);
  12877. }
  12878. }
  12879. void ConsoleReporter::printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row) {
  12880. for (auto col : cols) {
  12881. std::string value = col.rows[row];
  12882. if (col.label.empty()) {
  12883. stream << label << ": ";
  12884. if (value != "0")
  12885. stream << value;
  12886. else
  12887. stream << Colour(Colour::Warning) << "- none -";
  12888. } else if (value != "0") {
  12889. stream << Colour(Colour::LightGrey) << " | ";
  12890. stream << Colour(col.colour)
  12891. << value << ' ' << col.label;
  12892. }
  12893. }
  12894. stream << '\n';
  12895. }
  12896. void ConsoleReporter::printTotalsDivider(Totals const& totals) {
  12897. if (totals.testCases.total() > 0) {
  12898. std::size_t failedRatio = makeRatio(totals.testCases.failed, totals.testCases.total());
  12899. std::size_t failedButOkRatio = makeRatio(totals.testCases.failedButOk, totals.testCases.total());
  12900. std::size_t passedRatio = makeRatio(totals.testCases.passed, totals.testCases.total());
  12901. while (failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1)
  12902. findMax(failedRatio, failedButOkRatio, passedRatio)++;
  12903. while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1)
  12904. findMax(failedRatio, failedButOkRatio, passedRatio)--;
  12905. stream << Colour(Colour::Error) << std::string(failedRatio, '=');
  12906. stream << Colour(Colour::ResultExpectedFailure) << std::string(failedButOkRatio, '=');
  12907. if (totals.testCases.allPassed())
  12908. stream << Colour(Colour::ResultSuccess) << std::string(passedRatio, '=');
  12909. else
  12910. stream << Colour(Colour::Success) << std::string(passedRatio, '=');
  12911. } else {
  12912. stream << Colour(Colour::Warning) << std::string(CATCH_CONFIG_CONSOLE_WIDTH - 1, '=');
  12913. }
  12914. stream << '\n';
  12915. }
  12916. void ConsoleReporter::printSummaryDivider() {
  12917. stream << getLineOfChars<'-'>() << '\n';
  12918. }
  12919. void ConsoleReporter::printTestFilters() {
  12920. if (m_config->testSpec().hasFilters())
  12921. stream << Colour(Colour::BrightYellow) << "Filters: " << serializeFilters( m_config->getTestsOrTags() ) << '\n';
  12922. }
  12923. CATCH_REGISTER_REPORTER("console", ConsoleReporter)
  12924. } // end namespace Catch
  12925. #if defined(_MSC_VER)
  12926. #pragma warning(pop)
  12927. #endif
  12928. #if defined(__clang__)
  12929. # pragma clang diagnostic pop
  12930. #endif
  12931. // end catch_reporter_console.cpp
  12932. // start catch_reporter_junit.cpp
  12933. #include <cassert>
  12934. #include <sstream>
  12935. #include <ctime>
  12936. #include <algorithm>
  12937. namespace Catch {
  12938. namespace {
  12939. std::string getCurrentTimestamp() {
  12940. // Beware, this is not reentrant because of backward compatibility issues
  12941. // Also, UTC only, again because of backward compatibility (%z is C++11)
  12942. time_t rawtime;
  12943. std::time(&rawtime);
  12944. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  12945. #ifdef _MSC_VER
  12946. std::tm timeInfo = {};
  12947. gmtime_s(&timeInfo, &rawtime);
  12948. #else
  12949. std::tm* timeInfo;
  12950. timeInfo = std::gmtime(&rawtime);
  12951. #endif
  12952. char timeStamp[timeStampSize];
  12953. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  12954. #ifdef _MSC_VER
  12955. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  12956. #else
  12957. std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
  12958. #endif
  12959. return std::string(timeStamp);
  12960. }
  12961. std::string fileNameTag(const std::vector<std::string> &tags) {
  12962. auto it = std::find_if(begin(tags),
  12963. end(tags),
  12964. [] (std::string const& tag) {return tag.front() == '#'; });
  12965. if (it != tags.end())
  12966. return it->substr(1);
  12967. return std::string();
  12968. }
  12969. } // anonymous namespace
  12970. JunitReporter::JunitReporter( ReporterConfig const& _config )
  12971. : CumulativeReporterBase( _config ),
  12972. xml( _config.stream() )
  12973. {
  12974. m_reporterPrefs.shouldRedirectStdOut = true;
  12975. m_reporterPrefs.shouldReportAllAssertions = true;
  12976. }
  12977. JunitReporter::~JunitReporter() {}
  12978. std::string JunitReporter::getDescription() {
  12979. return "Reports test results in an XML format that looks like Ant's junitreport target";
  12980. }
  12981. void JunitReporter::noMatchingTestCases( std::string const& /*spec*/ ) {}
  12982. void JunitReporter::testRunStarting( TestRunInfo const& runInfo ) {
  12983. CumulativeReporterBase::testRunStarting( runInfo );
  12984. xml.startElement( "testsuites" );
  12985. }
  12986. void JunitReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  12987. suiteTimer.start();
  12988. stdOutForSuite.clear();
  12989. stdErrForSuite.clear();
  12990. unexpectedExceptions = 0;
  12991. CumulativeReporterBase::testGroupStarting( groupInfo );
  12992. }
  12993. void JunitReporter::testCaseStarting( TestCaseInfo const& testCaseInfo ) {
  12994. m_okToFail = testCaseInfo.okToFail();
  12995. }
  12996. bool JunitReporter::assertionEnded( AssertionStats const& assertionStats ) {
  12997. if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail )
  12998. unexpectedExceptions++;
  12999. return CumulativeReporterBase::assertionEnded( assertionStats );
  13000. }
  13001. void JunitReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  13002. stdOutForSuite += testCaseStats.stdOut;
  13003. stdErrForSuite += testCaseStats.stdErr;
  13004. CumulativeReporterBase::testCaseEnded( testCaseStats );
  13005. }
  13006. void JunitReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  13007. double suiteTime = suiteTimer.getElapsedSeconds();
  13008. CumulativeReporterBase::testGroupEnded( testGroupStats );
  13009. writeGroup( *m_testGroups.back(), suiteTime );
  13010. }
  13011. void JunitReporter::testRunEndedCumulative() {
  13012. xml.endElement();
  13013. }
  13014. void JunitReporter::writeGroup( TestGroupNode const& groupNode, double suiteTime ) {
  13015. XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" );
  13016. TestGroupStats const& stats = groupNode.value;
  13017. xml.writeAttribute( "name", stats.groupInfo.name );
  13018. xml.writeAttribute( "errors", unexpectedExceptions );
  13019. xml.writeAttribute( "failures", stats.totals.assertions.failed-unexpectedExceptions );
  13020. xml.writeAttribute( "tests", stats.totals.assertions.total() );
  13021. xml.writeAttribute( "hostname", "tbd" ); // !TBD
  13022. if( m_config->showDurations() == ShowDurations::Never )
  13023. xml.writeAttribute( "time", "" );
  13024. else
  13025. xml.writeAttribute( "time", suiteTime );
  13026. xml.writeAttribute( "timestamp", getCurrentTimestamp() );
  13027. // Write properties if there are any
  13028. if (m_config->hasTestFilters() || m_config->rngSeed() != 0) {
  13029. auto properties = xml.scopedElement("properties");
  13030. if (m_config->hasTestFilters()) {
  13031. xml.scopedElement("property")
  13032. .writeAttribute("name", "filters")
  13033. .writeAttribute("value", serializeFilters(m_config->getTestsOrTags()));
  13034. }
  13035. if (m_config->rngSeed() != 0) {
  13036. xml.scopedElement("property")
  13037. .writeAttribute("name", "random-seed")
  13038. .writeAttribute("value", m_config->rngSeed());
  13039. }
  13040. }
  13041. // Write test cases
  13042. for( auto const& child : groupNode.children )
  13043. writeTestCase( *child );
  13044. xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite ), false );
  13045. xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite ), false );
  13046. }
  13047. void JunitReporter::writeTestCase( TestCaseNode const& testCaseNode ) {
  13048. TestCaseStats const& stats = testCaseNode.value;
  13049. // All test cases have exactly one section - which represents the
  13050. // test case itself. That section may have 0-n nested sections
  13051. assert( testCaseNode.children.size() == 1 );
  13052. SectionNode const& rootSection = *testCaseNode.children.front();
  13053. std::string className = stats.testInfo.className;
  13054. if( className.empty() ) {
  13055. className = fileNameTag(stats.testInfo.tags);
  13056. if ( className.empty() )
  13057. className = "global";
  13058. }
  13059. if ( !m_config->name().empty() )
  13060. className = m_config->name() + "." + className;
  13061. writeSection( className, "", rootSection );
  13062. }
  13063. void JunitReporter::writeSection( std::string const& className,
  13064. std::string const& rootName,
  13065. SectionNode const& sectionNode ) {
  13066. std::string name = trim( sectionNode.stats.sectionInfo.name );
  13067. if( !rootName.empty() )
  13068. name = rootName + '/' + name;
  13069. if( !sectionNode.assertions.empty() ||
  13070. !sectionNode.stdOut.empty() ||
  13071. !sectionNode.stdErr.empty() ) {
  13072. XmlWriter::ScopedElement e = xml.scopedElement( "testcase" );
  13073. if( className.empty() ) {
  13074. xml.writeAttribute( "classname", name );
  13075. xml.writeAttribute( "name", "root" );
  13076. }
  13077. else {
  13078. xml.writeAttribute( "classname", className );
  13079. xml.writeAttribute( "name", name );
  13080. }
  13081. xml.writeAttribute( "time", ::Catch::Detail::stringify( sectionNode.stats.durationInSeconds ) );
  13082. writeAssertions( sectionNode );
  13083. if( !sectionNode.stdOut.empty() )
  13084. xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), false );
  13085. if( !sectionNode.stdErr.empty() )
  13086. xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), false );
  13087. }
  13088. for( auto const& childNode : sectionNode.childSections )
  13089. if( className.empty() )
  13090. writeSection( name, "", *childNode );
  13091. else
  13092. writeSection( className, name, *childNode );
  13093. }
  13094. void JunitReporter::writeAssertions( SectionNode const& sectionNode ) {
  13095. for( auto const& assertion : sectionNode.assertions )
  13096. writeAssertion( assertion );
  13097. }
  13098. void JunitReporter::writeAssertion( AssertionStats const& stats ) {
  13099. AssertionResult const& result = stats.assertionResult;
  13100. if( !result.isOk() ) {
  13101. std::string elementName;
  13102. switch( result.getResultType() ) {
  13103. case ResultWas::ThrewException:
  13104. case ResultWas::FatalErrorCondition:
  13105. elementName = "error";
  13106. break;
  13107. case ResultWas::ExplicitFailure:
  13108. elementName = "failure";
  13109. break;
  13110. case ResultWas::ExpressionFailed:
  13111. elementName = "failure";
  13112. break;
  13113. case ResultWas::DidntThrowException:
  13114. elementName = "failure";
  13115. break;
  13116. // We should never see these here:
  13117. case ResultWas::Info:
  13118. case ResultWas::Warning:
  13119. case ResultWas::Ok:
  13120. case ResultWas::Unknown:
  13121. case ResultWas::FailureBit:
  13122. case ResultWas::Exception:
  13123. elementName = "internalError";
  13124. break;
  13125. }
  13126. XmlWriter::ScopedElement e = xml.scopedElement( elementName );
  13127. xml.writeAttribute( "message", result.getExpandedExpression() );
  13128. xml.writeAttribute( "type", result.getTestMacroName() );
  13129. ReusableStringStream rss;
  13130. if( !result.getMessage().empty() )
  13131. rss << result.getMessage() << '\n';
  13132. for( auto const& msg : stats.infoMessages )
  13133. if( msg.type == ResultWas::Info )
  13134. rss << msg.message << '\n';
  13135. rss << "at " << result.getSourceInfo();
  13136. xml.writeText( rss.str(), false );
  13137. }
  13138. }
  13139. CATCH_REGISTER_REPORTER( "junit", JunitReporter )
  13140. } // end namespace Catch
  13141. // end catch_reporter_junit.cpp
  13142. // start catch_reporter_listening.cpp
  13143. #include <cassert>
  13144. namespace Catch {
  13145. ListeningReporter::ListeningReporter() {
  13146. // We will assume that listeners will always want all assertions
  13147. m_preferences.shouldReportAllAssertions = true;
  13148. }
  13149. void ListeningReporter::addListener( IStreamingReporterPtr&& listener ) {
  13150. m_listeners.push_back( std::move( listener ) );
  13151. }
  13152. void ListeningReporter::addReporter(IStreamingReporterPtr&& reporter) {
  13153. assert(!m_reporter && "Listening reporter can wrap only 1 real reporter");
  13154. m_reporter = std::move( reporter );
  13155. m_preferences.shouldRedirectStdOut = m_reporter->getPreferences().shouldRedirectStdOut;
  13156. }
  13157. ReporterPreferences ListeningReporter::getPreferences() const {
  13158. return m_preferences;
  13159. }
  13160. std::set<Verbosity> ListeningReporter::getSupportedVerbosities() {
  13161. return std::set<Verbosity>{ };
  13162. }
  13163. void ListeningReporter::noMatchingTestCases( std::string const& spec ) {
  13164. for ( auto const& listener : m_listeners ) {
  13165. listener->noMatchingTestCases( spec );
  13166. }
  13167. m_reporter->noMatchingTestCases( spec );
  13168. }
  13169. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  13170. void ListeningReporter::benchmarkPreparing( std::string const& name ) {
  13171. for (auto const& listener : m_listeners) {
  13172. listener->benchmarkPreparing(name);
  13173. }
  13174. m_reporter->benchmarkPreparing(name);
  13175. }
  13176. void ListeningReporter::benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) {
  13177. for ( auto const& listener : m_listeners ) {
  13178. listener->benchmarkStarting( benchmarkInfo );
  13179. }
  13180. m_reporter->benchmarkStarting( benchmarkInfo );
  13181. }
  13182. void ListeningReporter::benchmarkEnded( BenchmarkStats<> const& benchmarkStats ) {
  13183. for ( auto const& listener : m_listeners ) {
  13184. listener->benchmarkEnded( benchmarkStats );
  13185. }
  13186. m_reporter->benchmarkEnded( benchmarkStats );
  13187. }
  13188. void ListeningReporter::benchmarkFailed( std::string const& error ) {
  13189. for (auto const& listener : m_listeners) {
  13190. listener->benchmarkFailed(error);
  13191. }
  13192. m_reporter->benchmarkFailed(error);
  13193. }
  13194. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  13195. void ListeningReporter::testRunStarting( TestRunInfo const& testRunInfo ) {
  13196. for ( auto const& listener : m_listeners ) {
  13197. listener->testRunStarting( testRunInfo );
  13198. }
  13199. m_reporter->testRunStarting( testRunInfo );
  13200. }
  13201. void ListeningReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  13202. for ( auto const& listener : m_listeners ) {
  13203. listener->testGroupStarting( groupInfo );
  13204. }
  13205. m_reporter->testGroupStarting( groupInfo );
  13206. }
  13207. void ListeningReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
  13208. for ( auto const& listener : m_listeners ) {
  13209. listener->testCaseStarting( testInfo );
  13210. }
  13211. m_reporter->testCaseStarting( testInfo );
  13212. }
  13213. void ListeningReporter::sectionStarting( SectionInfo const& sectionInfo ) {
  13214. for ( auto const& listener : m_listeners ) {
  13215. listener->sectionStarting( sectionInfo );
  13216. }
  13217. m_reporter->sectionStarting( sectionInfo );
  13218. }
  13219. void ListeningReporter::assertionStarting( AssertionInfo const& assertionInfo ) {
  13220. for ( auto const& listener : m_listeners ) {
  13221. listener->assertionStarting( assertionInfo );
  13222. }
  13223. m_reporter->assertionStarting( assertionInfo );
  13224. }
  13225. // The return value indicates if the messages buffer should be cleared:
  13226. bool ListeningReporter::assertionEnded( AssertionStats const& assertionStats ) {
  13227. for( auto const& listener : m_listeners ) {
  13228. static_cast<void>( listener->assertionEnded( assertionStats ) );
  13229. }
  13230. return m_reporter->assertionEnded( assertionStats );
  13231. }
  13232. void ListeningReporter::sectionEnded( SectionStats const& sectionStats ) {
  13233. for ( auto const& listener : m_listeners ) {
  13234. listener->sectionEnded( sectionStats );
  13235. }
  13236. m_reporter->sectionEnded( sectionStats );
  13237. }
  13238. void ListeningReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  13239. for ( auto const& listener : m_listeners ) {
  13240. listener->testCaseEnded( testCaseStats );
  13241. }
  13242. m_reporter->testCaseEnded( testCaseStats );
  13243. }
  13244. void ListeningReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  13245. for ( auto const& listener : m_listeners ) {
  13246. listener->testGroupEnded( testGroupStats );
  13247. }
  13248. m_reporter->testGroupEnded( testGroupStats );
  13249. }
  13250. void ListeningReporter::testRunEnded( TestRunStats const& testRunStats ) {
  13251. for ( auto const& listener : m_listeners ) {
  13252. listener->testRunEnded( testRunStats );
  13253. }
  13254. m_reporter->testRunEnded( testRunStats );
  13255. }
  13256. void ListeningReporter::skipTest( TestCaseInfo const& testInfo ) {
  13257. for ( auto const& listener : m_listeners ) {
  13258. listener->skipTest( testInfo );
  13259. }
  13260. m_reporter->skipTest( testInfo );
  13261. }
  13262. bool ListeningReporter::isMulti() const {
  13263. return true;
  13264. }
  13265. } // end namespace Catch
  13266. // end catch_reporter_listening.cpp
  13267. // start catch_reporter_xml.cpp
  13268. #if defined(_MSC_VER)
  13269. #pragma warning(push)
  13270. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  13271. // Note that 4062 (not all labels are handled
  13272. // and default is missing) is enabled
  13273. #endif
  13274. namespace Catch {
  13275. XmlReporter::XmlReporter( ReporterConfig const& _config )
  13276. : StreamingReporterBase( _config ),
  13277. m_xml(_config.stream())
  13278. {
  13279. m_reporterPrefs.shouldRedirectStdOut = true;
  13280. m_reporterPrefs.shouldReportAllAssertions = true;
  13281. }
  13282. XmlReporter::~XmlReporter() = default;
  13283. std::string XmlReporter::getDescription() {
  13284. return "Reports test results as an XML document";
  13285. }
  13286. std::string XmlReporter::getStylesheetRef() const {
  13287. return std::string();
  13288. }
  13289. void XmlReporter::writeSourceInfo( SourceLineInfo const& sourceInfo ) {
  13290. m_xml
  13291. .writeAttribute( "filename", sourceInfo.file )
  13292. .writeAttribute( "line", sourceInfo.line );
  13293. }
  13294. void XmlReporter::noMatchingTestCases( std::string const& s ) {
  13295. StreamingReporterBase::noMatchingTestCases( s );
  13296. }
  13297. void XmlReporter::testRunStarting( TestRunInfo const& testInfo ) {
  13298. StreamingReporterBase::testRunStarting( testInfo );
  13299. std::string stylesheetRef = getStylesheetRef();
  13300. if( !stylesheetRef.empty() )
  13301. m_xml.writeStylesheetRef( stylesheetRef );
  13302. m_xml.startElement( "Catch" );
  13303. if( !m_config->name().empty() )
  13304. m_xml.writeAttribute( "name", m_config->name() );
  13305. if (m_config->testSpec().hasFilters())
  13306. m_xml.writeAttribute( "filters", serializeFilters( m_config->getTestsOrTags() ) );
  13307. if( m_config->rngSeed() != 0 )
  13308. m_xml.scopedElement( "Randomness" )
  13309. .writeAttribute( "seed", m_config->rngSeed() );
  13310. }
  13311. void XmlReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  13312. StreamingReporterBase::testGroupStarting( groupInfo );
  13313. m_xml.startElement( "Group" )
  13314. .writeAttribute( "name", groupInfo.name );
  13315. }
  13316. void XmlReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
  13317. StreamingReporterBase::testCaseStarting(testInfo);
  13318. m_xml.startElement( "TestCase" )
  13319. .writeAttribute( "name", trim( testInfo.name ) )
  13320. .writeAttribute( "description", testInfo.description )
  13321. .writeAttribute( "tags", testInfo.tagsAsString() );
  13322. writeSourceInfo( testInfo.lineInfo );
  13323. if ( m_config->showDurations() == ShowDurations::Always )
  13324. m_testCaseTimer.start();
  13325. m_xml.ensureTagClosed();
  13326. }
  13327. void XmlReporter::sectionStarting( SectionInfo const& sectionInfo ) {
  13328. StreamingReporterBase::sectionStarting( sectionInfo );
  13329. if( m_sectionDepth++ > 0 ) {
  13330. m_xml.startElement( "Section" )
  13331. .writeAttribute( "name", trim( sectionInfo.name ) );
  13332. writeSourceInfo( sectionInfo.lineInfo );
  13333. m_xml.ensureTagClosed();
  13334. }
  13335. }
  13336. void XmlReporter::assertionStarting( AssertionInfo const& ) { }
  13337. bool XmlReporter::assertionEnded( AssertionStats const& assertionStats ) {
  13338. AssertionResult const& result = assertionStats.assertionResult;
  13339. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  13340. if( includeResults || result.getResultType() == ResultWas::Warning ) {
  13341. // Print any info messages in <Info> tags.
  13342. for( auto const& msg : assertionStats.infoMessages ) {
  13343. if( msg.type == ResultWas::Info && includeResults ) {
  13344. m_xml.scopedElement( "Info" )
  13345. .writeText( msg.message );
  13346. } else if ( msg.type == ResultWas::Warning ) {
  13347. m_xml.scopedElement( "Warning" )
  13348. .writeText( msg.message );
  13349. }
  13350. }
  13351. }
  13352. // Drop out if result was successful but we're not printing them.
  13353. if( !includeResults && result.getResultType() != ResultWas::Warning )
  13354. return true;
  13355. // Print the expression if there is one.
  13356. if( result.hasExpression() ) {
  13357. m_xml.startElement( "Expression" )
  13358. .writeAttribute( "success", result.succeeded() )
  13359. .writeAttribute( "type", result.getTestMacroName() );
  13360. writeSourceInfo( result.getSourceInfo() );
  13361. m_xml.scopedElement( "Original" )
  13362. .writeText( result.getExpression() );
  13363. m_xml.scopedElement( "Expanded" )
  13364. .writeText( result.getExpandedExpression() );
  13365. }
  13366. // And... Print a result applicable to each result type.
  13367. switch( result.getResultType() ) {
  13368. case ResultWas::ThrewException:
  13369. m_xml.startElement( "Exception" );
  13370. writeSourceInfo( result.getSourceInfo() );
  13371. m_xml.writeText( result.getMessage() );
  13372. m_xml.endElement();
  13373. break;
  13374. case ResultWas::FatalErrorCondition:
  13375. m_xml.startElement( "FatalErrorCondition" );
  13376. writeSourceInfo( result.getSourceInfo() );
  13377. m_xml.writeText( result.getMessage() );
  13378. m_xml.endElement();
  13379. break;
  13380. case ResultWas::Info:
  13381. m_xml.scopedElement( "Info" )
  13382. .writeText( result.getMessage() );
  13383. break;
  13384. case ResultWas::Warning:
  13385. // Warning will already have been written
  13386. break;
  13387. case ResultWas::ExplicitFailure:
  13388. m_xml.startElement( "Failure" );
  13389. writeSourceInfo( result.getSourceInfo() );
  13390. m_xml.writeText( result.getMessage() );
  13391. m_xml.endElement();
  13392. break;
  13393. default:
  13394. break;
  13395. }
  13396. if( result.hasExpression() )
  13397. m_xml.endElement();
  13398. return true;
  13399. }
  13400. void XmlReporter::sectionEnded( SectionStats const& sectionStats ) {
  13401. StreamingReporterBase::sectionEnded( sectionStats );
  13402. if( --m_sectionDepth > 0 ) {
  13403. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResults" );
  13404. e.writeAttribute( "successes", sectionStats.assertions.passed );
  13405. e.writeAttribute( "failures", sectionStats.assertions.failed );
  13406. e.writeAttribute( "expectedFailures", sectionStats.assertions.failedButOk );
  13407. if ( m_config->showDurations() == ShowDurations::Always )
  13408. e.writeAttribute( "durationInSeconds", sectionStats.durationInSeconds );
  13409. m_xml.endElement();
  13410. }
  13411. }
  13412. void XmlReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  13413. StreamingReporterBase::testCaseEnded( testCaseStats );
  13414. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResult" );
  13415. e.writeAttribute( "success", testCaseStats.totals.assertions.allOk() );
  13416. if ( m_config->showDurations() == ShowDurations::Always )
  13417. e.writeAttribute( "durationInSeconds", m_testCaseTimer.getElapsedSeconds() );
  13418. if( !testCaseStats.stdOut.empty() )
  13419. m_xml.scopedElement( "StdOut" ).writeText( trim( testCaseStats.stdOut ), false );
  13420. if( !testCaseStats.stdErr.empty() )
  13421. m_xml.scopedElement( "StdErr" ).writeText( trim( testCaseStats.stdErr ), false );
  13422. m_xml.endElement();
  13423. }
  13424. void XmlReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  13425. StreamingReporterBase::testGroupEnded( testGroupStats );
  13426. // TODO: Check testGroupStats.aborting and act accordingly.
  13427. m_xml.scopedElement( "OverallResults" )
  13428. .writeAttribute( "successes", testGroupStats.totals.assertions.passed )
  13429. .writeAttribute( "failures", testGroupStats.totals.assertions.failed )
  13430. .writeAttribute( "expectedFailures", testGroupStats.totals.assertions.failedButOk );
  13431. m_xml.endElement();
  13432. }
  13433. void XmlReporter::testRunEnded( TestRunStats const& testRunStats ) {
  13434. StreamingReporterBase::testRunEnded( testRunStats );
  13435. m_xml.scopedElement( "OverallResults" )
  13436. .writeAttribute( "successes", testRunStats.totals.assertions.passed )
  13437. .writeAttribute( "failures", testRunStats.totals.assertions.failed )
  13438. .writeAttribute( "expectedFailures", testRunStats.totals.assertions.failedButOk );
  13439. m_xml.endElement();
  13440. }
  13441. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  13442. void XmlReporter::benchmarkStarting(BenchmarkInfo const &info) {
  13443. m_xml.startElement("BenchmarkResults")
  13444. .writeAttribute("name", info.name)
  13445. .writeAttribute("samples", info.samples)
  13446. .writeAttribute("resamples", info.resamples)
  13447. .writeAttribute("iterations", info.iterations)
  13448. .writeAttribute("clockResolution", static_cast<uint64_t>(info.clockResolution))
  13449. .writeAttribute("estimatedDuration", static_cast<uint64_t>(info.estimatedDuration))
  13450. .writeComment("All values in nano seconds");
  13451. }
  13452. void XmlReporter::benchmarkEnded(BenchmarkStats<> const& benchmarkStats) {
  13453. m_xml.startElement("mean")
  13454. .writeAttribute("value", static_cast<uint64_t>(benchmarkStats.mean.point.count()))
  13455. .writeAttribute("lowerBound", static_cast<uint64_t>(benchmarkStats.mean.lower_bound.count()))
  13456. .writeAttribute("upperBound", static_cast<uint64_t>(benchmarkStats.mean.upper_bound.count()))
  13457. .writeAttribute("ci", benchmarkStats.mean.confidence_interval);
  13458. m_xml.endElement();
  13459. m_xml.startElement("standardDeviation")
  13460. .writeAttribute("value", benchmarkStats.standardDeviation.point.count())
  13461. .writeAttribute("lowerBound", benchmarkStats.standardDeviation.lower_bound.count())
  13462. .writeAttribute("upperBound", benchmarkStats.standardDeviation.upper_bound.count())
  13463. .writeAttribute("ci", benchmarkStats.standardDeviation.confidence_interval);
  13464. m_xml.endElement();
  13465. m_xml.startElement("outliers")
  13466. .writeAttribute("variance", benchmarkStats.outlierVariance)
  13467. .writeAttribute("lowMild", benchmarkStats.outliers.low_mild)
  13468. .writeAttribute("lowSevere", benchmarkStats.outliers.low_severe)
  13469. .writeAttribute("highMild", benchmarkStats.outliers.high_mild)
  13470. .writeAttribute("highSevere", benchmarkStats.outliers.high_severe);
  13471. m_xml.endElement();
  13472. m_xml.endElement();
  13473. }
  13474. void XmlReporter::benchmarkFailed(std::string const &error) {
  13475. m_xml.scopedElement("failed").
  13476. writeAttribute("message", error);
  13477. m_xml.endElement();
  13478. }
  13479. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  13480. CATCH_REGISTER_REPORTER( "xml", XmlReporter )
  13481. } // end namespace Catch
  13482. #if defined(_MSC_VER)
  13483. #pragma warning(pop)
  13484. #endif
  13485. // end catch_reporter_xml.cpp
  13486. namespace Catch {
  13487. LeakDetector leakDetector;
  13488. }
  13489. #ifdef __clang__
  13490. #pragma clang diagnostic pop
  13491. #endif
  13492. // end catch_impl.hpp
  13493. #endif
  13494. #ifdef CATCH_CONFIG_MAIN
  13495. // start catch_default_main.hpp
  13496. #ifndef __OBJC__
  13497. #if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN)
  13498. // Standard C/C++ Win32 Unicode wmain entry point
  13499. extern "C" int wmain (int argc, wchar_t * argv[], wchar_t * []) {
  13500. #else
  13501. // Standard C/C++ main entry point
  13502. int main (int argc, char * argv[]) {
  13503. #endif
  13504. return Catch::Session().run( argc, argv );
  13505. }
  13506. #else // __OBJC__
  13507. // Objective-C entry point
  13508. int main (int argc, char * const argv[]) {
  13509. #if !CATCH_ARC_ENABLED
  13510. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  13511. #endif
  13512. Catch::registerTestMethods();
  13513. int result = Catch::Session().run( argc, (char**)argv );
  13514. #if !CATCH_ARC_ENABLED
  13515. [pool drain];
  13516. #endif
  13517. return result;
  13518. }
  13519. #endif // __OBJC__
  13520. // end catch_default_main.hpp
  13521. #endif
  13522. #if !defined(CATCH_CONFIG_IMPL_ONLY)
  13523. #ifdef CLARA_CONFIG_MAIN_NOT_DEFINED
  13524. # undef CLARA_CONFIG_MAIN
  13525. #endif
  13526. #if !defined(CATCH_CONFIG_DISABLE)
  13527. //////
  13528. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  13529. #ifdef CATCH_CONFIG_PREFIX_ALL
  13530. #define CATCH_REQUIRE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  13531. #define CATCH_REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  13532. #define CATCH_REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  13533. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  13534. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  13535. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13536. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  13537. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  13538. #define CATCH_REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  13539. #define CATCH_CHECK( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13540. #define CATCH_CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  13541. #define CATCH_CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13542. #define CATCH_CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13543. #define CATCH_CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  13544. #define CATCH_CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13545. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  13546. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  13547. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13548. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  13549. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  13550. #define CATCH_CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13551. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13552. #define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  13553. #define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  13554. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  13555. #define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg )
  13556. #define CATCH_UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "CATCH_UNSCOPED_INFO", msg )
  13557. #define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  13558. #define CATCH_CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CATCH_CAPTURE",__VA_ARGS__ )
  13559. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  13560. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13561. #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  13562. #define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  13563. #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  13564. #define CATCH_DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
  13565. #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  13566. #define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13567. #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13568. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  13569. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  13570. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  13571. #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ )
  13572. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13573. #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
  13574. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )
  13575. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ )
  13576. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13577. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
  13578. #else
  13579. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
  13580. #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) )
  13581. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  13582. #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
  13583. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )
  13584. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) )
  13585. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  13586. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
  13587. #endif
  13588. #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
  13589. #define CATCH_STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__ , #__VA_ARGS__ ); CATCH_SUCCEED( #__VA_ARGS__ )
  13590. #define CATCH_STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); CATCH_SUCCEED( #__VA_ARGS__ )
  13591. #else
  13592. #define CATCH_STATIC_REQUIRE( ... ) CATCH_REQUIRE( __VA_ARGS__ )
  13593. #define CATCH_STATIC_REQUIRE_FALSE( ... ) CATCH_REQUIRE_FALSE( __VA_ARGS__ )
  13594. #endif
  13595. // "BDD-style" convenience wrappers
  13596. #define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ )
  13597. #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  13598. #define CATCH_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
  13599. #define CATCH_AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
  13600. #define CATCH_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
  13601. #define CATCH_AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
  13602. #define CATCH_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
  13603. #define CATCH_AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
  13604. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  13605. #define CATCH_BENCHMARK(...) \
  13606. 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__,,))
  13607. #define CATCH_BENCHMARK_ADVANCED(name) \
  13608. INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), name)
  13609. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  13610. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  13611. #else
  13612. #define REQUIRE( ... ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  13613. #define REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  13614. #define REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  13615. #define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  13616. #define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  13617. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13618. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  13619. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  13620. #define REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  13621. #define CHECK( ... ) INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13622. #define CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  13623. #define CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13624. #define CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13625. #define CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  13626. #define CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13627. #define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  13628. #define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  13629. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13630. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  13631. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  13632. #define CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13633. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13634. #define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  13635. #define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  13636. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  13637. #define INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg )
  13638. #define UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "UNSCOPED_INFO", msg )
  13639. #define WARN( msg ) INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  13640. #define CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CAPTURE",__VA_ARGS__ )
  13641. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  13642. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13643. #define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  13644. #define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  13645. #define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  13646. #define DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
  13647. #define FAIL( ... ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  13648. #define FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13649. #define SUCCEED( ... ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13650. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  13651. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  13652. #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  13653. #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ )
  13654. #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13655. #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
  13656. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )
  13657. #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ )
  13658. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13659. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
  13660. #define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(__VA_ARGS__)
  13661. #define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13662. #else
  13663. #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
  13664. #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) )
  13665. #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  13666. #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
  13667. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )
  13668. #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) )
  13669. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  13670. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
  13671. #define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE( __VA_ARGS__ ) )
  13672. #define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  13673. #endif
  13674. #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
  13675. #define STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__, #__VA_ARGS__ ); SUCCEED( #__VA_ARGS__ )
  13676. #define STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); SUCCEED( "!(" #__VA_ARGS__ ")" )
  13677. #else
  13678. #define STATIC_REQUIRE( ... ) REQUIRE( __VA_ARGS__ )
  13679. #define STATIC_REQUIRE_FALSE( ... ) REQUIRE_FALSE( __VA_ARGS__ )
  13680. #endif
  13681. #endif
  13682. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature )
  13683. // "BDD-style" convenience wrappers
  13684. #define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ )
  13685. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  13686. #define GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
  13687. #define AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
  13688. #define WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
  13689. #define AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
  13690. #define THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
  13691. #define AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
  13692. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  13693. #define BENCHMARK(...) \
  13694. 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__,,))
  13695. #define BENCHMARK_ADVANCED(name) \
  13696. INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), name)
  13697. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  13698. using Catch::Detail::Approx;
  13699. #else // CATCH_CONFIG_DISABLE
  13700. //////
  13701. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  13702. #ifdef CATCH_CONFIG_PREFIX_ALL
  13703. #define CATCH_REQUIRE( ... ) (void)(0)
  13704. #define CATCH_REQUIRE_FALSE( ... ) (void)(0)
  13705. #define CATCH_REQUIRE_THROWS( ... ) (void)(0)
  13706. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  13707. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  13708. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13709. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  13710. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  13711. #define CATCH_REQUIRE_NOTHROW( ... ) (void)(0)
  13712. #define CATCH_CHECK( ... ) (void)(0)
  13713. #define CATCH_CHECK_FALSE( ... ) (void)(0)
  13714. #define CATCH_CHECKED_IF( ... ) if (__VA_ARGS__)
  13715. #define CATCH_CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  13716. #define CATCH_CHECK_NOFAIL( ... ) (void)(0)
  13717. #define CATCH_CHECK_THROWS( ... ) (void)(0)
  13718. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  13719. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  13720. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13721. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  13722. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  13723. #define CATCH_CHECK_NOTHROW( ... ) (void)(0)
  13724. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13725. #define CATCH_CHECK_THAT( arg, matcher ) (void)(0)
  13726. #define CATCH_REQUIRE_THAT( arg, matcher ) (void)(0)
  13727. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  13728. #define CATCH_INFO( msg ) (void)(0)
  13729. #define CATCH_UNSCOPED_INFO( msg ) (void)(0)
  13730. #define CATCH_WARN( msg ) (void)(0)
  13731. #define CATCH_CAPTURE( msg ) (void)(0)
  13732. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  13733. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  13734. #define CATCH_METHOD_AS_TEST_CASE( method, ... )
  13735. #define CATCH_REGISTER_TEST_CASE( Function, ... ) (void)(0)
  13736. #define CATCH_SECTION( ... )
  13737. #define CATCH_DYNAMIC_SECTION( ... )
  13738. #define CATCH_FAIL( ... ) (void)(0)
  13739. #define CATCH_FAIL_CHECK( ... ) (void)(0)
  13740. #define CATCH_SUCCEED( ... ) (void)(0)
  13741. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  13742. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  13743. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
  13744. #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
  13745. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
  13746. #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ )
  13747. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  13748. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  13749. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13750. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13751. #else
  13752. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) )
  13753. #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) )
  13754. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) )
  13755. #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) )
  13756. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  13757. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  13758. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13759. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13760. #endif
  13761. // "BDD-style" convenience wrappers
  13762. #define CATCH_SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  13763. #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 )
  13764. #define CATCH_GIVEN( desc )
  13765. #define CATCH_AND_GIVEN( desc )
  13766. #define CATCH_WHEN( desc )
  13767. #define CATCH_AND_WHEN( desc )
  13768. #define CATCH_THEN( desc )
  13769. #define CATCH_AND_THEN( desc )
  13770. #define CATCH_STATIC_REQUIRE( ... ) (void)(0)
  13771. #define CATCH_STATIC_REQUIRE_FALSE( ... ) (void)(0)
  13772. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  13773. #else
  13774. #define REQUIRE( ... ) (void)(0)
  13775. #define REQUIRE_FALSE( ... ) (void)(0)
  13776. #define REQUIRE_THROWS( ... ) (void)(0)
  13777. #define REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  13778. #define REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  13779. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13780. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  13781. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  13782. #define REQUIRE_NOTHROW( ... ) (void)(0)
  13783. #define CHECK( ... ) (void)(0)
  13784. #define CHECK_FALSE( ... ) (void)(0)
  13785. #define CHECKED_IF( ... ) if (__VA_ARGS__)
  13786. #define CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  13787. #define CHECK_NOFAIL( ... ) (void)(0)
  13788. #define CHECK_THROWS( ... ) (void)(0)
  13789. #define CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  13790. #define CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  13791. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13792. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  13793. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  13794. #define CHECK_NOTHROW( ... ) (void)(0)
  13795. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13796. #define CHECK_THAT( arg, matcher ) (void)(0)
  13797. #define REQUIRE_THAT( arg, matcher ) (void)(0)
  13798. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  13799. #define INFO( msg ) (void)(0)
  13800. #define UNSCOPED_INFO( msg ) (void)(0)
  13801. #define WARN( msg ) (void)(0)
  13802. #define CAPTURE( msg ) (void)(0)
  13803. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  13804. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  13805. #define METHOD_AS_TEST_CASE( method, ... )
  13806. #define REGISTER_TEST_CASE( Function, ... ) (void)(0)
  13807. #define SECTION( ... )
  13808. #define DYNAMIC_SECTION( ... )
  13809. #define FAIL( ... ) (void)(0)
  13810. #define FAIL_CHECK( ... ) (void)(0)
  13811. #define SUCCEED( ... ) (void)(0)
  13812. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  13813. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  13814. #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
  13815. #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
  13816. #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
  13817. #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ )
  13818. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
  13819. #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
  13820. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13821. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13822. #else
  13823. #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) )
  13824. #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) )
  13825. #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) )
  13826. #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) )
  13827. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
  13828. #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
  13829. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13830. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13831. #endif
  13832. #define STATIC_REQUIRE( ... ) (void)(0)
  13833. #define STATIC_REQUIRE_FALSE( ... ) (void)(0)
  13834. #endif
  13835. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
  13836. // "BDD-style" convenience wrappers
  13837. #define SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) )
  13838. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className )
  13839. #define GIVEN( desc )
  13840. #define AND_GIVEN( desc )
  13841. #define WHEN( desc )
  13842. #define AND_WHEN( desc )
  13843. #define THEN( desc )
  13844. #define AND_THEN( desc )
  13845. using Catch::Detail::Approx;
  13846. #endif
  13847. #endif // ! CATCH_CONFIG_IMPL_ONLY
  13848. // start catch_reenable_warnings.h
  13849. #ifdef __clang__
  13850. # ifdef __ICC // icpc defines the __clang__ macro
  13851. # pragma warning(pop)
  13852. # else
  13853. # pragma clang diagnostic pop
  13854. # endif
  13855. #elif defined __GNUC__
  13856. # pragma GCC diagnostic pop
  13857. #endif
  13858. // end catch_reenable_warnings.h
  13859. // end catch.hpp
  13860. #endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED