catch.hpp 601 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516
  1. /*
  2. * Catch v2.9.2
  3. * Generated: 2019-08-08 13:35:12.279703
  4. * ----------------------------------------------------------
  5. * This file has been merged from multiple headers. Please don't edit it directly
  6. * Copyright (c) 2019 Two Blue Cubes Ltd. All rights reserved.
  7. *
  8. * Distributed under the Boost Software License, Version 1.0. (See accompanying
  9. * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  10. */
  11. #ifndef TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
  12. #define TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
  13. // start catch.hpp
  14. #define CATCH_VERSION_MAJOR 2
  15. #define CATCH_VERSION_MINOR 9
  16. #define CATCH_VERSION_PATCH 2
  17. #ifdef __clang__
  18. # pragma clang system_header
  19. #elif defined __GNUC__
  20. # pragma GCC system_header
  21. #endif
  22. // start catch_suppress_warnings.h
  23. #ifdef __clang__
  24. # ifdef __ICC // icpc defines the __clang__ macro
  25. # pragma warning(push)
  26. # pragma warning(disable: 161 1682)
  27. # else // __ICC
  28. # pragma clang diagnostic push
  29. # pragma clang diagnostic ignored "-Wpadded"
  30. # pragma clang diagnostic ignored "-Wswitch-enum"
  31. # pragma clang diagnostic ignored "-Wcovered-switch-default"
  32. # endif
  33. #elif defined __GNUC__
  34. // Because REQUIREs trigger GCC's -Wparentheses, and because still
  35. // supported version of g++ have only buggy support for _Pragmas,
  36. // Wparentheses have to be suppressed globally.
  37. # pragma GCC diagnostic ignored "-Wparentheses" // See #674 for details
  38. # pragma GCC diagnostic push
  39. # pragma GCC diagnostic ignored "-Wunused-variable"
  40. # pragma GCC diagnostic ignored "-Wpadded"
  41. #endif
  42. // end catch_suppress_warnings.h
  43. #if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER)
  44. # define CATCH_IMPL
  45. # define CATCH_CONFIG_ALL_PARTS
  46. #endif
  47. // In the impl file, we want to have access to all parts of the headers
  48. // Can also be used to sanely support PCHs
  49. #if defined(CATCH_CONFIG_ALL_PARTS)
  50. # define CATCH_CONFIG_EXTERNAL_INTERFACES
  51. # if defined(CATCH_CONFIG_DISABLE_MATCHERS)
  52. # undef CATCH_CONFIG_DISABLE_MATCHERS
  53. # endif
  54. # if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  55. # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  56. # endif
  57. #endif
  58. #if !defined(CATCH_CONFIG_IMPL_ONLY)
  59. // start catch_platform.h
  60. #ifdef __APPLE__
  61. # include <TargetConditionals.h>
  62. # if TARGET_OS_OSX == 1
  63. # define CATCH_PLATFORM_MAC
  64. # elif TARGET_OS_IPHONE == 1
  65. # define CATCH_PLATFORM_IPHONE
  66. # endif
  67. #elif defined(linux) || defined(__linux) || defined(__linux__)
  68. # define CATCH_PLATFORM_LINUX
  69. #elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) || defined(__MINGW32__)
  70. # define CATCH_PLATFORM_WINDOWS
  71. #endif
  72. // end catch_platform.h
  73. #ifdef CATCH_IMPL
  74. # ifndef CLARA_CONFIG_MAIN
  75. # define CLARA_CONFIG_MAIN_NOT_DEFINED
  76. # define CLARA_CONFIG_MAIN
  77. # endif
  78. #endif
  79. // start catch_user_interfaces.h
  80. namespace Catch {
  81. unsigned int rngSeed();
  82. }
  83. // end catch_user_interfaces.h
  84. // start catch_tag_alias_autoregistrar.h
  85. // start catch_common.h
  86. // start catch_compiler_capabilities.h
  87. // Detect a number of compiler features - by compiler
  88. // The following features are defined:
  89. //
  90. // CATCH_CONFIG_COUNTER : is the __COUNTER__ macro supported?
  91. // CATCH_CONFIG_WINDOWS_SEH : is Windows SEH supported?
  92. // CATCH_CONFIG_POSIX_SIGNALS : are POSIX signals supported?
  93. // CATCH_CONFIG_DISABLE_EXCEPTIONS : Are exceptions enabled?
  94. // ****************
  95. // Note to maintainers: if new toggles are added please document them
  96. // in configuration.md, too
  97. // ****************
  98. // In general each macro has a _NO_<feature name> form
  99. // (e.g. CATCH_CONFIG_NO_POSIX_SIGNALS) which disables the feature.
  100. // Many features, at point of detection, define an _INTERNAL_ macro, so they
  101. // can be combined, en-mass, with the _NO_ forms later.
  102. #ifdef __cplusplus
  103. # if (__cplusplus >= 201402L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201402L)
  104. # define CATCH_CPP14_OR_GREATER
  105. # endif
  106. # if (__cplusplus >= 201703L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L)
  107. # define CATCH_CPP17_OR_GREATER
  108. # endif
  109. #endif
  110. #if defined(CATCH_CPP17_OR_GREATER)
  111. # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
  112. #endif
  113. #ifdef __clang__
  114. # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  115. _Pragma( "clang diagnostic push" ) \
  116. _Pragma( "clang diagnostic ignored \"-Wexit-time-destructors\"" ) \
  117. _Pragma( "clang diagnostic ignored \"-Wglobal-constructors\"")
  118. # define CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  119. _Pragma( "clang diagnostic pop" )
  120. # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
  121. _Pragma( "clang diagnostic push" ) \
  122. _Pragma( "clang diagnostic ignored \"-Wparentheses\"" )
  123. # define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
  124. _Pragma( "clang diagnostic pop" )
  125. # define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
  126. _Pragma( "clang diagnostic push" ) \
  127. _Pragma( "clang diagnostic ignored \"-Wunused-variable\"" )
  128. # define CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS \
  129. _Pragma( "clang diagnostic pop" )
  130. # define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
  131. _Pragma( "clang diagnostic push" ) \
  132. _Pragma( "clang diagnostic ignored \"-Wgnu-zero-variadic-macro-arguments\"" )
  133. # define CATCH_INTERNAL_UNSUPPRESS_ZERO_VARIADIC_WARNINGS \
  134. _Pragma( "clang diagnostic pop" )
  135. #endif // __clang__
  136. ////////////////////////////////////////////////////////////////////////////////
  137. // Assume that non-Windows platforms support posix signals by default
  138. #if !defined(CATCH_PLATFORM_WINDOWS)
  139. #define CATCH_INTERNAL_CONFIG_POSIX_SIGNALS
  140. #endif
  141. ////////////////////////////////////////////////////////////////////////////////
  142. // We know some environments not to support full POSIX signals
  143. #if defined(__CYGWIN__) || defined(__QNX__) || defined(__EMSCRIPTEN__) || defined(__DJGPP__)
  144. #define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
  145. #endif
  146. #ifdef __OS400__
  147. # define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
  148. # define CATCH_CONFIG_COLOUR_NONE
  149. #endif
  150. ////////////////////////////////////////////////////////////////////////////////
  151. // Android somehow still does not support std::to_string
  152. #if defined(__ANDROID__)
  153. # define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
  154. #endif
  155. ////////////////////////////////////////////////////////////////////////////////
  156. // Not all Windows environments support SEH properly
  157. #if defined(__MINGW32__)
  158. # define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH
  159. #endif
  160. ////////////////////////////////////////////////////////////////////////////////
  161. // PS4
  162. #if defined(__ORBIS__)
  163. # define CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE
  164. #endif
  165. ////////////////////////////////////////////////////////////////////////////////
  166. // Cygwin
  167. #ifdef __CYGWIN__
  168. // Required for some versions of Cygwin to declare gettimeofday
  169. // see: http://stackoverflow.com/questions/36901803/gettimeofday-not-declared-in-this-scope-cygwin
  170. # define _BSD_SOURCE
  171. // some versions of cygwin (most) do not support std::to_string. Use the libstd check.
  172. // https://gcc.gnu.org/onlinedocs/gcc-4.8.2/libstdc++/api/a01053_source.html line 2812-2813
  173. # if !((__cplusplus >= 201103L) && defined(_GLIBCXX_USE_C99) \
  174. && !defined(_GLIBCXX_HAVE_BROKEN_VSWPRINTF))
  175. # define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
  176. # endif
  177. #endif // __CYGWIN__
  178. ////////////////////////////////////////////////////////////////////////////////
  179. // Visual C++
  180. #ifdef _MSC_VER
  181. # if _MSC_VER >= 1900 // Visual Studio 2015 or newer
  182. # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
  183. # endif
  184. // Universal Windows platform does not support SEH
  185. // Or console colours (or console at all...)
  186. # if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP)
  187. # define CATCH_CONFIG_COLOUR_NONE
  188. # else
  189. # define CATCH_INTERNAL_CONFIG_WINDOWS_SEH
  190. # endif
  191. // MSVC traditional preprocessor needs some workaround for __VA_ARGS__
  192. // _MSVC_TRADITIONAL == 0 means new conformant preprocessor
  193. // _MSVC_TRADITIONAL == 1 means old traditional non-conformant preprocessor
  194. # if !defined(_MSVC_TRADITIONAL) || (defined(_MSVC_TRADITIONAL) && _MSVC_TRADITIONAL)
  195. # define CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  196. # endif
  197. #endif // _MSC_VER
  198. #if defined(_REENTRANT) || defined(_MSC_VER)
  199. // Enable async processing, as -pthread is specified or no additional linking is required
  200. # define CATCH_INTERNAL_CONFIG_USE_ASYNC
  201. #endif // _MSC_VER
  202. ////////////////////////////////////////////////////////////////////////////////
  203. // Check if we are compiled with -fno-exceptions or equivalent
  204. #if defined(__EXCEPTIONS) || defined(__cpp_exceptions) || defined(_CPPUNWIND)
  205. # define CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED
  206. #endif
  207. ////////////////////////////////////////////////////////////////////////////////
  208. // DJGPP
  209. #ifdef __DJGPP__
  210. # define CATCH_INTERNAL_CONFIG_NO_WCHAR
  211. #endif // __DJGPP__
  212. ////////////////////////////////////////////////////////////////////////////////
  213. // Embarcadero C++Build
  214. #if defined(__BORLANDC__)
  215. #define CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN
  216. #endif
  217. ////////////////////////////////////////////////////////////////////////////////
  218. // Use of __COUNTER__ is suppressed during code analysis in
  219. // CLion/AppCode 2017.2.x and former, because __COUNTER__ is not properly
  220. // handled by it.
  221. // Otherwise all supported compilers support COUNTER macro,
  222. // but user still might want to turn it off
  223. #if (!defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L)
  224. #define CATCH_INTERNAL_CONFIG_COUNTER
  225. #endif
  226. ////////////////////////////////////////////////////////////////////////////////
  227. // RTX is a special version of Windows that is real time.
  228. // This means that it is detected as Windows, but does not provide
  229. // the same set of capabilities as real Windows does.
  230. #if defined(UNDER_RTSS) || defined(RTX64_BUILD)
  231. #define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH
  232. #define CATCH_INTERNAL_CONFIG_NO_ASYNC
  233. #define CATCH_CONFIG_COLOUR_NONE
  234. #endif
  235. ////////////////////////////////////////////////////////////////////////////////
  236. // Check if string_view is available and usable
  237. // The check is split apart to work around v140 (VS2015) preprocessor issue...
  238. #if defined(__has_include)
  239. #if __has_include(<string_view>) && defined(CATCH_CPP17_OR_GREATER)
  240. # define CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW
  241. #endif
  242. #endif
  243. ////////////////////////////////////////////////////////////////////////////////
  244. // Check if optional is available and usable
  245. #if defined(__has_include)
  246. # if __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
  247. # define CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL
  248. # endif // __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
  249. #endif // __has_include
  250. ////////////////////////////////////////////////////////////////////////////////
  251. // Check if byte is available and usable
  252. #if defined(__has_include)
  253. # if __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER)
  254. # define CATCH_INTERNAL_CONFIG_CPP17_BYTE
  255. # endif // __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER)
  256. #endif // __has_include
  257. ////////////////////////////////////////////////////////////////////////////////
  258. // Check if variant is available and usable
  259. #if defined(__has_include)
  260. # if __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
  261. # if defined(__clang__) && (__clang_major__ < 8)
  262. // work around clang bug with libstdc++ https://bugs.llvm.org/show_bug.cgi?id=31852
  263. // fix should be in clang 8, workaround in libstdc++ 8.2
  264. # include <ciso646>
  265. # if defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
  266. # define CATCH_CONFIG_NO_CPP17_VARIANT
  267. # else
  268. # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
  269. # endif // defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
  270. # else
  271. # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
  272. # endif // defined(__clang__) && (__clang_major__ < 8)
  273. # endif // __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
  274. #endif // __has_include
  275. #if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER)
  276. # define CATCH_CONFIG_COUNTER
  277. #endif
  278. #if defined(CATCH_INTERNAL_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_NO_WINDOWS_SEH) && !defined(CATCH_CONFIG_WINDOWS_SEH) && !defined(CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH)
  279. # define CATCH_CONFIG_WINDOWS_SEH
  280. #endif
  281. // This is set by default, because we assume that unix compilers are posix-signal-compatible by default.
  282. #if defined(CATCH_INTERNAL_CONFIG_POSIX_SIGNALS) && !defined(CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_POSIX_SIGNALS)
  283. # define CATCH_CONFIG_POSIX_SIGNALS
  284. #endif
  285. // This is set by default, because we assume that compilers with no wchar_t support are just rare exceptions.
  286. #if !defined(CATCH_INTERNAL_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_WCHAR)
  287. # define CATCH_CONFIG_WCHAR
  288. #endif
  289. #if !defined(CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_CPP11_TO_STRING)
  290. # define CATCH_CONFIG_CPP11_TO_STRING
  291. #endif
  292. #if defined(CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_NO_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_CPP17_OPTIONAL)
  293. # define CATCH_CONFIG_CPP17_OPTIONAL
  294. #endif
  295. #if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
  296. # define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
  297. #endif
  298. #if defined(CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_NO_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_CPP17_STRING_VIEW)
  299. # define CATCH_CONFIG_CPP17_STRING_VIEW
  300. #endif
  301. #if defined(CATCH_INTERNAL_CONFIG_CPP17_VARIANT) && !defined(CATCH_CONFIG_NO_CPP17_VARIANT) && !defined(CATCH_CONFIG_CPP17_VARIANT)
  302. # define CATCH_CONFIG_CPP17_VARIANT
  303. #endif
  304. #if defined(CATCH_INTERNAL_CONFIG_CPP17_BYTE) && !defined(CATCH_CONFIG_NO_CPP17_BYTE) && !defined(CATCH_CONFIG_CPP17_BYTE)
  305. # define CATCH_CONFIG_CPP17_BYTE
  306. #endif
  307. #if defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
  308. # define CATCH_INTERNAL_CONFIG_NEW_CAPTURE
  309. #endif
  310. #if defined(CATCH_INTERNAL_CONFIG_NEW_CAPTURE) && !defined(CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NEW_CAPTURE)
  311. # define CATCH_CONFIG_NEW_CAPTURE
  312. #endif
  313. #if !defined(CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  314. # define CATCH_CONFIG_DISABLE_EXCEPTIONS
  315. #endif
  316. #if defined(CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_NO_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_POLYFILL_ISNAN)
  317. # define CATCH_CONFIG_POLYFILL_ISNAN
  318. #endif
  319. #if defined(CATCH_INTERNAL_CONFIG_USE_ASYNC) && !defined(CATCH_INTERNAL_CONFIG_NO_ASYNC) && !defined(CATCH_CONFIG_NO_USE_ASYNC) && !defined(CATCH_CONFIG_USE_ASYNC)
  320. # define CATCH_CONFIG_USE_ASYNC
  321. #endif
  322. #if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS)
  323. # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS
  324. # define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS
  325. #endif
  326. #if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS)
  327. # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  328. # define CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  329. #endif
  330. #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS)
  331. # define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS
  332. # define CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS
  333. #endif
  334. #if !defined(CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS)
  335. # define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS
  336. # define CATCH_INTERNAL_UNSUPPRESS_ZERO_VARIADIC_WARNINGS
  337. #endif
  338. #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  339. #define CATCH_TRY if ((true))
  340. #define CATCH_CATCH_ALL if ((false))
  341. #define CATCH_CATCH_ANON(type) if ((false))
  342. #else
  343. #define CATCH_TRY try
  344. #define CATCH_CATCH_ALL catch (...)
  345. #define CATCH_CATCH_ANON(type) catch (type)
  346. #endif
  347. #if defined(CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_NO_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR)
  348. #define CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  349. #endif
  350. // end catch_compiler_capabilities.h
  351. #define INTERNAL_CATCH_UNIQUE_NAME_LINE2(name, line) name##line
  352. #define INTERNAL_CATCH_UNIQUE_NAME_LINE(name, line) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line )
  353. #ifdef CATCH_CONFIG_COUNTER
  354. # define INTERNAL_CATCH_UNIQUE_NAME(name) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ )
  355. #else
  356. # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ )
  357. #endif
  358. #include <iosfwd>
  359. #include <string>
  360. #include <cstdint>
  361. // We need a dummy global operator<< so we can bring it into Catch namespace later
  362. struct Catch_global_namespace_dummy
  363. {
  364. };
  365. std::ostream &operator<<(std::ostream &, Catch_global_namespace_dummy);
  366. namespace Catch {
  367. struct CaseSensitive
  368. {
  369. enum Choice
  370. {
  371. Yes,
  372. No
  373. };
  374. };
  375. class NonCopyable
  376. {
  377. NonCopyable(NonCopyable const &) = delete;
  378. NonCopyable(NonCopyable &&) = delete;
  379. NonCopyable &operator=(NonCopyable const &) = delete;
  380. NonCopyable &operator=(NonCopyable &&) = delete;
  381. protected:
  382. NonCopyable();
  383. virtual ~NonCopyable();
  384. };
  385. struct SourceLineInfo
  386. {
  387. SourceLineInfo() = delete;
  388. SourceLineInfo(char const *_file, std::size_t _line) noexcept
  389. : file(_file),
  390. line(_line)
  391. {}
  392. SourceLineInfo(SourceLineInfo const &other) = default;
  393. SourceLineInfo &operator=(SourceLineInfo const &) = default;
  394. SourceLineInfo(SourceLineInfo &&) noexcept = default;
  395. SourceLineInfo &operator=(SourceLineInfo &&) noexcept = default;
  396. bool empty() const noexcept;
  397. bool operator==(SourceLineInfo const &other) const noexcept;
  398. bool operator<(SourceLineInfo const &other) const noexcept;
  399. char const *file;
  400. std::size_t line;
  401. };
  402. std::ostream &operator<<(std::ostream &os, SourceLineInfo const &info);
  403. // Bring in operator<< from global namespace into Catch namespace
  404. // This is necessary because the overload of operator<< above makes
  405. // lookup stop at namespace Catch
  406. using ::operator<<;
  407. // Use this in variadic streaming macros to allow
  408. // >> +StreamEndStop
  409. // as well as
  410. // >> stuff +StreamEndStop
  411. struct StreamEndStop
  412. {
  413. std::string operator+() const;
  414. };
  415. template<typename T>
  416. T const &operator+(T const &value, StreamEndStop)
  417. {
  418. return value;
  419. }
  420. }
  421. #define CATCH_INTERNAL_LINEINFO \
  422. ::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) )
  423. // end catch_common.h
  424. namespace Catch {
  425. struct RegistrarForTagAliases
  426. {
  427. RegistrarForTagAliases(char const *alias, char const *tag, SourceLineInfo const &lineInfo);
  428. };
  429. } // end namespace Catch
  430. #define CATCH_REGISTER_TAG_ALIAS(alias, spec) \
  431. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  432. namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } \
  433. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  434. // end catch_tag_alias_autoregistrar.h
  435. // start catch_test_registry.h
  436. // start catch_interfaces_testcase.h
  437. #include <vector>
  438. namespace Catch {
  439. class TestSpec;
  440. struct ITestInvoker
  441. {
  442. virtual void invoke() const = 0;
  443. virtual ~ITestInvoker();
  444. };
  445. class TestCase;
  446. struct IConfig;
  447. struct ITestCaseRegistry
  448. {
  449. virtual ~ITestCaseRegistry();
  450. virtual std::vector<TestCase> const &getAllTests() const = 0;
  451. virtual std::vector<TestCase> const &getAllTestsSorted(IConfig const &config) const = 0;
  452. };
  453. bool isThrowSafe(TestCase const &testCase, IConfig const &config);
  454. bool matchTest(TestCase const &testCase, TestSpec const &testSpec, IConfig const &config);
  455. std::vector<TestCase> filterTests(std::vector<TestCase> const &testCases,
  456. TestSpec const &testSpec,
  457. IConfig const &config);
  458. std::vector<TestCase> const &getAllTestCasesSorted(IConfig const &config);
  459. }
  460. // end catch_interfaces_testcase.h
  461. // start catch_stringref.h
  462. #include <cstddef>
  463. #include <string>
  464. #include <iosfwd>
  465. namespace Catch {
  466. /// A non-owning string class (similar to the forthcoming std::string_view)
  467. /// Note that, because a StringRef may be a substring of another string,
  468. /// it may not be null terminated. c_str() must return a null terminated
  469. /// string, however, and so the StringRef will internally take ownership
  470. /// (taking a copy), if necessary. In theory this ownership is not externally
  471. /// visible - but it does mean (substring) StringRefs should not be shared between
  472. /// threads.
  473. class StringRef
  474. {
  475. public:
  476. using size_type = std::size_t;
  477. private:
  478. friend struct StringRefTestAccess;
  479. char const *m_start;
  480. size_type m_size;
  481. char *m_data = nullptr;
  482. void takeOwnership();
  483. static constexpr char const *const s_empty = "";
  484. public: // construction/ assignment
  485. StringRef() noexcept
  486. : StringRef(s_empty, 0)
  487. {}
  488. StringRef(StringRef const &other) noexcept
  489. : m_start(other.m_start),
  490. m_size(other.m_size)
  491. {}
  492. StringRef(StringRef &&other) noexcept
  493. : m_start(other.m_start),
  494. m_size(other.m_size),
  495. m_data(other.m_data)
  496. {
  497. other.m_data = nullptr;
  498. }
  499. StringRef(char const *rawChars) noexcept;
  500. StringRef(char const *rawChars, size_type size) noexcept
  501. : m_start(rawChars),
  502. m_size(size)
  503. {}
  504. StringRef(std::string const &stdString) noexcept
  505. : m_start(stdString.c_str()),
  506. m_size(stdString.size())
  507. {}
  508. ~StringRef() noexcept
  509. {
  510. delete[] m_data;
  511. }
  512. auto operator=(StringRef const &other) noexcept -> StringRef &
  513. {
  514. delete[] m_data;
  515. m_data = nullptr;
  516. m_start = other.m_start;
  517. m_size = other.m_size;
  518. return *this;
  519. }
  520. operator std::string() const;
  521. void swap(StringRef &other) noexcept;
  522. public: // operators
  523. auto operator==(StringRef const &other) const noexcept -> bool;
  524. auto operator!=(StringRef const &other) const noexcept -> bool;
  525. auto operator[](size_type index) const noexcept -> char;
  526. public: // named queries
  527. auto empty() const noexcept -> bool
  528. {
  529. return m_size == 0;
  530. }
  531. auto size() const noexcept -> size_type
  532. {
  533. return m_size;
  534. }
  535. auto numberOfCharacters() const noexcept -> size_type;
  536. auto c_str() const -> char const *;
  537. public: // substrings and searches
  538. auto substr(size_type start, size_type size) const noexcept -> StringRef;
  539. // Returns the current start pointer.
  540. // Note that the pointer can change when if the StringRef is a substring
  541. auto currentData() const noexcept -> char const *;
  542. private: // ownership queries - may not be consistent between calls
  543. auto isOwned() const noexcept -> bool;
  544. auto isSubstring() const noexcept -> bool;
  545. };
  546. auto operator+(StringRef const &lhs, StringRef const &rhs) -> std::string;
  547. auto operator+(StringRef const &lhs, char const *rhs) -> std::string;
  548. auto operator+(char const *lhs, StringRef const &rhs) -> std::string;
  549. auto operator+=(std::string &lhs, StringRef const &sr) -> std::string &;
  550. auto operator<<(std::ostream &os, StringRef const &sr) -> std::ostream &;
  551. inline auto operator "" _sr(char const *rawChars, std::size_t size) noexcept -> StringRef
  552. {
  553. return StringRef(rawChars, size);
  554. }
  555. } // namespace Catch
  556. inline auto operator "" _catch_sr(char const *rawChars,
  557. std::size_t size) noexcept -> Catch::StringRef
  558. {
  559. return Catch::StringRef(rawChars, size);
  560. }
  561. // end catch_stringref.h
  562. // start catch_type_traits.hpp
  563. #include <type_traits>
  564. namespace Catch {
  565. #ifdef CATCH_CPP17_OR_GREATER
  566. template <typename...>
  567. inline constexpr auto is_unique = std::true_type{};
  568. template <typename T, typename... Rest>
  569. inline constexpr auto is_unique<T, Rest...> = std::bool_constant<
  570. (!std::is_same_v<T, Rest> && ...) && is_unique<Rest...>
  571. >{};
  572. #else
  573. template<typename...>
  574. struct is_unique : std::true_type
  575. {
  576. };
  577. template<typename T0, typename T1, typename... Rest>
  578. struct is_unique<T0, T1, Rest...> : std::integral_constant
  579. <bool,
  580. !std::is_same<T0, T1>::value
  581. && is_unique<T0, Rest...>::value
  582. && is_unique<T1, Rest...>::value
  583. >
  584. {
  585. };
  586. #endif
  587. }
  588. // end catch_type_traits.hpp
  589. // start catch_preprocessor.hpp
  590. #define CATCH_RECURSION_LEVEL0(...) __VA_ARGS__
  591. #define CATCH_RECURSION_LEVEL1(...) CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(__VA_ARGS__)))
  592. #define CATCH_RECURSION_LEVEL2(...) CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(__VA_ARGS__)))
  593. #define CATCH_RECURSION_LEVEL3(...) CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(__VA_ARGS__)))
  594. #define CATCH_RECURSION_LEVEL4(...) CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(__VA_ARGS__)))
  595. #define CATCH_RECURSION_LEVEL5(...) CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(__VA_ARGS__)))
  596. #ifdef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  597. #define INTERNAL_CATCH_EXPAND_VARGS(...) __VA_ARGS__
  598. // MSVC needs more evaluations
  599. #define CATCH_RECURSION_LEVEL6(...) CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(__VA_ARGS__)))
  600. #define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL6(CATCH_RECURSION_LEVEL6(__VA_ARGS__))
  601. #else
  602. #define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL5(__VA_ARGS__)
  603. #endif
  604. #define CATCH_REC_END(...)
  605. #define CATCH_REC_OUT
  606. #define CATCH_EMPTY()
  607. #define CATCH_DEFER(id) id CATCH_EMPTY()
  608. #define CATCH_REC_GET_END2() 0, CATCH_REC_END
  609. #define CATCH_REC_GET_END1(...) CATCH_REC_GET_END2
  610. #define CATCH_REC_GET_END(...) CATCH_REC_GET_END1
  611. #define CATCH_REC_NEXT0(test, next, ...) next CATCH_REC_OUT
  612. #define CATCH_REC_NEXT1(test, next) CATCH_DEFER ( CATCH_REC_NEXT0 ) ( test, next, 0)
  613. #define CATCH_REC_NEXT(test, next) CATCH_REC_NEXT1(CATCH_REC_GET_END test, next)
  614. #define CATCH_REC_LIST0(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ )
  615. #define CATCH_REC_LIST1(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0) ) ( f, peek, __VA_ARGS__ )
  616. #define CATCH_REC_LIST2(f, x, peek, ...) f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ )
  617. #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__ )
  618. #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__ )
  619. #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__ )
  620. // Applies the function macro `f` to each of the remaining parameters, inserts commas between the results,
  621. // and passes userdata as the first parameter to each invocation,
  622. // e.g. CATCH_REC_LIST_UD(f, x, a, b, c) evaluates to f(x, a), f(x, b), f(x, c)
  623. #define CATCH_REC_LIST_UD(f, userdata, ...) CATCH_RECURSE(CATCH_REC_LIST2_UD(f, userdata, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
  624. #define CATCH_REC_LIST(f, ...) CATCH_RECURSE(CATCH_REC_LIST2(f, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
  625. #define INTERNAL_CATCH_EXPAND1(param) INTERNAL_CATCH_EXPAND2(param)
  626. #define INTERNAL_CATCH_EXPAND2(...) INTERNAL_CATCH_NO## __VA_ARGS__
  627. #define INTERNAL_CATCH_DEF(...) INTERNAL_CATCH_DEF __VA_ARGS__
  628. #define INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
  629. #define INTERNAL_CATCH_STRINGIZE(...) INTERNAL_CATCH_STRINGIZE2(__VA_ARGS__)
  630. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  631. #define INTERNAL_CATCH_STRINGIZE2(...) #__VA_ARGS__
  632. #define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param))
  633. #else
  634. // MSVC is adding extra space and needs another indirection to expand INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
  635. #define INTERNAL_CATCH_STRINGIZE2(...) INTERNAL_CATCH_STRINGIZE3(__VA_ARGS__)
  636. #define INTERNAL_CATCH_STRINGIZE3(...) #__VA_ARGS__
  637. #define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) (INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) + 1)
  638. #endif
  639. #define INTERNAL_CATCH_MAKE_NAMESPACE2(...) ns_##__VA_ARGS__
  640. #define INTERNAL_CATCH_MAKE_NAMESPACE(name) INTERNAL_CATCH_MAKE_NAMESPACE2(name)
  641. #define INTERNAL_CATCH_REMOVE_PARENS(...) INTERNAL_CATCH_EXPAND1(INTERNAL_CATCH_DEF __VA_ARGS__)
  642. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  643. #define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>())
  644. #define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__))
  645. #else
  646. #define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) INTERNAL_CATCH_EXPAND_VARGS(decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>()))
  647. #define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__)))
  648. #endif
  649. #define INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(...)\
  650. CATCH_REC_LIST(INTERNAL_CATCH_MAKE_TYPE_LIST,__VA_ARGS__)
  651. #define INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_0) INTERNAL_CATCH_REMOVE_PARENS(_0)
  652. #define INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_0, _1) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_1)
  653. #define INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_0, _1, _2) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_1, _2)
  654. #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)
  655. #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)
  656. #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)
  657. #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)
  658. #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)
  659. #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)
  660. #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)
  661. #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)
  662. #define INTERNAL_CATCH_VA_NARGS_IMPL(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N
  663. #define INTERNAL_CATCH_TYPE_GEN\
  664. template<typename...> struct TypeList {};\
  665. template<typename...Ts>\
  666. constexpr auto get_wrapper() noexcept -> TypeList<Ts...> { return {}; }\
  667. \
  668. template<template<typename...> class L1, typename...E1, template<typename...> class L2, typename...E2> \
  669. constexpr auto append(L1<E1...>, L2<E2...>) noexcept -> L1<E1...,E2...> { return {}; }\
  670. template< template<typename...> class L1, typename...E1, template<typename...> class L2, typename...E2, typename...Rest>\
  671. constexpr auto append(L1<E1...>, L2<E2...>, Rest...) noexcept -> decltype(append(L1<E1...,E2...>{}, Rest{}...)) { return {}; }\
  672. template< template<typename...> class L1, typename...E1, typename...Rest>\
  673. constexpr auto append(L1<E1...>, TypeList<mpl_::na>, Rest...) noexcept -> L1<E1...> { return {}; }\
  674. \
  675. template< template<typename...> class Container, template<typename...> class List, typename...elems>\
  676. constexpr auto rewrap(List<elems...>) noexcept -> TypeList<Container<elems...>> { return {}; }\
  677. template< template<typename...> class Container, template<typename...> class List, class...Elems, typename...Elements>\
  678. constexpr auto rewrap(List<Elems...>,Elements...) noexcept -> decltype(append(TypeList<Container<Elems...>>{}, rewrap<Container>(Elements{}...))) { return {}; }\
  679. \
  680. template<template <typename...> class Final, template< typename...> class...Containers, typename...Types>\
  681. constexpr auto create(TypeList<Types...>) noexcept -> decltype(append(Final<>{}, rewrap<Containers>(Types{}...)...)) { return {}; }\
  682. template<template <typename...> class Final, template <typename...> class List, typename...Ts>\
  683. constexpr auto convert(List<Ts...>) noexcept -> decltype(append(Final<>{},TypeList<Ts>{}...)) { return {}; }
  684. #define INTERNAL_CATCH_NTTP_1(signature, ...)\
  685. template<INTERNAL_CATCH_REMOVE_PARENS(signature)> struct Nttp{};\
  686. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  687. constexpr auto get_wrapper() noexcept -> Nttp<__VA_ARGS__> { return {}; } \
  688. \
  689. template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  690. constexpr auto rewrap(List<__VA_ARGS__>) noexcept -> TypeList<Container<__VA_ARGS__>> { return {}; }\
  691. template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature), typename...Elements>\
  692. constexpr auto rewrap(List<__VA_ARGS__>,Elements...elems) noexcept -> decltype(append(TypeList<Container<__VA_ARGS__>>{}, rewrap<Container>(elems...))) { return {}; }\
  693. template<template <typename...> class Final, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...Containers, typename...Types>\
  694. constexpr auto create(TypeList<Types...>) noexcept -> decltype(append(Final<>{}, rewrap<Containers>(Types{}...)...)) { return {}; }
  695. #define INTERNAL_CATCH_DECLARE_SIG_TEST0(TestName)
  696. #define INTERNAL_CATCH_DECLARE_SIG_TEST1(TestName, signature)\
  697. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  698. static void TestName()
  699. #define INTERNAL_CATCH_DECLARE_SIG_TEST_X(TestName, signature, ...)\
  700. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  701. static void TestName()
  702. #define INTERNAL_CATCH_DEFINE_SIG_TEST0(TestName)
  703. #define INTERNAL_CATCH_DEFINE_SIG_TEST1(TestName, signature)\
  704. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  705. static void TestName()
  706. #define INTERNAL_CATCH_DEFINE_SIG_TEST_X(TestName, signature, ...)\
  707. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  708. static void TestName()
  709. #define INTERNAL_CATCH_NTTP_REGISTER0(TestFunc, signature)\
  710. template<typename Type>\
  711. void reg_test(TypeList<Type>, Catch::NameAndTags nameAndTags)\
  712. {\
  713. Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<Type>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\
  714. }
  715. #define INTERNAL_CATCH_NTTP_REGISTER(TestFunc, signature, ...)\
  716. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  717. void reg_test(Nttp<__VA_ARGS__>, Catch::NameAndTags nameAndTags)\
  718. {\
  719. Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<__VA_ARGS__>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\
  720. }
  721. #define INTERNAL_CATCH_NTTP_REGISTER_METHOD0(TestName, signature, ...)\
  722. template<typename Type>\
  723. void reg_test(TypeList<Type>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\
  724. {\
  725. Catch::AutoReg( Catch::makeTestInvoker(&TestName<Type>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\
  726. }
  727. #define INTERNAL_CATCH_NTTP_REGISTER_METHOD(TestName, signature, ...)\
  728. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  729. void reg_test(Nttp<__VA_ARGS__>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\
  730. {\
  731. Catch::AutoReg( Catch::makeTestInvoker(&TestName<__VA_ARGS__>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\
  732. }
  733. #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0(TestName, ClassName)
  734. #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1(TestName, ClassName, signature)\
  735. template<typename TestType> \
  736. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<TestType> { \
  737. void test();\
  738. }
  739. #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X(TestName, ClassName, signature, ...)\
  740. template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \
  741. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<__VA_ARGS__> { \
  742. void test();\
  743. }
  744. #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0(TestName)
  745. #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1(TestName, signature)\
  746. template<typename TestType> \
  747. void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<TestType>::test()
  748. #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X(TestName, signature, ...)\
  749. template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \
  750. void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<__VA_ARGS__>::test()
  751. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  752. #define INTERNAL_CATCH_NTTP_0
  753. #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)
  754. #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__)
  755. #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__)
  756. #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__)
  757. #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__)
  758. #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__)
  759. #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__)
  760. #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__)
  761. #else
  762. #define INTERNAL_CATCH_NTTP_0(signature)
  763. #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__))
  764. #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__))
  765. #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__))
  766. #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__))
  767. #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__))
  768. #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__))
  769. #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__))
  770. #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__))
  771. #endif
  772. // end catch_preprocessor.hpp
  773. // start catch_meta.hpp
  774. #include <type_traits>
  775. namespace Catch {
  776. template<typename T>
  777. struct always_false : std::false_type
  778. {
  779. };
  780. template<typename> struct true_given : std::true_type
  781. {
  782. };
  783. struct is_callable_tester
  784. {
  785. template<typename Fun, typename... Args>
  786. true_given<decltype(std::declval<Fun>()(std::declval<Args>()...))> static test(int);
  787. template<typename...>
  788. std::false_type static test(...);
  789. };
  790. template<typename T>
  791. struct is_callable;
  792. template<typename Fun, typename... Args>
  793. struct is_callable<Fun(Args...)> : decltype(is_callable_tester::test<Fun, Args...>(0))
  794. {
  795. };
  796. } // namespace Catch
  797. namespace mpl_ {
  798. struct na;
  799. }
  800. // end catch_meta.hpp
  801. namespace Catch {
  802. template<typename C>
  803. class TestInvokerAsMethod : public ITestInvoker
  804. {
  805. void (C::*m_testAsMethod)();
  806. public:
  807. TestInvokerAsMethod(void (C::*testAsMethod)()) noexcept : m_testAsMethod(testAsMethod)
  808. {}
  809. void invoke() const override
  810. {
  811. C obj;
  812. (obj.*m_testAsMethod)();
  813. }
  814. };
  815. auto makeTestInvoker(void(*testAsFunction)()) noexcept -> ITestInvoker *;
  816. template<typename C>
  817. auto makeTestInvoker(void (C::*testAsMethod)()) noexcept -> ITestInvoker *
  818. {
  819. return new(std::nothrow)
  820. TestInvokerAsMethod<C>( testAsMethod );
  821. }
  822. struct NameAndTags
  823. {
  824. NameAndTags(StringRef const &name_ = StringRef(), StringRef const &tags_ = StringRef()) noexcept;
  825. StringRef name;
  826. StringRef tags;
  827. };
  828. struct AutoReg : NonCopyable
  829. {
  830. AutoReg(ITestInvoker *invoker,
  831. SourceLineInfo const &lineInfo,
  832. StringRef const &classOrMethod,
  833. NameAndTags const &nameAndTags) noexcept;
  834. ~AutoReg();
  835. };
  836. } // end namespace Catch
  837. #if defined(CATCH_CONFIG_DISABLE)
  838. #define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( TestName, ... ) \
  839. static void TestName()
  840. #define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( TestName, ClassName, ... ) \
  841. namespace{ \
  842. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
  843. void test(); \
  844. }; \
  845. } \
  846. void TestName::test()
  847. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( TestName, TestFunc, Name, Tags, Signature, ... ) \
  848. INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature))
  849. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... ) \
  850. namespace{ \
  851. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
  852. INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
  853. } \
  854. } \
  855. INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))
  856. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  857. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \
  858. 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__ )
  859. #else
  860. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \
  861. 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__ ) )
  862. #endif
  863. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  864. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \
  865. 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__ )
  866. #else
  867. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \
  868. 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__ ) )
  869. #endif
  870. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  871. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \
  872. 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__ )
  873. #else
  874. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \
  875. 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__ ) )
  876. #endif
  877. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  878. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \
  879. 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__ )
  880. #else
  881. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \
  882. 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__ ) )
  883. #endif
  884. #endif
  885. ///////////////////////////////////////////////////////////////////////////////
  886. #define INTERNAL_CATCH_TESTCASE2(TestName, ...) \
  887. static void TestName(); \
  888. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  889. namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &TestName ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
  890. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  891. static void TestName()
  892. #define INTERNAL_CATCH_TESTCASE(...) \
  893. INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), __VA_ARGS__ )
  894. ///////////////////////////////////////////////////////////////////////////////
  895. #define INTERNAL_CATCH_METHOD_AS_TEST_CASE(QualifiedMethod, ...) \
  896. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  897. namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &QualifiedMethod ), CATCH_INTERNAL_LINEINFO, "&" #QualifiedMethod, Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
  898. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  899. ///////////////////////////////////////////////////////////////////////////////
  900. #define INTERNAL_CATCH_TEST_CASE_METHOD2(TestName, ClassName, ...)\
  901. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  902. namespace{ \
  903. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
  904. void test(); \
  905. }; \
  906. Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( Catch::makeTestInvoker( &TestName::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
  907. } \
  908. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  909. void TestName::test()
  910. #define INTERNAL_CATCH_TEST_CASE_METHOD(ClassName, ...) \
  911. INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, __VA_ARGS__ )
  912. ///////////////////////////////////////////////////////////////////////////////
  913. #define INTERNAL_CATCH_REGISTER_TESTCASE(Function, ...) \
  914. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  915. Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( Function ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
  916. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  917. ///////////////////////////////////////////////////////////////////////////////
  918. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_2(TestName, TestFunc, Name, Tags, Signature, ...)\
  919. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  920. CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
  921. INTERNAL_CATCH_DECLARE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
  922. namespace {\
  923. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\
  924. INTERNAL_CATCH_TYPE_GEN\
  925. INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
  926. INTERNAL_CATCH_NTTP_REG_GEN(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature))\
  927. template<typename...Types> \
  928. struct TestName{\
  929. TestName(){\
  930. int index = 0; \
  931. constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\
  932. using expander = int[];\
  933. (void)expander{(reg_test(Types{}, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++, 0)... };/* NOLINT */ \
  934. }\
  935. };\
  936. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
  937. TestName<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\
  938. return 0;\
  939. }();\
  940. }\
  941. }\
  942. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  943. CATCH_INTERNAL_UNSUPPRESS_ZERO_VARIADIC_WARNINGS \
  944. INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature))
  945. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  946. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
  947. 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__ )
  948. #else
  949. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
  950. 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__ ) )
  951. #endif
  952. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  953. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \
  954. 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__ )
  955. #else
  956. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \
  957. 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__ ) )
  958. #endif
  959. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(TestName, TestFuncName, Name, Tags, Signature, TmplTypes, TypesList) \
  960. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  961. CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
  962. template<typename TestType> static void TestFuncName(); \
  963. namespace {\
  964. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
  965. INTERNAL_CATCH_TYPE_GEN \
  966. INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature)) \
  967. template<typename... Types> \
  968. struct TestName { \
  969. void reg_tests() { \
  970. int index = 0; \
  971. using expander = int[]; \
  972. constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\
  973. constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\
  974. constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\
  975. (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 */\
  976. } \
  977. }; \
  978. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \
  979. using TestInit = decltype(create<TestName, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>(TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(INTERNAL_CATCH_REMOVE_PARENS(TypesList))>{})); \
  980. TestInit t; \
  981. t.reg_tests(); \
  982. return 0; \
  983. }(); \
  984. } \
  985. } \
  986. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  987. CATCH_INTERNAL_UNSUPPRESS_ZERO_VARIADIC_WARNINGS \
  988. template<typename TestType> \
  989. static void TestFuncName()
  990. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  991. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\
  992. 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__)
  993. #else
  994. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\
  995. 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__ ) )
  996. #endif
  997. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  998. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\
  999. 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__)
  1000. #else
  1001. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\
  1002. 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__ ) )
  1003. #endif
  1004. #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2(TestName, TestFunc, Name, Tags, TmplList)\
  1005. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  1006. template<typename TestType> static void TestFunc(); \
  1007. namespace {\
  1008. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\
  1009. INTERNAL_CATCH_TYPE_GEN\
  1010. template<typename... Types> \
  1011. struct TestName { \
  1012. void reg_tests() { \
  1013. int index = 0; \
  1014. using expander = int[]; \
  1015. (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 */\
  1016. } \
  1017. };\
  1018. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \
  1019. using TestInit = decltype(convert<TestName>(std::declval<TmplList>())); \
  1020. TestInit t; \
  1021. t.reg_tests(); \
  1022. return 0; \
  1023. }(); \
  1024. }}\
  1025. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  1026. template<typename TestType> \
  1027. static void TestFunc()
  1028. #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(Name, Tags, TmplList) \
  1029. 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 )
  1030. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2(TestNameClass, TestName, ClassName, Name, Tags, Signature, ...) \
  1031. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  1032. CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
  1033. namespace {\
  1034. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \
  1035. INTERNAL_CATCH_TYPE_GEN\
  1036. INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
  1037. INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
  1038. INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))\
  1039. template<typename...Types> \
  1040. struct TestNameClass{\
  1041. TestNameClass(){\
  1042. int index = 0; \
  1043. constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\
  1044. using expander = int[];\
  1045. (void)expander{(reg_test(Types{}, #ClassName, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++, 0)... };/* NOLINT */ \
  1046. }\
  1047. };\
  1048. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
  1049. TestNameClass<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\
  1050. return 0;\
  1051. }();\
  1052. }\
  1053. }\
  1054. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS\
  1055. CATCH_INTERNAL_UNSUPPRESS_ZERO_VARIADIC_WARNINGS\
  1056. INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))
  1057. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  1058. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD(ClassName, Name, Tags, ...) \
  1059. 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__ )
  1060. #else
  1061. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \
  1062. 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__ ) )
  1063. #endif
  1064. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  1065. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(ClassName, Name, Tags, Signature, ...) \
  1066. 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__ )
  1067. #else
  1068. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \
  1069. 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__ ) )
  1070. #endif
  1071. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2(TestNameClass, TestName, ClassName, Name, Tags, Signature, TmplTypes, TypesList)\
  1072. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  1073. CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
  1074. template<typename TestType> \
  1075. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \
  1076. void test();\
  1077. };\
  1078. namespace {\
  1079. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestNameClass) {\
  1080. INTERNAL_CATCH_TYPE_GEN \
  1081. INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
  1082. template<typename...Types>\
  1083. struct TestNameClass{\
  1084. void reg_tests(){\
  1085. int index = 0;\
  1086. using expander = int[];\
  1087. constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\
  1088. constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\
  1089. constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\
  1090. (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 */ \
  1091. }\
  1092. };\
  1093. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
  1094. using TestInit = decltype(create<TestNameClass, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>(TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(INTERNAL_CATCH_REMOVE_PARENS(TypesList))>{}));\
  1095. TestInit t;\
  1096. t.reg_tests();\
  1097. return 0;\
  1098. }(); \
  1099. }\
  1100. }\
  1101. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  1102. CATCH_INTERNAL_UNSUPPRESS_ZERO_VARIADIC_WARNINGS \
  1103. template<typename TestType> \
  1104. void TestName<TestType>::test()
  1105. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  1106. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(ClassName, Name, Tags, ...)\
  1107. 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__ )
  1108. #else
  1109. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\
  1110. 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__ ) )
  1111. #endif
  1112. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  1113. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(ClassName, Name, Tags, Signature, ...)\
  1114. 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__ )
  1115. #else
  1116. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\
  1117. 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__ ) )
  1118. #endif
  1119. #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2(TestNameClass, TestName, ClassName, Name, Tags, TmplList) \
  1120. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  1121. template<typename TestType> \
  1122. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \
  1123. void test();\
  1124. };\
  1125. namespace {\
  1126. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \
  1127. INTERNAL_CATCH_TYPE_GEN\
  1128. template<typename...Types>\
  1129. struct TestNameClass{\
  1130. void reg_tests(){\
  1131. int index = 0;\
  1132. using expander = int[];\
  1133. (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 */ \
  1134. }\
  1135. };\
  1136. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
  1137. using TestInit = decltype(convert<TestNameClass>(std::declval<TmplList>()));\
  1138. TestInit t;\
  1139. t.reg_tests();\
  1140. return 0;\
  1141. }(); \
  1142. }}\
  1143. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  1144. template<typename TestType> \
  1145. void TestName<TestType>::test()
  1146. #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD(ClassName, Name, Tags, TmplList) \
  1147. 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 )
  1148. // end catch_test_registry.h
  1149. // start catch_capture.hpp
  1150. // start catch_assertionhandler.h
  1151. // start catch_assertioninfo.h
  1152. // start catch_result_type.h
  1153. namespace Catch {
  1154. // ResultWas::OfType enum
  1155. struct ResultWas
  1156. {
  1157. enum OfType
  1158. {
  1159. Unknown = -1,
  1160. Ok = 0,
  1161. Info = 1,
  1162. Warning = 2,
  1163. FailureBit = 0x10,
  1164. ExpressionFailed = FailureBit | 1,
  1165. ExplicitFailure = FailureBit | 2,
  1166. Exception = 0x100 | FailureBit,
  1167. ThrewException = Exception | 1,
  1168. DidntThrowException = Exception | 2,
  1169. FatalErrorCondition = 0x200 | FailureBit
  1170. };
  1171. };
  1172. bool isOk(ResultWas::OfType resultType);
  1173. bool isJustInfo(int flags);
  1174. // ResultDisposition::Flags enum
  1175. struct ResultDisposition
  1176. {
  1177. enum Flags
  1178. {
  1179. Normal = 0x01,
  1180. ContinueOnFailure = 0x02, // Failures fail test, but execution continues
  1181. FalseTest = 0x04, // Prefix expression with !
  1182. SuppressFail = 0x08 // Failures are reported but do not fail the test
  1183. };
  1184. };
  1185. ResultDisposition::Flags operator|(ResultDisposition::Flags lhs, ResultDisposition::Flags rhs);
  1186. bool shouldContinueOnFailure(int flags);
  1187. inline bool isFalseTest(int flags)
  1188. { return (flags & ResultDisposition::FalseTest) != 0; }
  1189. bool shouldSuppressFailure(int flags);
  1190. } // end namespace Catch
  1191. // end catch_result_type.h
  1192. namespace Catch {
  1193. struct AssertionInfo
  1194. {
  1195. StringRef macroName;
  1196. SourceLineInfo lineInfo;
  1197. StringRef capturedExpression;
  1198. ResultDisposition::Flags resultDisposition;
  1199. // We want to delete this constructor but a compiler bug in 4.8 means
  1200. // the struct is then treated as non-aggregate
  1201. //AssertionInfo() = delete;
  1202. };
  1203. } // end namespace Catch
  1204. // end catch_assertioninfo.h
  1205. // start catch_decomposer.h
  1206. // start catch_tostring.h
  1207. #include <vector>
  1208. #include <cstddef>
  1209. #include <type_traits>
  1210. #include <string>
  1211. // start catch_stream.h
  1212. #include <iosfwd>
  1213. #include <cstddef>
  1214. #include <ostream>
  1215. namespace Catch {
  1216. std::ostream &cout();
  1217. std::ostream &cerr();
  1218. std::ostream &clog();
  1219. class StringRef;
  1220. struct IStream
  1221. {
  1222. virtual ~IStream();
  1223. virtual std::ostream &stream() const = 0;
  1224. };
  1225. auto makeStream(StringRef const &filename) -> IStream const *;
  1226. class ReusableStringStream
  1227. {
  1228. std::size_t m_index;
  1229. std::ostream *m_oss;
  1230. public:
  1231. ReusableStringStream();
  1232. ~ReusableStringStream();
  1233. auto str() const -> std::string;
  1234. template<typename T>
  1235. auto operator<<(T const &value) -> ReusableStringStream &
  1236. {
  1237. *m_oss << value;
  1238. return *this;
  1239. }
  1240. auto get() -> std::ostream &
  1241. { return *m_oss; }
  1242. };
  1243. }
  1244. // end catch_stream.h
  1245. // start catch_interfaces_enum_values_registry.h
  1246. #include <vector>
  1247. namespace Catch {
  1248. namespace Detail {
  1249. struct EnumInfo
  1250. {
  1251. StringRef m_name;
  1252. std::vector<std::pair<int, std::string>> m_values;
  1253. ~EnumInfo();
  1254. StringRef lookup(int value) const;
  1255. };
  1256. } // namespace Detail
  1257. struct IMutableEnumValuesRegistry
  1258. {
  1259. virtual ~IMutableEnumValuesRegistry();
  1260. virtual Detail::EnumInfo const &registerEnum(StringRef enumName,
  1261. StringRef allEnums,
  1262. std::vector<int> const &values) = 0;
  1263. template<typename E>
  1264. Detail::EnumInfo const &registerEnum(StringRef enumName,
  1265. StringRef allEnums,
  1266. std::initializer_list<E> values)
  1267. {
  1268. std::vector<int> intValues;
  1269. intValues.reserve(values.size());
  1270. for (auto enumValue : values)
  1271. intValues.push_back(static_cast<int>( enumValue ));
  1272. return registerEnum(enumName, allEnums, intValues);
  1273. }
  1274. };
  1275. } // Catch
  1276. // end catch_interfaces_enum_values_registry.h
  1277. #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  1278. #include <string_view>
  1279. #endif
  1280. #ifdef __OBJC__
  1281. // start catch_objc_arc.hpp
  1282. #import <Foundation/Foundation.h>
  1283. #ifdef __has_feature
  1284. #define CATCH_ARC_ENABLED __has_feature(objc_arc)
  1285. #else
  1286. #define CATCH_ARC_ENABLED 0
  1287. #endif
  1288. void arcSafeRelease( NSObject* obj );
  1289. id performOptionalSelector( id obj, SEL sel );
  1290. #if !CATCH_ARC_ENABLED
  1291. inline void arcSafeRelease( NSObject* obj ) {
  1292. [obj release];
  1293. }
  1294. inline id performOptionalSelector( id obj, SEL sel ) {
  1295. if( [obj respondsToSelector: sel] )
  1296. return [obj performSelector: sel];
  1297. return nil;
  1298. }
  1299. #define CATCH_UNSAFE_UNRETAINED
  1300. #define CATCH_ARC_STRONG
  1301. #else
  1302. inline void arcSafeRelease( NSObject* ){}
  1303. inline id performOptionalSelector( id obj, SEL sel ) {
  1304. #ifdef __clang__
  1305. #pragma clang diagnostic push
  1306. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  1307. #endif
  1308. if( [obj respondsToSelector: sel] )
  1309. return [obj performSelector: sel];
  1310. #ifdef __clang__
  1311. #pragma clang diagnostic pop
  1312. #endif
  1313. return nil;
  1314. }
  1315. #define CATCH_UNSAFE_UNRETAINED __unsafe_unretained
  1316. #define CATCH_ARC_STRONG __strong
  1317. #endif
  1318. // end catch_objc_arc.hpp
  1319. #endif
  1320. #ifdef _MSC_VER
  1321. #pragma warning(push)
  1322. #pragma warning(disable:4180) // We attempt to stream a function (address) by const&, which MSVC complains about but is harmless
  1323. #endif
  1324. namespace Catch {
  1325. namespace Detail {
  1326. extern const std::string unprintableString;
  1327. std::string rawMemoryToString(const void *object, std::size_t size);
  1328. template<typename T>
  1329. std::string rawMemoryToString(const T &object)
  1330. {
  1331. return rawMemoryToString(&object, sizeof(object));
  1332. }
  1333. template<typename T>
  1334. class IsStreamInsertable
  1335. {
  1336. template<typename SS, typename TT>
  1337. static auto test(int)
  1338. -> decltype(std::declval<SS &>() << std::declval<TT>(), std::true_type());
  1339. template<typename, typename>
  1340. static auto test(...) -> std::false_type;
  1341. public:
  1342. static const bool value = decltype(test<std::ostream, const T &>(0))::value;
  1343. };
  1344. template<typename E>
  1345. std::string convertUnknownEnumToString(E e);
  1346. template<typename T>
  1347. typename std::enable_if<
  1348. !std::is_enum<T>::value && !std::is_base_of<std::exception, T>::value,
  1349. std::string>::type convertUnstreamable(T const &)
  1350. {
  1351. return Detail::unprintableString;
  1352. }
  1353. template<typename T>
  1354. typename std::enable_if<
  1355. !std::is_enum<T>::value && std::is_base_of<std::exception, T>::value,
  1356. std::string>::type convertUnstreamable(T const &ex)
  1357. {
  1358. return ex.what();
  1359. }
  1360. template<typename T>
  1361. typename std::enable_if<
  1362. std::is_enum<T>::value, std::string>::type convertUnstreamable(T const &value)
  1363. {
  1364. return convertUnknownEnumToString(value);
  1365. }
  1366. #if defined(_MANAGED)
  1367. //! Convert a CLR string to a utf8 std::string
  1368. template<typename T>
  1369. std::string clrReferenceToString( T^ ref ) {
  1370. if (ref == nullptr)
  1371. return std::string("null");
  1372. auto bytes = System::Text::Encoding::UTF8->GetBytes(ref->ToString());
  1373. cli::pin_ptr<System::Byte> p = &bytes[0];
  1374. return std::string(reinterpret_cast<char const *>(p), bytes->Length);
  1375. }
  1376. #endif
  1377. } // namespace Detail
  1378. // If we decide for C++14, change these to enable_if_ts
  1379. template<typename T, typename = void>
  1380. struct StringMaker
  1381. {
  1382. template<typename Fake = T>
  1383. static
  1384. typename std::enable_if<::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
  1385. convert(const Fake &value)
  1386. {
  1387. ReusableStringStream rss;
  1388. // NB: call using the function-like syntax to avoid ambiguity with
  1389. // user-defined templated operator<< under clang.
  1390. rss.operator<<(value);
  1391. return rss.str();
  1392. }
  1393. template<typename Fake = T>
  1394. static
  1395. typename std::enable_if<!::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
  1396. convert(const Fake &value)
  1397. {
  1398. #if !defined(CATCH_CONFIG_FALLBACK_STRINGIFIER)
  1399. return Detail::convertUnstreamable(value);
  1400. #else
  1401. return CATCH_CONFIG_FALLBACK_STRINGIFIER(value);
  1402. #endif
  1403. }
  1404. };
  1405. namespace Detail {
  1406. // This function dispatches all stringification requests inside of Catch.
  1407. // Should be preferably called fully qualified, like ::Catch::Detail::stringify
  1408. template<typename T>
  1409. std::string stringify(const T &e)
  1410. {
  1411. return ::Catch::StringMaker<typename std::remove_cv<typename std::remove_reference<T>::type>::type>::convert(
  1412. e);
  1413. }
  1414. template<typename E>
  1415. std::string convertUnknownEnumToString(E e)
  1416. {
  1417. return ::Catch::Detail::stringify(static_cast<typename std::underlying_type<E>::type>(e));
  1418. }
  1419. #if defined(_MANAGED)
  1420. template <typename T>
  1421. std::string stringify( T^ e ) {
  1422. return ::Catch::StringMaker<T^>::convert(e);
  1423. }
  1424. #endif
  1425. } // namespace Detail
  1426. // Some predefined specializations
  1427. template<>
  1428. struct StringMaker<std::string>
  1429. {
  1430. static std::string convert(const std::string &str);
  1431. };
  1432. #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  1433. template<>
  1434. struct StringMaker<std::string_view> {
  1435. static std::string convert(std::string_view str);
  1436. };
  1437. #endif
  1438. template<>
  1439. struct StringMaker<char const *>
  1440. {
  1441. static std::string convert(char const *str);
  1442. };
  1443. template<>
  1444. struct StringMaker<char *>
  1445. {
  1446. static std::string convert(char *str);
  1447. };
  1448. #ifdef CATCH_CONFIG_WCHAR
  1449. template<>
  1450. struct StringMaker<std::wstring>
  1451. {
  1452. static std::string convert(const std::wstring &wstr);
  1453. };
  1454. # ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  1455. template<>
  1456. struct StringMaker<std::wstring_view> {
  1457. static std::string convert(std::wstring_view str);
  1458. };
  1459. # endif
  1460. template<>
  1461. struct StringMaker<wchar_t const *>
  1462. {
  1463. static std::string convert(wchar_t const *str);
  1464. };
  1465. template<>
  1466. struct StringMaker<wchar_t *>
  1467. {
  1468. static std::string convert(wchar_t *str);
  1469. };
  1470. #endif
  1471. // TBD: Should we use `strnlen` to ensure that we don't go out of the buffer,
  1472. // while keeping string semantics?
  1473. template<int SZ>
  1474. struct StringMaker<char[SZ]>
  1475. {
  1476. static std::string convert(char const *str)
  1477. {
  1478. return ::Catch::Detail::stringify(std::string{str});
  1479. }
  1480. };
  1481. template<int SZ>
  1482. struct StringMaker<signed char[SZ]>
  1483. {
  1484. static std::string convert(signed char const *str)
  1485. {
  1486. return ::Catch::Detail::stringify(std::string{reinterpret_cast<char const *>(str)});
  1487. }
  1488. };
  1489. template<int SZ>
  1490. struct StringMaker<unsigned char[SZ]>
  1491. {
  1492. static std::string convert(unsigned char const *str)
  1493. {
  1494. return ::Catch::Detail::stringify(std::string{reinterpret_cast<char const *>(str)});
  1495. }
  1496. };
  1497. #if defined(CATCH_CONFIG_CPP17_BYTE)
  1498. template<>
  1499. struct StringMaker<std::byte> {
  1500. static std::string convert(std::byte value);
  1501. };
  1502. #endif // defined(CATCH_CONFIG_CPP17_BYTE)
  1503. template<>
  1504. struct StringMaker<int>
  1505. {
  1506. static std::string convert(int value);
  1507. };
  1508. template<>
  1509. struct StringMaker<long>
  1510. {
  1511. static std::string convert(long value);
  1512. };
  1513. template<>
  1514. struct StringMaker<long long>
  1515. {
  1516. static std::string convert(long long value);
  1517. };
  1518. template<>
  1519. struct StringMaker<unsigned int>
  1520. {
  1521. static std::string convert(unsigned int value);
  1522. };
  1523. template<>
  1524. struct StringMaker<unsigned long>
  1525. {
  1526. static std::string convert(unsigned long value);
  1527. };
  1528. template<>
  1529. struct StringMaker<unsigned long long>
  1530. {
  1531. static std::string convert(unsigned long long value);
  1532. };
  1533. template<>
  1534. struct StringMaker<bool>
  1535. {
  1536. static std::string convert(bool b);
  1537. };
  1538. template<>
  1539. struct StringMaker<char>
  1540. {
  1541. static std::string convert(char c);
  1542. };
  1543. template<>
  1544. struct StringMaker<signed char>
  1545. {
  1546. static std::string convert(signed char c);
  1547. };
  1548. template<>
  1549. struct StringMaker<unsigned char>
  1550. {
  1551. static std::string convert(unsigned char c);
  1552. };
  1553. template<>
  1554. struct StringMaker<std::nullptr_t>
  1555. {
  1556. static std::string convert(std::nullptr_t);
  1557. };
  1558. template<>
  1559. struct StringMaker<float>
  1560. {
  1561. static std::string convert(float value);
  1562. static int precision;
  1563. };
  1564. template<>
  1565. struct StringMaker<double>
  1566. {
  1567. static std::string convert(double value);
  1568. static int precision;
  1569. };
  1570. template<typename T>
  1571. struct StringMaker<T *>
  1572. {
  1573. template<typename U>
  1574. static std::string convert(U *p)
  1575. {
  1576. if (p) {
  1577. return ::Catch::Detail::rawMemoryToString(p);
  1578. } else {
  1579. return "nullptr";
  1580. }
  1581. }
  1582. };
  1583. template<typename R, typename C>
  1584. struct StringMaker<R C::*>
  1585. {
  1586. static std::string convert(R C::* p)
  1587. {
  1588. if (p) {
  1589. return ::Catch::Detail::rawMemoryToString(p);
  1590. } else {
  1591. return "nullptr";
  1592. }
  1593. }
  1594. };
  1595. #if defined(_MANAGED)
  1596. template <typename T>
  1597. struct StringMaker<T^> {
  1598. static std::string convert( T^ ref ) {
  1599. return ::Catch::Detail::clrReferenceToString(ref);
  1600. }
  1601. };
  1602. #endif
  1603. namespace Detail {
  1604. template<typename InputIterator>
  1605. std::string rangeToString(InputIterator first, InputIterator last)
  1606. {
  1607. ReusableStringStream rss;
  1608. rss << "{ ";
  1609. if (first != last) {
  1610. rss << ::Catch::Detail::stringify(*first);
  1611. for (++first; first != last; ++first)
  1612. rss << ", " << ::Catch::Detail::stringify(*first);
  1613. }
  1614. rss << " }";
  1615. return rss.str();
  1616. }
  1617. }
  1618. #ifdef __OBJC__
  1619. template<>
  1620. struct StringMaker<NSString*> {
  1621. static std::string convert(NSString * nsstring) {
  1622. if (!nsstring)
  1623. return "nil";
  1624. return std::string("@") + [nsstring UTF8String];
  1625. }
  1626. };
  1627. template<>
  1628. struct StringMaker<NSObject*> {
  1629. static std::string convert(NSObject* nsObject) {
  1630. return ::Catch::Detail::stringify([nsObject description]);
  1631. }
  1632. };
  1633. namespace Detail {
  1634. inline std::string stringify( NSString* nsstring ) {
  1635. return StringMaker<NSString*>::convert( nsstring );
  1636. }
  1637. } // namespace Detail
  1638. #endif // __OBJC__
  1639. } // namespace Catch
  1640. //////////////////////////////////////////////////////
  1641. // Separate std-lib types stringification, so it can be selectively enabled
  1642. // This means that we do not bring in
  1643. #if defined(CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS)
  1644. # define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
  1645. # define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
  1646. # define CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
  1647. # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  1648. # define CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
  1649. #endif
  1650. // Separate std::pair specialization
  1651. #if defined(CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER)
  1652. #include <utility>
  1653. namespace Catch {
  1654. template<typename T1, typename T2>
  1655. struct StringMaker<std::pair<T1, T2> > {
  1656. static std::string convert(const std::pair<T1, T2>& pair) {
  1657. ReusableStringStream rss;
  1658. rss << "{ "
  1659. << ::Catch::Detail::stringify(pair.first)
  1660. << ", "
  1661. << ::Catch::Detail::stringify(pair.second)
  1662. << " }";
  1663. return rss.str();
  1664. }
  1665. };
  1666. }
  1667. #endif // CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
  1668. #if defined(CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_OPTIONAL)
  1669. #include <optional>
  1670. namespace Catch {
  1671. template<typename T>
  1672. struct StringMaker<std::optional<T> > {
  1673. static std::string convert(const std::optional<T>& optional) {
  1674. ReusableStringStream rss;
  1675. if (optional.has_value()) {
  1676. rss << ::Catch::Detail::stringify(*optional);
  1677. } else {
  1678. rss << "{ }";
  1679. }
  1680. return rss.str();
  1681. }
  1682. };
  1683. }
  1684. #endif // CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
  1685. // Separate std::tuple specialization
  1686. #if defined(CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER)
  1687. #include <tuple>
  1688. namespace Catch {
  1689. namespace Detail {
  1690. template<
  1691. typename Tuple,
  1692. std::size_t N = 0,
  1693. bool = (N < std::tuple_size<Tuple>::value)
  1694. >
  1695. struct TupleElementPrinter {
  1696. static void print(const Tuple& tuple, std::ostream& os) {
  1697. os << (N ? ", " : " ")
  1698. << ::Catch::Detail::stringify(std::get<N>(tuple));
  1699. TupleElementPrinter<Tuple, N + 1>::print(tuple, os);
  1700. }
  1701. };
  1702. template<
  1703. typename Tuple,
  1704. std::size_t N
  1705. >
  1706. struct TupleElementPrinter<Tuple, N, false> {
  1707. static void print(const Tuple&, std::ostream&) {}
  1708. };
  1709. }
  1710. template<typename ...Types>
  1711. struct StringMaker<std::tuple<Types...>> {
  1712. static std::string convert(const std::tuple<Types...>& tuple) {
  1713. ReusableStringStream rss;
  1714. rss << '{';
  1715. Detail::TupleElementPrinter<std::tuple<Types...>>::print(tuple, rss.get());
  1716. rss << " }";
  1717. return rss.str();
  1718. }
  1719. };
  1720. }
  1721. #endif // CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
  1722. #if defined(CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_VARIANT)
  1723. #include <variant>
  1724. namespace Catch {
  1725. template<>
  1726. struct StringMaker<std::monostate> {
  1727. static std::string convert(const std::monostate&) {
  1728. return "{ }";
  1729. }
  1730. };
  1731. template<typename... Elements>
  1732. struct StringMaker<std::variant<Elements...>> {
  1733. static std::string convert(const std::variant<Elements...>& variant) {
  1734. if (variant.valueless_by_exception()) {
  1735. return "{valueless variant}";
  1736. } else {
  1737. return std::visit(
  1738. [](const auto& value) {
  1739. return ::Catch::Detail::stringify(value);
  1740. },
  1741. variant
  1742. );
  1743. }
  1744. }
  1745. };
  1746. }
  1747. #endif // CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
  1748. namespace Catch {
  1749. struct not_this_one
  1750. {
  1751. }; // Tag type for detecting which begin/ end are being selected
  1752. // Import begin/ end from std here so they are considered alongside the fallback (...) overloads in this namespace
  1753. using std::begin;
  1754. using std::end;
  1755. not_this_one begin(...);
  1756. not_this_one end(...);
  1757. template<typename T>
  1758. struct is_range
  1759. {
  1760. static const bool value =
  1761. !std::is_same<decltype(begin(std::declval<T>())), not_this_one>::value &&
  1762. !std::is_same<decltype(end(std::declval<T>())), not_this_one>::value;
  1763. };
  1764. #if defined(_MANAGED) // Managed types are never ranges
  1765. template <typename T>
  1766. struct is_range<T^> {
  1767. static const bool value = false;
  1768. };
  1769. #endif
  1770. template<typename Range>
  1771. std::string rangeToString(Range const &range)
  1772. {
  1773. return ::Catch::Detail::rangeToString(begin(range), end(range));
  1774. }
  1775. // Handle vector<bool> specially
  1776. template<typename Allocator>
  1777. std::string rangeToString(std::vector<bool, Allocator> const &v)
  1778. {
  1779. ReusableStringStream rss;
  1780. rss << "{ ";
  1781. bool first = true;
  1782. for (bool b : v) {
  1783. if (first)
  1784. first = false;
  1785. else
  1786. rss << ", ";
  1787. rss << ::Catch::Detail::stringify(b);
  1788. }
  1789. rss << " }";
  1790. return rss.str();
  1791. }
  1792. template<typename R>
  1793. struct StringMaker<R,
  1794. typename std::enable_if<is_range<R>::value
  1795. && !::Catch::Detail::IsStreamInsertable<R>::value>::type>
  1796. {
  1797. static std::string convert(R const &range)
  1798. {
  1799. return rangeToString(range);
  1800. }
  1801. };
  1802. template<typename T, int SZ>
  1803. struct StringMaker<T[SZ]>
  1804. {
  1805. static std::string convert(T const(&arr)[SZ])
  1806. {
  1807. return rangeToString(arr);
  1808. }
  1809. };
  1810. } // namespace Catch
  1811. // Separate std::chrono::duration specialization
  1812. #if defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  1813. #include <ctime>
  1814. #include <ratio>
  1815. #include <chrono>
  1816. namespace Catch {
  1817. template <class Ratio>
  1818. struct ratio_string {
  1819. static std::string symbol();
  1820. };
  1821. template <class Ratio>
  1822. std::string ratio_string<Ratio>::symbol() {
  1823. Catch::ReusableStringStream rss;
  1824. rss << '[' << Ratio::num << '/'
  1825. << Ratio::den << ']';
  1826. return rss.str();
  1827. }
  1828. template <>
  1829. struct ratio_string<std::atto> {
  1830. static std::string symbol();
  1831. };
  1832. template <>
  1833. struct ratio_string<std::femto> {
  1834. static std::string symbol();
  1835. };
  1836. template <>
  1837. struct ratio_string<std::pico> {
  1838. static std::string symbol();
  1839. };
  1840. template <>
  1841. struct ratio_string<std::nano> {
  1842. static std::string symbol();
  1843. };
  1844. template <>
  1845. struct ratio_string<std::micro> {
  1846. static std::string symbol();
  1847. };
  1848. template <>
  1849. struct ratio_string<std::milli> {
  1850. static std::string symbol();
  1851. };
  1852. ////////////
  1853. // std::chrono::duration specializations
  1854. template<typename Value, typename Ratio>
  1855. struct StringMaker<std::chrono::duration<Value, Ratio>> {
  1856. static std::string convert(std::chrono::duration<Value, Ratio> const& duration) {
  1857. ReusableStringStream rss;
  1858. rss << duration.count() << ' ' << ratio_string<Ratio>::symbol() << 's';
  1859. return rss.str();
  1860. }
  1861. };
  1862. template<typename Value>
  1863. struct StringMaker<std::chrono::duration<Value, std::ratio<1>>> {
  1864. static std::string convert(std::chrono::duration<Value, std::ratio<1>> const& duration) {
  1865. ReusableStringStream rss;
  1866. rss << duration.count() << " s";
  1867. return rss.str();
  1868. }
  1869. };
  1870. template<typename Value>
  1871. struct StringMaker<std::chrono::duration<Value, std::ratio<60>>> {
  1872. static std::string convert(std::chrono::duration<Value, std::ratio<60>> const& duration) {
  1873. ReusableStringStream rss;
  1874. rss << duration.count() << " m";
  1875. return rss.str();
  1876. }
  1877. };
  1878. template<typename Value>
  1879. struct StringMaker<std::chrono::duration<Value, std::ratio<3600>>> {
  1880. static std::string convert(std::chrono::duration<Value, std::ratio<3600>> const& duration) {
  1881. ReusableStringStream rss;
  1882. rss << duration.count() << " h";
  1883. return rss.str();
  1884. }
  1885. };
  1886. ////////////
  1887. // std::chrono::time_point specialization
  1888. // Generic time_point cannot be specialized, only std::chrono::time_point<system_clock>
  1889. template<typename Clock, typename Duration>
  1890. struct StringMaker<std::chrono::time_point<Clock, Duration>> {
  1891. static std::string convert(std::chrono::time_point<Clock, Duration> const& time_point) {
  1892. return ::Catch::Detail::stringify(time_point.time_since_epoch()) + " since epoch";
  1893. }
  1894. };
  1895. // std::chrono::time_point<system_clock> specialization
  1896. template<typename Duration>
  1897. struct StringMaker<std::chrono::time_point<std::chrono::system_clock, Duration>> {
  1898. static std::string convert(std::chrono::time_point<std::chrono::system_clock, Duration> const& time_point) {
  1899. auto converted = std::chrono::system_clock::to_time_t(time_point);
  1900. #ifdef _MSC_VER
  1901. std::tm timeInfo = {};
  1902. gmtime_s(&timeInfo, &converted);
  1903. #else
  1904. std::tm* timeInfo = std::gmtime(&converted);
  1905. #endif
  1906. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  1907. char timeStamp[timeStampSize];
  1908. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  1909. #ifdef _MSC_VER
  1910. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  1911. #else
  1912. std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
  1913. #endif
  1914. return std::string(timeStamp);
  1915. }
  1916. };
  1917. }
  1918. #endif // CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  1919. #define INTERNAL_CATCH_REGISTER_ENUM(enumName, ...) \
  1920. namespace Catch { \
  1921. template<> struct StringMaker<enumName> { \
  1922. static std::string convert( enumName value ) { \
  1923. static const auto& enumInfo = ::Catch::getMutableRegistryHub().getMutableEnumValuesRegistry().registerEnum( #enumName, #__VA_ARGS__, { __VA_ARGS__ } ); \
  1924. return enumInfo.lookup( static_cast<int>( value ) ); \
  1925. } \
  1926. }; \
  1927. }
  1928. #define CATCH_REGISTER_ENUM(enumName, ...) INTERNAL_CATCH_REGISTER_ENUM( enumName, __VA_ARGS__ )
  1929. #ifdef _MSC_VER
  1930. #pragma warning(pop)
  1931. #endif
  1932. // end catch_tostring.h
  1933. #include <iosfwd>
  1934. #ifdef _MSC_VER
  1935. #pragma warning(push)
  1936. #pragma warning(disable:4389) // '==' : signed/unsigned mismatch
  1937. #pragma warning(disable:4018) // more "signed/unsigned mismatch"
  1938. #pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform)
  1939. #pragma warning(disable:4180) // qualifier applied to function type has no meaning
  1940. #pragma warning(disable:4800) // Forcing result to true or false
  1941. #endif
  1942. namespace Catch {
  1943. struct ITransientExpression
  1944. {
  1945. auto isBinaryExpression() const -> bool
  1946. { return m_isBinaryExpression; }
  1947. auto getResult() const -> bool
  1948. { return m_result; }
  1949. virtual void streamReconstructedExpression(std::ostream &os) const = 0;
  1950. ITransientExpression(bool isBinaryExpression, bool result)
  1951. : m_isBinaryExpression(isBinaryExpression),
  1952. m_result(result)
  1953. {}
  1954. // We don't actually need a virtual destructor, but many static analysers
  1955. // complain if it's not here :-(
  1956. virtual ~ITransientExpression();
  1957. bool m_isBinaryExpression;
  1958. bool m_result;
  1959. };
  1960. void formatReconstructedExpression(std::ostream &os,
  1961. std::string const &lhs,
  1962. StringRef op,
  1963. std::string const &rhs);
  1964. template<typename LhsT, typename RhsT>
  1965. class BinaryExpr : public ITransientExpression
  1966. {
  1967. LhsT m_lhs;
  1968. StringRef m_op;
  1969. RhsT m_rhs;
  1970. void streamReconstructedExpression(std::ostream &os) const override
  1971. {
  1972. formatReconstructedExpression
  1973. (os, Catch::Detail::stringify(m_lhs), m_op, Catch::Detail::stringify(m_rhs));
  1974. }
  1975. public:
  1976. BinaryExpr(bool comparisonResult, LhsT lhs, StringRef op, RhsT rhs)
  1977. : ITransientExpression{true, comparisonResult},
  1978. m_lhs(lhs),
  1979. m_op(op),
  1980. m_rhs(rhs)
  1981. {}
  1982. template<typename T>
  1983. auto operator&&(T) const -> BinaryExpr<LhsT, RhsT const &> const
  1984. {
  1985. static_assert(always_false<T>::value,
  1986. "chained comparisons are not supported inside assertions, "
  1987. "wrap the expression inside parentheses, or decompose it");
  1988. }
  1989. template<typename T>
  1990. auto operator||(T) const -> BinaryExpr<LhsT, RhsT const &> const
  1991. {
  1992. static_assert(always_false<T>::value,
  1993. "chained comparisons are not supported inside assertions, "
  1994. "wrap the expression inside parentheses, or decompose it");
  1995. }
  1996. template<typename T>
  1997. auto operator==(T) const -> BinaryExpr<LhsT, RhsT const &> const
  1998. {
  1999. static_assert(always_false<T>::value,
  2000. "chained comparisons are not supported inside assertions, "
  2001. "wrap the expression inside parentheses, or decompose it");
  2002. }
  2003. template<typename T>
  2004. auto operator!=(T) const -> BinaryExpr<LhsT, RhsT const &> const
  2005. {
  2006. static_assert(always_false<T>::value,
  2007. "chained comparisons are not supported inside assertions, "
  2008. "wrap the expression inside parentheses, or decompose it");
  2009. }
  2010. template<typename T>
  2011. auto operator>(T) const -> BinaryExpr<LhsT, RhsT const &> const
  2012. {
  2013. static_assert(always_false<T>::value,
  2014. "chained comparisons are not supported inside assertions, "
  2015. "wrap the expression inside parentheses, or decompose it");
  2016. }
  2017. template<typename T>
  2018. auto operator<(T) const -> BinaryExpr<LhsT, RhsT const &> const
  2019. {
  2020. static_assert(always_false<T>::value,
  2021. "chained comparisons are not supported inside assertions, "
  2022. "wrap the expression inside parentheses, or decompose it");
  2023. }
  2024. template<typename T>
  2025. auto operator>=(T) const -> BinaryExpr<LhsT, RhsT const &> const
  2026. {
  2027. static_assert(always_false<T>::value,
  2028. "chained comparisons are not supported inside assertions, "
  2029. "wrap the expression inside parentheses, or decompose it");
  2030. }
  2031. template<typename T>
  2032. auto operator<=(T) const -> BinaryExpr<LhsT, RhsT const &> const
  2033. {
  2034. static_assert(always_false<T>::value,
  2035. "chained comparisons are not supported inside assertions, "
  2036. "wrap the expression inside parentheses, or decompose it");
  2037. }
  2038. };
  2039. template<typename LhsT>
  2040. class UnaryExpr : public ITransientExpression
  2041. {
  2042. LhsT m_lhs;
  2043. void streamReconstructedExpression(std::ostream &os) const override
  2044. {
  2045. os << Catch::Detail::stringify(m_lhs);
  2046. }
  2047. public:
  2048. explicit UnaryExpr(LhsT lhs)
  2049. : ITransientExpression{false, static_cast<bool>(lhs)},
  2050. m_lhs(lhs)
  2051. {}
  2052. };
  2053. // Specialised comparison functions to handle equality comparisons between ints and pointers (NULL deduces as an int)
  2054. template<typename LhsT, typename RhsT>
  2055. auto compareEqual(LhsT const &lhs, RhsT const &rhs) -> bool
  2056. {
  2057. return static_cast<bool>(lhs == rhs);
  2058. }
  2059. template<typename T>
  2060. auto compareEqual(T *const &lhs, int rhs) -> bool
  2061. {
  2062. return lhs == reinterpret_cast<void const *>( rhs );
  2063. }
  2064. template<typename T>
  2065. auto compareEqual(T *const &lhs, long rhs) -> bool
  2066. {
  2067. return lhs == reinterpret_cast<void const *>( rhs );
  2068. }
  2069. template<typename T>
  2070. auto compareEqual(int lhs, T *const &rhs) -> bool
  2071. {
  2072. return reinterpret_cast<void const *>( lhs ) == rhs;
  2073. }
  2074. template<typename T>
  2075. auto compareEqual(long lhs, T *const &rhs) -> bool
  2076. {
  2077. return reinterpret_cast<void const *>( lhs ) == rhs;
  2078. }
  2079. template<typename LhsT, typename RhsT>
  2080. auto compareNotEqual(LhsT const &lhs, RhsT &&rhs) -> bool
  2081. { return static_cast<bool>(lhs != rhs); }
  2082. template<typename T>
  2083. auto compareNotEqual(T *const &lhs, int rhs) -> bool
  2084. {
  2085. return lhs != reinterpret_cast<void const *>( rhs );
  2086. }
  2087. template<typename T>
  2088. auto compareNotEqual(T *const &lhs, long rhs) -> bool
  2089. {
  2090. return lhs != reinterpret_cast<void const *>( rhs );
  2091. }
  2092. template<typename T>
  2093. auto compareNotEqual(int lhs, T *const &rhs) -> bool
  2094. {
  2095. return reinterpret_cast<void const *>( lhs ) != rhs;
  2096. }
  2097. template<typename T>
  2098. auto compareNotEqual(long lhs, T *const &rhs) -> bool
  2099. {
  2100. return reinterpret_cast<void const *>( lhs ) != rhs;
  2101. }
  2102. template<typename LhsT>
  2103. class ExprLhs
  2104. {
  2105. LhsT m_lhs;
  2106. public:
  2107. explicit ExprLhs(LhsT lhs) : m_lhs(lhs)
  2108. {}
  2109. template<typename RhsT>
  2110. auto operator==(RhsT const &rhs) -> BinaryExpr<LhsT, RhsT const &> const
  2111. {
  2112. return {compareEqual(m_lhs, rhs), m_lhs, "==", rhs};
  2113. }
  2114. auto operator==(bool rhs) -> BinaryExpr<LhsT, bool> const
  2115. {
  2116. return {m_lhs == rhs, m_lhs, "==", rhs};
  2117. }
  2118. template<typename RhsT>
  2119. auto operator!=(RhsT const &rhs) -> BinaryExpr<LhsT, RhsT const &> const
  2120. {
  2121. return {compareNotEqual(m_lhs, rhs), m_lhs, "!=", rhs};
  2122. }
  2123. auto operator!=(bool rhs) -> BinaryExpr<LhsT, bool> const
  2124. {
  2125. return {m_lhs != rhs, m_lhs, "!=", rhs};
  2126. }
  2127. template<typename RhsT>
  2128. auto operator>(RhsT const &rhs) -> BinaryExpr<LhsT, RhsT const &> const
  2129. {
  2130. return {static_cast<bool>(m_lhs > rhs), m_lhs, ">", rhs};
  2131. }
  2132. template<typename RhsT>
  2133. auto operator<(RhsT const &rhs) -> BinaryExpr<LhsT, RhsT const &> const
  2134. {
  2135. return {static_cast<bool>(m_lhs < rhs), m_lhs, "<", rhs};
  2136. }
  2137. template<typename RhsT>
  2138. auto operator>=(RhsT const &rhs) -> BinaryExpr<LhsT, RhsT const &> const
  2139. {
  2140. return {static_cast<bool>(m_lhs >= rhs), m_lhs, ">=", rhs};
  2141. }
  2142. template<typename RhsT>
  2143. auto operator<=(RhsT const &rhs) -> BinaryExpr<LhsT, RhsT const &> const
  2144. {
  2145. return {static_cast<bool>(m_lhs <= rhs), m_lhs, "<=", rhs};
  2146. }
  2147. template<typename RhsT>
  2148. auto operator&&(RhsT const &) -> BinaryExpr<LhsT, RhsT const &> const
  2149. {
  2150. static_assert(always_false<RhsT>::value,
  2151. "operator&& is not supported inside assertions, "
  2152. "wrap the expression inside parentheses, or decompose it");
  2153. }
  2154. template<typename RhsT>
  2155. auto operator||(RhsT const &) -> BinaryExpr<LhsT, RhsT const &> const
  2156. {
  2157. static_assert(always_false<RhsT>::value,
  2158. "operator|| is not supported inside assertions, "
  2159. "wrap the expression inside parentheses, or decompose it");
  2160. }
  2161. auto makeUnaryExpr() const -> UnaryExpr<LhsT>
  2162. {
  2163. return UnaryExpr<LhsT>{m_lhs};
  2164. }
  2165. };
  2166. void handleExpression(ITransientExpression const &expr);
  2167. template<typename T>
  2168. void handleExpression(ExprLhs<T> const &expr)
  2169. {
  2170. handleExpression(expr.makeUnaryExpr());
  2171. }
  2172. struct Decomposer
  2173. {
  2174. template<typename T>
  2175. auto operator<=(T const &lhs) -> ExprLhs<T const &>
  2176. {
  2177. return ExprLhs<T const &>{lhs};
  2178. }
  2179. auto operator<=(bool value) -> ExprLhs<bool>
  2180. {
  2181. return ExprLhs<bool>{value};
  2182. }
  2183. };
  2184. } // end namespace Catch
  2185. #ifdef _MSC_VER
  2186. #pragma warning(pop)
  2187. #endif
  2188. // end catch_decomposer.h
  2189. // start catch_interfaces_capture.h
  2190. #include <string>
  2191. #include <chrono>
  2192. namespace Catch {
  2193. class AssertionResult;
  2194. struct AssertionInfo;
  2195. struct SectionInfo;
  2196. struct SectionEndInfo;
  2197. struct MessageInfo;
  2198. struct MessageBuilder;
  2199. struct Counts;
  2200. struct AssertionReaction;
  2201. struct SourceLineInfo;
  2202. struct ITransientExpression;
  2203. struct IGeneratorTracker;
  2204. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  2205. struct BenchmarkInfo;
  2206. template <typename Duration = std::chrono::duration<double, std::nano>>
  2207. struct BenchmarkStats;
  2208. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  2209. struct IResultCapture
  2210. {
  2211. virtual ~IResultCapture();
  2212. virtual bool sectionStarted(SectionInfo const &sectionInfo,
  2213. Counts &assertions) = 0;
  2214. virtual void sectionEnded(SectionEndInfo const &endInfo) = 0;
  2215. virtual void sectionEndedEarly(SectionEndInfo const &endInfo) = 0;
  2216. virtual auto acquireGeneratorTracker(SourceLineInfo const &lineInfo) -> IGeneratorTracker & = 0;
  2217. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  2218. virtual void benchmarkPreparing( std::string const& name ) = 0;
  2219. virtual void benchmarkStarting( BenchmarkInfo const& info ) = 0;
  2220. virtual void benchmarkEnded( BenchmarkStats<> const& stats ) = 0;
  2221. virtual void benchmarkFailed( std::string const& error ) = 0;
  2222. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  2223. virtual void pushScopedMessage(MessageInfo const &message) = 0;
  2224. virtual void popScopedMessage(MessageInfo const &message) = 0;
  2225. virtual void emplaceUnscopedMessage(MessageBuilder const &builder) = 0;
  2226. virtual void handleFatalErrorCondition(StringRef message) = 0;
  2227. virtual void handleExpr
  2228. (AssertionInfo const &info,
  2229. ITransientExpression const &expr,
  2230. AssertionReaction &reaction) = 0;
  2231. virtual void handleMessage
  2232. (AssertionInfo const &info,
  2233. ResultWas::OfType resultType,
  2234. StringRef const &message,
  2235. AssertionReaction &reaction) = 0;
  2236. virtual void handleUnexpectedExceptionNotThrown
  2237. (AssertionInfo const &info,
  2238. AssertionReaction &reaction) = 0;
  2239. virtual void handleUnexpectedInflightException
  2240. (AssertionInfo const &info,
  2241. std::string const &message,
  2242. AssertionReaction &reaction) = 0;
  2243. virtual void handleIncomplete
  2244. (AssertionInfo const &info) = 0;
  2245. virtual void handleNonExpr
  2246. (AssertionInfo const &info,
  2247. ResultWas::OfType resultType,
  2248. AssertionReaction &reaction) = 0;
  2249. virtual bool lastAssertionPassed() = 0;
  2250. virtual void assertionPassed() = 0;
  2251. // Deprecated, do not use:
  2252. virtual std::string getCurrentTestName() const = 0;
  2253. virtual const AssertionResult *getLastResult() const = 0;
  2254. virtual void exceptionEarlyReported() = 0;
  2255. };
  2256. IResultCapture &getResultCapture();
  2257. }
  2258. // end catch_interfaces_capture.h
  2259. namespace Catch {
  2260. struct TestFailureException
  2261. {
  2262. };
  2263. struct AssertionResultData;
  2264. struct IResultCapture;
  2265. class RunContext;
  2266. class LazyExpression
  2267. {
  2268. friend class AssertionHandler;
  2269. friend struct AssertionStats;
  2270. friend class RunContext;
  2271. ITransientExpression const *m_transientExpression = nullptr;
  2272. bool m_isNegated;
  2273. public:
  2274. LazyExpression(bool isNegated);
  2275. LazyExpression(LazyExpression const &other);
  2276. LazyExpression &operator=(LazyExpression const &) = delete;
  2277. explicit operator bool() const;
  2278. friend auto operator<<(std::ostream &os, LazyExpression const &lazyExpr) -> std::ostream &;
  2279. };
  2280. struct AssertionReaction
  2281. {
  2282. bool shouldDebugBreak = false;
  2283. bool shouldThrow = false;
  2284. };
  2285. class AssertionHandler
  2286. {
  2287. AssertionInfo m_assertionInfo;
  2288. AssertionReaction m_reaction;
  2289. bool m_completed = false;
  2290. IResultCapture &m_resultCapture;
  2291. public:
  2292. AssertionHandler
  2293. (StringRef const &macroName,
  2294. SourceLineInfo const &lineInfo,
  2295. StringRef capturedExpression,
  2296. ResultDisposition::Flags resultDisposition);
  2297. ~AssertionHandler()
  2298. {
  2299. if (!m_completed) {
  2300. m_resultCapture.handleIncomplete(m_assertionInfo);
  2301. }
  2302. }
  2303. template<typename T>
  2304. void handleExpr(ExprLhs<T> const &expr)
  2305. {
  2306. handleExpr(expr.makeUnaryExpr());
  2307. }
  2308. void handleExpr(ITransientExpression const &expr);
  2309. void handleMessage(ResultWas::OfType resultType, StringRef const &message);
  2310. void handleExceptionThrownAsExpected();
  2311. void handleUnexpectedExceptionNotThrown();
  2312. void handleExceptionNotThrownAsExpected();
  2313. void handleThrowingCallSkipped();
  2314. void handleUnexpectedInflightException();
  2315. void complete();
  2316. void setCompleted();
  2317. // query
  2318. auto allowThrows() const -> bool;
  2319. };
  2320. void handleExceptionMatchExpr(AssertionHandler &handler,
  2321. std::string const &str,
  2322. StringRef const &matcherString);
  2323. } // namespace Catch
  2324. // end catch_assertionhandler.h
  2325. // start catch_message.h
  2326. #include <string>
  2327. #include <vector>
  2328. namespace Catch {
  2329. struct MessageInfo
  2330. {
  2331. MessageInfo(StringRef const &_macroName,
  2332. SourceLineInfo const &_lineInfo,
  2333. ResultWas::OfType _type);
  2334. StringRef macroName;
  2335. std::string message;
  2336. SourceLineInfo lineInfo;
  2337. ResultWas::OfType type;
  2338. unsigned int sequence;
  2339. bool operator==(MessageInfo const &other) const;
  2340. bool operator<(MessageInfo const &other) const;
  2341. private:
  2342. static unsigned int globalCount;
  2343. };
  2344. struct MessageStream
  2345. {
  2346. template<typename T>
  2347. MessageStream &operator<<(T const &value)
  2348. {
  2349. m_stream << value;
  2350. return *this;
  2351. }
  2352. ReusableStringStream m_stream;
  2353. };
  2354. struct MessageBuilder : MessageStream
  2355. {
  2356. MessageBuilder(StringRef const &macroName,
  2357. SourceLineInfo const &lineInfo,
  2358. ResultWas::OfType type);
  2359. template<typename T>
  2360. MessageBuilder &operator<<(T const &value)
  2361. {
  2362. m_stream << value;
  2363. return *this;
  2364. }
  2365. MessageInfo m_info;
  2366. };
  2367. class ScopedMessage
  2368. {
  2369. public:
  2370. explicit ScopedMessage(MessageBuilder const &builder);
  2371. ScopedMessage(ScopedMessage &duplicate) = delete;
  2372. ScopedMessage(ScopedMessage &&old);
  2373. ~ScopedMessage();
  2374. MessageInfo m_info;
  2375. bool m_moved;
  2376. };
  2377. class Capturer
  2378. {
  2379. std::vector<MessageInfo> m_messages;
  2380. IResultCapture &m_resultCapture = getResultCapture();
  2381. size_t m_captured = 0;
  2382. public:
  2383. Capturer(StringRef macroName,
  2384. SourceLineInfo const &lineInfo,
  2385. ResultWas::OfType resultType,
  2386. StringRef names);
  2387. ~Capturer();
  2388. void captureValue(size_t index, std::string const &value);
  2389. template<typename T>
  2390. void captureValues(size_t index, T const &value)
  2391. {
  2392. captureValue(index, Catch::Detail::stringify(value));
  2393. }
  2394. template<typename T, typename... Ts>
  2395. void captureValues(size_t index, T const &value, Ts const &... values)
  2396. {
  2397. captureValue(index, Catch::Detail::stringify(value));
  2398. captureValues(index + 1, values...);
  2399. }
  2400. };
  2401. } // end namespace Catch
  2402. // end catch_message.h
  2403. #if !defined(CATCH_CONFIG_DISABLE)
  2404. #if !defined(CATCH_CONFIG_DISABLE_STRINGIFICATION)
  2405. #define CATCH_INTERNAL_STRINGIFY(...) #__VA_ARGS__
  2406. #else
  2407. #define CATCH_INTERNAL_STRINGIFY(...) "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION"
  2408. #endif
  2409. #if defined(CATCH_CONFIG_FAST_COMPILE) || defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  2410. ///////////////////////////////////////////////////////////////////////////////
  2411. // Another way to speed-up compilation is to omit local try-catch for REQUIRE*
  2412. // macros.
  2413. #define INTERNAL_CATCH_TRY
  2414. #define INTERNAL_CATCH_CATCH( capturer )
  2415. #else // CATCH_CONFIG_FAST_COMPILE
  2416. #define INTERNAL_CATCH_TRY try
  2417. #define INTERNAL_CATCH_CATCH(handler) catch(...) { handler.handleUnexpectedInflightException(); }
  2418. #endif
  2419. #define INTERNAL_CATCH_REACT(handler) handler.complete();
  2420. ///////////////////////////////////////////////////////////////////////////////
  2421. #define INTERNAL_CATCH_TEST(macroName, resultDisposition, ...) \
  2422. do { \
  2423. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
  2424. INTERNAL_CATCH_TRY { \
  2425. CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
  2426. catchAssertionHandler.handleExpr( Catch::Decomposer() <= __VA_ARGS__ ); \
  2427. CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
  2428. } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
  2429. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2430. } 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
  2431. // The double negation silences MSVC's C4800 warning, the static_cast forces short-circuit evaluation if the type has overloaded &&.
  2432. ///////////////////////////////////////////////////////////////////////////////
  2433. #define INTERNAL_CATCH_IF(macroName, resultDisposition, ...) \
  2434. INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
  2435. if( Catch::getResultCapture().lastAssertionPassed() )
  2436. ///////////////////////////////////////////////////////////////////////////////
  2437. #define INTERNAL_CATCH_ELSE(macroName, resultDisposition, ...) \
  2438. INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
  2439. if( !Catch::getResultCapture().lastAssertionPassed() )
  2440. ///////////////////////////////////////////////////////////////////////////////
  2441. #define INTERNAL_CATCH_NO_THROW(macroName, resultDisposition, ...) \
  2442. do { \
  2443. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
  2444. try { \
  2445. static_cast<void>(__VA_ARGS__); \
  2446. catchAssertionHandler.handleExceptionNotThrownAsExpected(); \
  2447. } \
  2448. catch( ... ) { \
  2449. catchAssertionHandler.handleUnexpectedInflightException(); \
  2450. } \
  2451. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2452. } while( false )
  2453. ///////////////////////////////////////////////////////////////////////////////
  2454. #define INTERNAL_CATCH_THROWS(macroName, resultDisposition, ...) \
  2455. do { \
  2456. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition); \
  2457. if( catchAssertionHandler.allowThrows() ) \
  2458. try { \
  2459. static_cast<void>(__VA_ARGS__); \
  2460. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  2461. } \
  2462. catch( ... ) { \
  2463. catchAssertionHandler.handleExceptionThrownAsExpected(); \
  2464. } \
  2465. else \
  2466. catchAssertionHandler.handleThrowingCallSkipped(); \
  2467. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2468. } while( false )
  2469. ///////////////////////////////////////////////////////////////////////////////
  2470. #define INTERNAL_CATCH_THROWS_AS(macroName, exceptionType, resultDisposition, expr) \
  2471. do { \
  2472. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType), resultDisposition ); \
  2473. if( catchAssertionHandler.allowThrows() ) \
  2474. try { \
  2475. static_cast<void>(expr); \
  2476. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  2477. } \
  2478. catch( exceptionType const& ) { \
  2479. catchAssertionHandler.handleExceptionThrownAsExpected(); \
  2480. } \
  2481. catch( ... ) { \
  2482. catchAssertionHandler.handleUnexpectedInflightException(); \
  2483. } \
  2484. else \
  2485. catchAssertionHandler.handleThrowingCallSkipped(); \
  2486. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2487. } while( false )
  2488. ///////////////////////////////////////////////////////////////////////////////
  2489. #define INTERNAL_CATCH_MSG(macroName, messageType, resultDisposition, ...) \
  2490. do { \
  2491. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::StringRef(), resultDisposition ); \
  2492. catchAssertionHandler.handleMessage( messageType, ( Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop() ).m_stream.str() ); \
  2493. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2494. } while( false )
  2495. ///////////////////////////////////////////////////////////////////////////////
  2496. #define INTERNAL_CATCH_CAPTURE(varName, macroName, ...) \
  2497. auto varName = Catch::Capturer( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info, #__VA_ARGS__ ); \
  2498. varName.captureValues( 0, __VA_ARGS__ )
  2499. ///////////////////////////////////////////////////////////////////////////////
  2500. #define INTERNAL_CATCH_INFO(macroName, log) \
  2501. Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage )( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log );
  2502. ///////////////////////////////////////////////////////////////////////////////
  2503. #define INTERNAL_CATCH_UNSCOPED_INFO(macroName, log) \
  2504. Catch::getResultCapture().emplaceUnscopedMessage( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log )
  2505. ///////////////////////////////////////////////////////////////////////////////
  2506. // Although this is matcher-based, it can be used with just a string
  2507. #define INTERNAL_CATCH_THROWS_STR_MATCHES(macroName, resultDisposition, matcher, ...) \
  2508. do { \
  2509. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  2510. if( catchAssertionHandler.allowThrows() ) \
  2511. try { \
  2512. static_cast<void>(__VA_ARGS__); \
  2513. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  2514. } \
  2515. catch( ... ) { \
  2516. Catch::handleExceptionMatchExpr( catchAssertionHandler, matcher, #matcher##_catch_sr ); \
  2517. } \
  2518. else \
  2519. catchAssertionHandler.handleThrowingCallSkipped(); \
  2520. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2521. } while( false )
  2522. #endif // CATCH_CONFIG_DISABLE
  2523. // end catch_capture.hpp
  2524. // start catch_section.h
  2525. // start catch_section_info.h
  2526. // start catch_totals.h
  2527. #include <cstddef>
  2528. namespace Catch {
  2529. struct Counts
  2530. {
  2531. Counts operator-(Counts const &other) const;
  2532. Counts &operator+=(Counts const &other);
  2533. std::size_t total() const;
  2534. bool allPassed() const;
  2535. bool allOk() const;
  2536. std::size_t passed = 0;
  2537. std::size_t failed = 0;
  2538. std::size_t failedButOk = 0;
  2539. };
  2540. struct Totals
  2541. {
  2542. Totals operator-(Totals const &other) const;
  2543. Totals &operator+=(Totals const &other);
  2544. Totals delta(Totals const &prevTotals) const;
  2545. int error = 0;
  2546. Counts assertions;
  2547. Counts testCases;
  2548. };
  2549. }
  2550. // end catch_totals.h
  2551. #include <string>
  2552. namespace Catch {
  2553. struct SectionInfo
  2554. {
  2555. SectionInfo
  2556. (SourceLineInfo const &_lineInfo,
  2557. std::string const &_name);
  2558. // Deprecated
  2559. SectionInfo
  2560. (SourceLineInfo const &_lineInfo,
  2561. std::string const &_name,
  2562. std::string const &) : SectionInfo(_lineInfo, _name)
  2563. {}
  2564. std::string name;
  2565. std::string description; // !Deprecated: this will always be empty
  2566. SourceLineInfo lineInfo;
  2567. };
  2568. struct SectionEndInfo
  2569. {
  2570. SectionInfo sectionInfo;
  2571. Counts prevAssertions;
  2572. double durationInSeconds;
  2573. };
  2574. } // end namespace Catch
  2575. // end catch_section_info.h
  2576. // start catch_timer.h
  2577. #include <cstdint>
  2578. namespace Catch {
  2579. auto getCurrentNanosecondsSinceEpoch() -> uint64_t;
  2580. auto getEstimatedClockResolution() -> uint64_t;
  2581. class Timer
  2582. {
  2583. uint64_t m_nanoseconds = 0;
  2584. public:
  2585. void start();
  2586. auto getElapsedNanoseconds() const -> uint64_t;
  2587. auto getElapsedMicroseconds() const -> uint64_t;
  2588. auto getElapsedMilliseconds() const -> unsigned int;
  2589. auto getElapsedSeconds() const -> double;
  2590. };
  2591. } // namespace Catch
  2592. // end catch_timer.h
  2593. #include <string>
  2594. namespace Catch {
  2595. class Section : NonCopyable
  2596. {
  2597. public:
  2598. Section(SectionInfo const &info);
  2599. ~Section();
  2600. // This indicates whether the section should be executed or not
  2601. explicit operator bool() const;
  2602. private:
  2603. SectionInfo m_info;
  2604. std::string m_name;
  2605. Counts m_assertions;
  2606. bool m_sectionIncluded;
  2607. Timer m_timer;
  2608. };
  2609. } // end namespace Catch
  2610. #define INTERNAL_CATCH_SECTION(...) \
  2611. CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
  2612. if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) ) \
  2613. CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS
  2614. #define INTERNAL_CATCH_DYNAMIC_SECTION(...) \
  2615. CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
  2616. if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, (Catch::ReusableStringStream() << __VA_ARGS__).str() ) ) \
  2617. CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS
  2618. // end catch_section.h
  2619. // start catch_interfaces_exception.h
  2620. // start catch_interfaces_registry_hub.h
  2621. #include <string>
  2622. #include <memory>
  2623. namespace Catch {
  2624. class TestCase;
  2625. struct ITestCaseRegistry;
  2626. struct IExceptionTranslatorRegistry;
  2627. struct IExceptionTranslator;
  2628. struct IReporterRegistry;
  2629. struct IReporterFactory;
  2630. struct ITagAliasRegistry;
  2631. struct IMutableEnumValuesRegistry;
  2632. class StartupExceptionRegistry;
  2633. using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
  2634. struct IRegistryHub
  2635. {
  2636. virtual ~IRegistryHub();
  2637. virtual IReporterRegistry const &getReporterRegistry() const = 0;
  2638. virtual ITestCaseRegistry const &getTestCaseRegistry() const = 0;
  2639. virtual ITagAliasRegistry const &getTagAliasRegistry() const = 0;
  2640. virtual IExceptionTranslatorRegistry const &getExceptionTranslatorRegistry() const = 0;
  2641. virtual StartupExceptionRegistry const &getStartupExceptionRegistry() const = 0;
  2642. };
  2643. struct IMutableRegistryHub
  2644. {
  2645. virtual ~IMutableRegistryHub();
  2646. virtual void registerReporter(std::string const &name, IReporterFactoryPtr const &factory) = 0;
  2647. virtual void registerListener(IReporterFactoryPtr const &factory) = 0;
  2648. virtual void registerTest(TestCase const &testInfo) = 0;
  2649. virtual void registerTranslator(const IExceptionTranslator *translator) = 0;
  2650. virtual void registerTagAlias(std::string const &alias,
  2651. std::string const &tag,
  2652. SourceLineInfo const &lineInfo) = 0;
  2653. virtual void registerStartupException() noexcept = 0;
  2654. virtual IMutableEnumValuesRegistry &getMutableEnumValuesRegistry() = 0;
  2655. };
  2656. IRegistryHub const &getRegistryHub();
  2657. IMutableRegistryHub &getMutableRegistryHub();
  2658. void cleanUp();
  2659. std::string translateActiveException();
  2660. }
  2661. // end catch_interfaces_registry_hub.h
  2662. #if defined(CATCH_CONFIG_DISABLE)
  2663. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( translatorName, signature) \
  2664. static std::string translatorName( signature )
  2665. #endif
  2666. #include <exception>
  2667. #include <string>
  2668. #include <vector>
  2669. namespace Catch {
  2670. using exceptionTranslateFunction = std::string(*)();
  2671. struct IExceptionTranslator;
  2672. using ExceptionTranslators = std::vector<std::unique_ptr<IExceptionTranslator const>>;
  2673. struct IExceptionTranslator
  2674. {
  2675. virtual ~IExceptionTranslator();
  2676. virtual std::string translate(ExceptionTranslators::const_iterator it,
  2677. ExceptionTranslators::const_iterator itEnd) const = 0;
  2678. };
  2679. struct IExceptionTranslatorRegistry
  2680. {
  2681. virtual ~IExceptionTranslatorRegistry();
  2682. virtual std::string translateActiveException() const = 0;
  2683. };
  2684. class ExceptionTranslatorRegistrar
  2685. {
  2686. template<typename T>
  2687. class ExceptionTranslator : public IExceptionTranslator
  2688. {
  2689. public:
  2690. ExceptionTranslator(std::string(*translateFunction)(T &))
  2691. : m_translateFunction(translateFunction)
  2692. {}
  2693. std::string translate(ExceptionTranslators::const_iterator it,
  2694. ExceptionTranslators::const_iterator itEnd) const override
  2695. {
  2696. try {
  2697. if (it == itEnd)
  2698. std::rethrow_exception(std::current_exception());
  2699. else
  2700. return (*it)->translate(it + 1, itEnd);
  2701. }
  2702. catch (T &ex) {
  2703. return m_translateFunction(ex);
  2704. }
  2705. }
  2706. protected:
  2707. std::string (*m_translateFunction)(T &);
  2708. };
  2709. public:
  2710. template<typename T>
  2711. ExceptionTranslatorRegistrar(std::string(*translateFunction)(T &))
  2712. {
  2713. getMutableRegistryHub().registerTranslator
  2714. (new ExceptionTranslator<T>(translateFunction));
  2715. }
  2716. };
  2717. }
  2718. ///////////////////////////////////////////////////////////////////////////////
  2719. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION2(translatorName, signature) \
  2720. static std::string translatorName( signature ); \
  2721. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  2722. namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &translatorName ); } \
  2723. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  2724. static std::string translatorName( signature )
  2725. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION(signature) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
  2726. // end catch_interfaces_exception.h
  2727. // start catch_approx.h
  2728. #include <type_traits>
  2729. namespace Catch {
  2730. namespace Detail {
  2731. class Approx
  2732. {
  2733. private:
  2734. bool equalityComparisonImpl(double other) const;
  2735. // Validates the new margin (margin >= 0)
  2736. // out-of-line to avoid including stdexcept in the header
  2737. void setMargin(double margin);
  2738. // Validates the new epsilon (0 < epsilon < 1)
  2739. // out-of-line to avoid including stdexcept in the header
  2740. void setEpsilon(double epsilon);
  2741. public:
  2742. explicit Approx(double value);
  2743. static Approx custom();
  2744. Approx operator-() const;
  2745. template<typename T, typename = typename std::enable_if<std::is_constructible<double,
  2746. T>::value>::type>
  2747. Approx operator()(T const &value)
  2748. {
  2749. Approx approx(static_cast<double>(value));
  2750. approx.m_epsilon = m_epsilon;
  2751. approx.m_margin = m_margin;
  2752. approx.m_scale = m_scale;
  2753. return approx;
  2754. }
  2755. template<typename T, typename = typename std::enable_if<std::is_constructible<double,
  2756. T>::value>::type>
  2757. explicit Approx(T const &value): Approx(static_cast<double>(value))
  2758. {}
  2759. template<typename T, typename = typename std::enable_if<std::is_constructible<double,
  2760. T>::value>::type>
  2761. friend bool operator==(const T &lhs, Approx const &rhs)
  2762. {
  2763. auto lhs_v = static_cast<double>(lhs);
  2764. return rhs.equalityComparisonImpl(lhs_v);
  2765. }
  2766. template<typename T, typename = typename std::enable_if<std::is_constructible<double,
  2767. T>::value>::type>
  2768. friend bool operator==(Approx const &lhs, const T &rhs)
  2769. {
  2770. return operator==(rhs, lhs);
  2771. }
  2772. template<typename T, typename = typename std::enable_if<std::is_constructible<double,
  2773. T>::value>::type>
  2774. friend bool operator!=(T const &lhs, Approx const &rhs)
  2775. {
  2776. return !operator==(lhs, rhs);
  2777. }
  2778. template<typename T, typename = typename std::enable_if<std::is_constructible<double,
  2779. T>::value>::type>
  2780. friend bool operator!=(Approx const &lhs, T const &rhs)
  2781. {
  2782. return !operator==(rhs, lhs);
  2783. }
  2784. template<typename T, typename = typename std::enable_if<std::is_constructible<double,
  2785. T>::value>::type>
  2786. friend bool operator<=(T const &lhs, Approx const &rhs)
  2787. {
  2788. return static_cast<double>(lhs) < rhs.m_value || lhs == rhs;
  2789. }
  2790. template<typename T, typename = typename std::enable_if<std::is_constructible<double,
  2791. T>::value>::type>
  2792. friend bool operator<=(Approx const &lhs, T const &rhs)
  2793. {
  2794. return lhs.m_value < static_cast<double>(rhs) || lhs == rhs;
  2795. }
  2796. template<typename T, typename = typename std::enable_if<std::is_constructible<double,
  2797. T>::value>::type>
  2798. friend bool operator>=(T const &lhs, Approx const &rhs)
  2799. {
  2800. return static_cast<double>(lhs) > rhs.m_value || lhs == rhs;
  2801. }
  2802. template<typename T, typename = typename std::enable_if<std::is_constructible<double,
  2803. T>::value>::type>
  2804. friend bool operator>=(Approx const &lhs, T const &rhs)
  2805. {
  2806. return lhs.m_value > static_cast<double>(rhs) || lhs == rhs;
  2807. }
  2808. template<typename T, typename = typename std::enable_if<std::is_constructible<double,
  2809. T>::value>::type>
  2810. Approx &epsilon(T const &newEpsilon)
  2811. {
  2812. double epsilonAsDouble = static_cast<double>(newEpsilon);
  2813. setEpsilon(epsilonAsDouble);
  2814. return *this;
  2815. }
  2816. template<typename T, typename = typename std::enable_if<std::is_constructible<double,
  2817. T>::value>::type>
  2818. Approx &margin(T const &newMargin)
  2819. {
  2820. double marginAsDouble = static_cast<double>(newMargin);
  2821. setMargin(marginAsDouble);
  2822. return *this;
  2823. }
  2824. template<typename T, typename = typename std::enable_if<std::is_constructible<double,
  2825. T>::value>::type>
  2826. Approx &scale(T const &newScale)
  2827. {
  2828. m_scale = static_cast<double>(newScale);
  2829. return *this;
  2830. }
  2831. std::string toString() const;
  2832. private:
  2833. double m_epsilon;
  2834. double m_margin;
  2835. double m_scale;
  2836. double m_value;
  2837. };
  2838. } // end namespace Detail
  2839. namespace literals {
  2840. Detail::Approx operator "" _a(long double val);
  2841. Detail::Approx operator "" _a(unsigned long long val);
  2842. } // end namespace literals
  2843. template<>
  2844. struct StringMaker<Catch::Detail::Approx>
  2845. {
  2846. static std::string convert(Catch::Detail::Approx const &value);
  2847. };
  2848. } // end namespace Catch
  2849. // end catch_approx.h
  2850. // start catch_string_manip.h
  2851. #include <string>
  2852. #include <iosfwd>
  2853. #include <vector>
  2854. namespace Catch {
  2855. bool startsWith(std::string const &s, std::string const &prefix);
  2856. bool startsWith(std::string const &s, char prefix);
  2857. bool endsWith(std::string const &s, std::string const &suffix);
  2858. bool endsWith(std::string const &s, char suffix);
  2859. bool contains(std::string const &s, std::string const &infix);
  2860. void toLowerInPlace(std::string &s);
  2861. std::string toLower(std::string const &s);
  2862. std::string trim(std::string const &str);
  2863. // !!! Be aware, returns refs into original string - make sure original string outlives them
  2864. std::vector<StringRef> splitStringRef(StringRef str, char delimiter);
  2865. bool replaceInPlace(std::string &str, std::string const &replaceThis, std::string const &withThis);
  2866. struct pluralise
  2867. {
  2868. pluralise(std::size_t count, std::string const &label);
  2869. friend std::ostream &operator<<(std::ostream &os, pluralise const &pluraliser);
  2870. std::size_t m_count;
  2871. std::string m_label;
  2872. };
  2873. }
  2874. // end catch_string_manip.h
  2875. #ifndef CATCH_CONFIG_DISABLE_MATCHERS
  2876. // start catch_capture_matchers.h
  2877. // start catch_matchers.h
  2878. #include <string>
  2879. #include <vector>
  2880. namespace Catch {
  2881. namespace Matchers {
  2882. namespace Impl {
  2883. template<typename ArgT> struct MatchAllOf;
  2884. template<typename ArgT> struct MatchAnyOf;
  2885. template<typename ArgT> struct MatchNotOf;
  2886. class MatcherUntypedBase
  2887. {
  2888. public:
  2889. MatcherUntypedBase() = default;
  2890. MatcherUntypedBase(MatcherUntypedBase const &) = default;
  2891. MatcherUntypedBase &operator=(MatcherUntypedBase const &) = delete;
  2892. std::string toString() const;
  2893. protected:
  2894. virtual ~MatcherUntypedBase();
  2895. virtual std::string describe() const = 0;
  2896. mutable std::string m_cachedToString;
  2897. };
  2898. #ifdef __clang__
  2899. # pragma clang diagnostic push
  2900. # pragma clang diagnostic ignored "-Wnon-virtual-dtor"
  2901. #endif
  2902. template<typename ObjectT>
  2903. struct MatcherMethod
  2904. {
  2905. virtual bool match(ObjectT const &arg) const = 0;
  2906. };
  2907. #if defined(__OBJC__)
  2908. // Hack to fix Catch GH issue #1661. Could use id for generic Object support.
  2909. // use of const for Object pointers is very uncommon and under ARC it causes some kind of signature mismatch that breaks compilation
  2910. template<>
  2911. struct MatcherMethod<NSString*> {
  2912. virtual bool match( NSString* arg ) const = 0;
  2913. };
  2914. #endif
  2915. #ifdef __clang__
  2916. # pragma clang diagnostic pop
  2917. #endif
  2918. template<typename T>
  2919. struct MatcherBase : MatcherUntypedBase, MatcherMethod<T>
  2920. {
  2921. MatchAllOf<T> operator&&(MatcherBase const &other) const;
  2922. MatchAnyOf<T> operator||(MatcherBase const &other) const;
  2923. MatchNotOf<T> operator!() const;
  2924. };
  2925. template<typename ArgT>
  2926. struct MatchAllOf : MatcherBase<ArgT>
  2927. {
  2928. bool match(ArgT const &arg) const override
  2929. {
  2930. for (auto matcher : m_matchers) {
  2931. if (!matcher->match(arg))
  2932. return false;
  2933. }
  2934. return true;
  2935. }
  2936. std::string describe() const override
  2937. {
  2938. std::string description;
  2939. description.reserve(4 + m_matchers.size() * 32);
  2940. description += "( ";
  2941. bool first = true;
  2942. for (auto matcher : m_matchers) {
  2943. if (first)
  2944. first = false;
  2945. else
  2946. description += " and ";
  2947. description += matcher->toString();
  2948. }
  2949. description += " )";
  2950. return description;
  2951. }
  2952. MatchAllOf<ArgT> &operator&&(MatcherBase<ArgT> const &other)
  2953. {
  2954. m_matchers.push_back(&other);
  2955. return *this;
  2956. }
  2957. std::vector<MatcherBase<ArgT> const *> m_matchers;
  2958. };
  2959. template<typename ArgT>
  2960. struct MatchAnyOf : MatcherBase<ArgT>
  2961. {
  2962. bool match(ArgT const &arg) const override
  2963. {
  2964. for (auto matcher : m_matchers) {
  2965. if (matcher->match(arg))
  2966. return true;
  2967. }
  2968. return false;
  2969. }
  2970. std::string describe() const override
  2971. {
  2972. std::string description;
  2973. description.reserve(4 + m_matchers.size() * 32);
  2974. description += "( ";
  2975. bool first = true;
  2976. for (auto matcher : m_matchers) {
  2977. if (first)
  2978. first = false;
  2979. else
  2980. description += " or ";
  2981. description += matcher->toString();
  2982. }
  2983. description += " )";
  2984. return description;
  2985. }
  2986. MatchAnyOf<ArgT> &operator||(MatcherBase<ArgT> const &other)
  2987. {
  2988. m_matchers.push_back(&other);
  2989. return *this;
  2990. }
  2991. std::vector<MatcherBase<ArgT> const *> m_matchers;
  2992. };
  2993. template<typename ArgT>
  2994. struct MatchNotOf : MatcherBase<ArgT>
  2995. {
  2996. MatchNotOf(MatcherBase<ArgT> const &underlyingMatcher) : m_underlyingMatcher(underlyingMatcher)
  2997. {}
  2998. bool match(ArgT const &arg) const override
  2999. {
  3000. return !m_underlyingMatcher.match(arg);
  3001. }
  3002. std::string describe() const override
  3003. {
  3004. return "not " + m_underlyingMatcher.toString();
  3005. }
  3006. MatcherBase<ArgT> const &m_underlyingMatcher;
  3007. };
  3008. template<typename T>
  3009. MatchAllOf<T> MatcherBase<T>::operator&&(MatcherBase const &other) const
  3010. {
  3011. return MatchAllOf<T>() && *this && other;
  3012. }
  3013. template<typename T>
  3014. MatchAnyOf<T> MatcherBase<T>::operator||(MatcherBase const &other) const
  3015. {
  3016. return MatchAnyOf<T>() || *this || other;
  3017. }
  3018. template<typename T>
  3019. MatchNotOf<T> MatcherBase<T>::operator!() const
  3020. {
  3021. return MatchNotOf<T>(*this);
  3022. }
  3023. } // namespace Impl
  3024. } // namespace Matchers
  3025. using namespace Matchers;
  3026. using Matchers::Impl::MatcherBase;
  3027. } // namespace Catch
  3028. // end catch_matchers.h
  3029. // start catch_matchers_floating.h
  3030. #include <type_traits>
  3031. #include <cmath>
  3032. namespace Catch {
  3033. namespace Matchers {
  3034. namespace Floating {
  3035. enum class FloatingPointKind : uint8_t;
  3036. struct WithinAbsMatcher : MatcherBase<double>
  3037. {
  3038. WithinAbsMatcher(double target, double margin);
  3039. bool match(double const &matchee) const override;
  3040. std::string describe() const override;
  3041. private:
  3042. double m_target;
  3043. double m_margin;
  3044. };
  3045. struct WithinUlpsMatcher : MatcherBase<double>
  3046. {
  3047. WithinUlpsMatcher(double target, int ulps, FloatingPointKind baseType);
  3048. bool match(double const &matchee) const override;
  3049. std::string describe() const override;
  3050. private:
  3051. double m_target;
  3052. int m_ulps;
  3053. FloatingPointKind m_type;
  3054. };
  3055. } // namespace Floating
  3056. // The following functions create the actual matcher objects.
  3057. // This allows the types to be inferred
  3058. Floating::WithinUlpsMatcher WithinULP(double target, int maxUlpDiff);
  3059. Floating::WithinUlpsMatcher WithinULP(float target, int maxUlpDiff);
  3060. Floating::WithinAbsMatcher WithinAbs(double target, double margin);
  3061. } // namespace Matchers
  3062. } // namespace Catch
  3063. // end catch_matchers_floating.h
  3064. // start catch_matchers_generic.hpp
  3065. #include <functional>
  3066. #include <string>
  3067. namespace Catch {
  3068. namespace Matchers {
  3069. namespace Generic {
  3070. namespace Detail {
  3071. std::string finalizeDescription(const std::string &desc);
  3072. }
  3073. template<typename T>
  3074. class PredicateMatcher : public MatcherBase<T>
  3075. {
  3076. std::function<bool(T const &)> m_predicate;
  3077. std::string m_description;
  3078. public:
  3079. PredicateMatcher(std::function<bool(T const &)> const &elem, std::string const &descr)
  3080. : m_predicate(std::move(elem)),
  3081. m_description(Detail::finalizeDescription(descr))
  3082. {}
  3083. bool match(T const &item) const override
  3084. {
  3085. return m_predicate(item);
  3086. }
  3087. std::string describe() const override
  3088. {
  3089. return m_description;
  3090. }
  3091. };
  3092. } // namespace Generic
  3093. // The following functions create the actual matcher objects.
  3094. // The user has to explicitly specify type to the function, because
  3095. // inferring std::function<bool(T const&)> is hard (but possible) and
  3096. // requires a lot of TMP.
  3097. template<typename T>
  3098. Generic::PredicateMatcher<T> Predicate(std::function<bool(T const &)> const &predicate,
  3099. std::string const &description = "")
  3100. {
  3101. return Generic::PredicateMatcher<T>(predicate, description);
  3102. }
  3103. } // namespace Matchers
  3104. } // namespace Catch
  3105. // end catch_matchers_generic.hpp
  3106. // start catch_matchers_string.h
  3107. #include <string>
  3108. namespace Catch {
  3109. namespace Matchers {
  3110. namespace StdString {
  3111. struct CasedString
  3112. {
  3113. CasedString(std::string const &str, CaseSensitive::Choice caseSensitivity);
  3114. std::string adjustString(std::string const &str) const;
  3115. std::string caseSensitivitySuffix() const;
  3116. CaseSensitive::Choice m_caseSensitivity;
  3117. std::string m_str;
  3118. };
  3119. struct StringMatcherBase : MatcherBase<std::string>
  3120. {
  3121. StringMatcherBase(std::string const &operation, CasedString const &comparator);
  3122. std::string describe() const override;
  3123. CasedString m_comparator;
  3124. std::string m_operation;
  3125. };
  3126. struct EqualsMatcher : StringMatcherBase
  3127. {
  3128. EqualsMatcher(CasedString const &comparator);
  3129. bool match(std::string const &source) const override;
  3130. };
  3131. struct ContainsMatcher : StringMatcherBase
  3132. {
  3133. ContainsMatcher(CasedString const &comparator);
  3134. bool match(std::string const &source) const override;
  3135. };
  3136. struct StartsWithMatcher : StringMatcherBase
  3137. {
  3138. StartsWithMatcher(CasedString const &comparator);
  3139. bool match(std::string const &source) const override;
  3140. };
  3141. struct EndsWithMatcher : StringMatcherBase
  3142. {
  3143. EndsWithMatcher(CasedString const &comparator);
  3144. bool match(std::string const &source) const override;
  3145. };
  3146. struct RegexMatcher : MatcherBase<std::string>
  3147. {
  3148. RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity);
  3149. bool match(std::string const &matchee) const override;
  3150. std::string describe() const override;
  3151. private:
  3152. std::string m_regex;
  3153. CaseSensitive::Choice m_caseSensitivity;
  3154. };
  3155. } // namespace StdString
  3156. // The following functions create the actual matcher objects.
  3157. // This allows the types to be inferred
  3158. StdString::EqualsMatcher Equals(std::string const &str,
  3159. CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes);
  3160. StdString::ContainsMatcher Contains(std::string const &str,
  3161. CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes);
  3162. StdString::EndsWithMatcher EndsWith(std::string const &str,
  3163. CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes);
  3164. StdString::StartsWithMatcher StartsWith(std::string const &str,
  3165. CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes);
  3166. StdString::RegexMatcher Matches(std::string const &regex,
  3167. CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes);
  3168. } // namespace Matchers
  3169. } // namespace Catch
  3170. // end catch_matchers_string.h
  3171. // start catch_matchers_vector.h
  3172. #include <algorithm>
  3173. namespace Catch {
  3174. namespace Matchers {
  3175. namespace Vector {
  3176. template<typename T>
  3177. struct ContainsElementMatcher : MatcherBase<std::vector<T>>
  3178. {
  3179. ContainsElementMatcher(T const &comparator) : m_comparator(comparator)
  3180. {}
  3181. bool match(std::vector<T> const &v) const override
  3182. {
  3183. for (auto const &el : v) {
  3184. if (el == m_comparator) {
  3185. return true;
  3186. }
  3187. }
  3188. return false;
  3189. }
  3190. std::string describe() const override
  3191. {
  3192. return "Contains: " + ::Catch::Detail::stringify(m_comparator);
  3193. }
  3194. T const &m_comparator;
  3195. };
  3196. template<typename T>
  3197. struct ContainsMatcher : MatcherBase<std::vector<T>>
  3198. {
  3199. ContainsMatcher(std::vector<T> const &comparator) : m_comparator(comparator)
  3200. {}
  3201. bool match(std::vector<T> const &v) const override
  3202. {
  3203. // !TBD: see note in EqualsMatcher
  3204. if (m_comparator.size() > v.size())
  3205. return false;
  3206. for (auto const &comparator : m_comparator) {
  3207. auto present = false;
  3208. for (const auto &el : v) {
  3209. if (el == comparator) {
  3210. present = true;
  3211. break;
  3212. }
  3213. }
  3214. if (!present) {
  3215. return false;
  3216. }
  3217. }
  3218. return true;
  3219. }
  3220. std::string describe() const override
  3221. {
  3222. return "Contains: " + ::Catch::Detail::stringify(m_comparator);
  3223. }
  3224. std::vector<T> const &m_comparator;
  3225. };
  3226. template<typename T>
  3227. struct EqualsMatcher : MatcherBase<std::vector<T>>
  3228. {
  3229. EqualsMatcher(std::vector<T> const &comparator) : m_comparator(comparator)
  3230. {}
  3231. bool match(std::vector<T> const &v) const override
  3232. {
  3233. // !TBD: This currently works if all elements can be compared using !=
  3234. // - a more general approach would be via a compare template that defaults
  3235. // to using !=. but could be specialised for, e.g. std::vector<T> etc
  3236. // - then just call that directly
  3237. if (m_comparator.size() != v.size())
  3238. return false;
  3239. for (std::size_t i = 0; i < v.size(); ++i)
  3240. if (m_comparator[i] != v[i])
  3241. return false;
  3242. return true;
  3243. }
  3244. std::string describe() const override
  3245. {
  3246. return "Equals: " + ::Catch::Detail::stringify(m_comparator);
  3247. }
  3248. std::vector<T> const &m_comparator;
  3249. };
  3250. template<typename T>
  3251. struct ApproxMatcher : MatcherBase<std::vector<T>>
  3252. {
  3253. ApproxMatcher(std::vector<T> const &comparator) : m_comparator(comparator)
  3254. {}
  3255. bool match(std::vector<T> const &v) const override
  3256. {
  3257. if (m_comparator.size() != v.size())
  3258. return false;
  3259. for (std::size_t i = 0; i < v.size(); ++i)
  3260. if (m_comparator[i] != approx(v[i]))
  3261. return false;
  3262. return true;
  3263. }
  3264. std::string describe() const override
  3265. {
  3266. return "is approx: " + ::Catch::Detail::stringify(m_comparator);
  3267. }
  3268. template<typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  3269. ApproxMatcher &epsilon(T const &newEpsilon)
  3270. {
  3271. approx.epsilon(newEpsilon);
  3272. return *this;
  3273. }
  3274. template<typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  3275. ApproxMatcher &margin(T const &newMargin)
  3276. {
  3277. approx.margin(newMargin);
  3278. return *this;
  3279. }
  3280. template<typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  3281. ApproxMatcher &scale(T const &newScale)
  3282. {
  3283. approx.scale(newScale);
  3284. return *this;
  3285. }
  3286. std::vector<T> const &m_comparator;
  3287. mutable Catch::Detail::Approx approx = Catch::Detail::Approx::custom();
  3288. };
  3289. template<typename T>
  3290. struct UnorderedEqualsMatcher : MatcherBase<std::vector<T>>
  3291. {
  3292. UnorderedEqualsMatcher(std::vector<T> const &target) : m_target(target)
  3293. {}
  3294. bool match(std::vector<T> const &vec) const override
  3295. {
  3296. // Note: This is a reimplementation of std::is_permutation,
  3297. // because I don't want to include <algorithm> inside the common path
  3298. if (m_target.size() != vec.size()) {
  3299. return false;
  3300. }
  3301. return std::is_permutation(m_target.begin(), m_target.end(), vec.begin());
  3302. }
  3303. std::string describe() const override
  3304. {
  3305. return "UnorderedEquals: " + ::Catch::Detail::stringify(m_target);
  3306. }
  3307. private:
  3308. std::vector<T> const &m_target;
  3309. };
  3310. } // namespace Vector
  3311. // The following functions create the actual matcher objects.
  3312. // This allows the types to be inferred
  3313. template<typename T>
  3314. Vector::ContainsMatcher<T> Contains(std::vector<T> const &comparator)
  3315. {
  3316. return Vector::ContainsMatcher<T>(comparator);
  3317. }
  3318. template<typename T>
  3319. Vector::ContainsElementMatcher<T> VectorContains(T const &comparator)
  3320. {
  3321. return Vector::ContainsElementMatcher<T>(comparator);
  3322. }
  3323. template<typename T>
  3324. Vector::EqualsMatcher<T> Equals(std::vector<T> const &comparator)
  3325. {
  3326. return Vector::EqualsMatcher<T>(comparator);
  3327. }
  3328. template<typename T>
  3329. Vector::ApproxMatcher<T> Approx(std::vector<T> const &comparator)
  3330. {
  3331. return Vector::ApproxMatcher<T>(comparator);
  3332. }
  3333. template<typename T>
  3334. Vector::UnorderedEqualsMatcher<T> UnorderedEquals(std::vector<T> const &target)
  3335. {
  3336. return Vector::UnorderedEqualsMatcher<T>(target);
  3337. }
  3338. } // namespace Matchers
  3339. } // namespace Catch
  3340. // end catch_matchers_vector.h
  3341. namespace Catch {
  3342. template<typename ArgT, typename MatcherT>
  3343. class MatchExpr : public ITransientExpression
  3344. {
  3345. ArgT const &m_arg;
  3346. MatcherT m_matcher;
  3347. StringRef m_matcherString;
  3348. public:
  3349. MatchExpr(ArgT const &arg, MatcherT const &matcher, StringRef const &matcherString)
  3350. : ITransientExpression{true, matcher.match(arg)},
  3351. m_arg(arg),
  3352. m_matcher(matcher),
  3353. m_matcherString(matcherString)
  3354. {}
  3355. void streamReconstructedExpression(std::ostream &os) const override
  3356. {
  3357. auto matcherAsString = m_matcher.toString();
  3358. os << Catch::Detail::stringify(m_arg) << ' ';
  3359. if (matcherAsString == Detail::unprintableString)
  3360. os << m_matcherString;
  3361. else
  3362. os << matcherAsString;
  3363. }
  3364. };
  3365. using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
  3366. void handleExceptionMatchExpr(AssertionHandler &handler,
  3367. StringMatcher const &matcher,
  3368. StringRef const &matcherString);
  3369. template<typename ArgT, typename MatcherT>
  3370. auto makeMatchExpr(ArgT const &arg,
  3371. MatcherT const &matcher,
  3372. StringRef const &matcherString) -> MatchExpr<ArgT, MatcherT>
  3373. {
  3374. return MatchExpr<ArgT, MatcherT>(arg, matcher, matcherString);
  3375. }
  3376. } // namespace Catch
  3377. ///////////////////////////////////////////////////////////////////////////////
  3378. #define INTERNAL_CHECK_THAT(macroName, matcher, resultDisposition, arg) \
  3379. do { \
  3380. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  3381. INTERNAL_CATCH_TRY { \
  3382. catchAssertionHandler.handleExpr( Catch::makeMatchExpr( arg, matcher, #matcher##_catch_sr ) ); \
  3383. } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
  3384. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  3385. } while( false )
  3386. ///////////////////////////////////////////////////////////////////////////////
  3387. #define INTERNAL_CATCH_THROWS_MATCHES(macroName, exceptionType, resultDisposition, matcher, ...) \
  3388. do { \
  3389. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(exceptionType) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  3390. if( catchAssertionHandler.allowThrows() ) \
  3391. try { \
  3392. static_cast<void>(__VA_ARGS__ ); \
  3393. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  3394. } \
  3395. catch( exceptionType const& ex ) { \
  3396. catchAssertionHandler.handleExpr( Catch::makeMatchExpr( ex, matcher, #matcher##_catch_sr ) ); \
  3397. } \
  3398. catch( ... ) { \
  3399. catchAssertionHandler.handleUnexpectedInflightException(); \
  3400. } \
  3401. else \
  3402. catchAssertionHandler.handleThrowingCallSkipped(); \
  3403. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  3404. } while( false )
  3405. // end catch_capture_matchers.h
  3406. #endif
  3407. // start catch_generators.hpp
  3408. // start catch_interfaces_generatortracker.h
  3409. #include <memory>
  3410. namespace Catch {
  3411. namespace Generators {
  3412. class GeneratorUntypedBase
  3413. {
  3414. public:
  3415. GeneratorUntypedBase() = default;
  3416. virtual ~GeneratorUntypedBase();
  3417. // Attempts to move the generator to the next element
  3418. //
  3419. // Returns true iff the move succeeded (and a valid element
  3420. // can be retrieved).
  3421. virtual bool next() = 0;
  3422. };
  3423. using GeneratorBasePtr = std::unique_ptr<GeneratorUntypedBase>;
  3424. } // namespace Generators
  3425. struct IGeneratorTracker
  3426. {
  3427. virtual ~IGeneratorTracker();
  3428. virtual auto hasGenerator() const -> bool = 0;
  3429. virtual auto getGenerator() const -> Generators::GeneratorBasePtr const & = 0;
  3430. virtual void setGenerator(Generators::GeneratorBasePtr &&generator) = 0;
  3431. };
  3432. } // namespace Catch
  3433. // end catch_interfaces_generatortracker.h
  3434. // start catch_enforce.h
  3435. #include <exception>
  3436. namespace Catch {
  3437. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  3438. template<typename Ex>
  3439. [[noreturn]]
  3440. void throw_exception(Ex const &e)
  3441. {
  3442. throw e;
  3443. }
  3444. #else // ^^ Exceptions are enabled // Exceptions are disabled vv
  3445. [[noreturn]]
  3446. void throw_exception(std::exception const& e);
  3447. #endif
  3448. [[noreturn]]
  3449. void throw_logic_error(std::string const &msg);
  3450. [[noreturn]]
  3451. void throw_domain_error(std::string const &msg);
  3452. [[noreturn]]
  3453. void throw_runtime_error(std::string const &msg);
  3454. } // namespace Catch;
  3455. #define CATCH_MAKE_MSG(...) \
  3456. (Catch::ReusableStringStream() << __VA_ARGS__).str()
  3457. #define CATCH_INTERNAL_ERROR(...) \
  3458. Catch::throw_logic_error(CATCH_MAKE_MSG( CATCH_INTERNAL_LINEINFO << ": Internal Catch2 error: " << __VA_ARGS__));
  3459. #define CATCH_ERROR(...) \
  3460. Catch::throw_domain_error(CATCH_MAKE_MSG( __VA_ARGS__ ));
  3461. #define CATCH_RUNTIME_ERROR(...) \
  3462. Catch::throw_runtime_error(CATCH_MAKE_MSG( __VA_ARGS__ ));
  3463. #define CATCH_ENFORCE(condition, ...) \
  3464. do{ if( !(condition) ) CATCH_ERROR( __VA_ARGS__ ); } while(false)
  3465. // end catch_enforce.h
  3466. #include <memory>
  3467. #include <vector>
  3468. #include <cassert>
  3469. #include <utility>
  3470. #include <exception>
  3471. namespace Catch {
  3472. class GeneratorException : public std::exception
  3473. {
  3474. const char *const m_msg = "";
  3475. public:
  3476. GeneratorException(const char *msg) :
  3477. m_msg(msg)
  3478. {}
  3479. const char *what() const noexcept override final;
  3480. };
  3481. namespace Generators {
  3482. // !TBD move this into its own location?
  3483. namespace pf {
  3484. template<typename T, typename... Args>
  3485. std::unique_ptr<T> make_unique(Args &&... args)
  3486. {
  3487. return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
  3488. }
  3489. }
  3490. template<typename T>
  3491. struct IGenerator : GeneratorUntypedBase
  3492. {
  3493. virtual ~IGenerator() = default;
  3494. // Returns the current element of the generator
  3495. //
  3496. // \Precondition The generator is either freshly constructed,
  3497. // or the last call to `next()` returned true
  3498. virtual T const &get() const = 0;
  3499. using type = T;
  3500. };
  3501. template<typename T>
  3502. class SingleValueGenerator final : public IGenerator<T>
  3503. {
  3504. T m_value;
  3505. public:
  3506. SingleValueGenerator(T const &value) : m_value(value)
  3507. {}
  3508. SingleValueGenerator(T &&value) : m_value(std::move(value))
  3509. {}
  3510. T const &get() const override
  3511. {
  3512. return m_value;
  3513. }
  3514. bool next() override
  3515. {
  3516. return false;
  3517. }
  3518. };
  3519. template<typename T>
  3520. class FixedValuesGenerator final : public IGenerator<T>
  3521. {
  3522. static_assert(!std::is_same<T, bool>::value,
  3523. "ValuesGenerator does not support bools because of std::vector<bool>"
  3524. "specialization, use SingleValue Generator instead.");
  3525. std::vector<T> m_values;
  3526. size_t m_idx = 0;
  3527. public:
  3528. FixedValuesGenerator(std::initializer_list<T> values) : m_values(values)
  3529. {}
  3530. T const &get() const override
  3531. {
  3532. return m_values[m_idx];
  3533. }
  3534. bool next() override
  3535. {
  3536. ++m_idx;
  3537. return m_idx < m_values.size();
  3538. }
  3539. };
  3540. template<typename T>
  3541. class GeneratorWrapper final
  3542. {
  3543. std::unique_ptr<IGenerator<T>> m_generator;
  3544. public:
  3545. GeneratorWrapper(std::unique_ptr<IGenerator<T>> generator) :
  3546. m_generator(std::move(generator))
  3547. {}
  3548. T const &get() const
  3549. {
  3550. return m_generator->get();
  3551. }
  3552. bool next()
  3553. {
  3554. return m_generator->next();
  3555. }
  3556. };
  3557. template<typename T>
  3558. GeneratorWrapper<T> value(T &&value)
  3559. {
  3560. return GeneratorWrapper<T>(pf::make_unique<SingleValueGenerator<T>>(std::forward<T>(value)));
  3561. }
  3562. template<typename T>
  3563. GeneratorWrapper<T> values(std::initializer_list<T> values)
  3564. {
  3565. return GeneratorWrapper<T>(pf::make_unique<FixedValuesGenerator<T>>(values));
  3566. }
  3567. template<typename T>
  3568. class Generators : public IGenerator<T>
  3569. {
  3570. std::vector<GeneratorWrapper<T>> m_generators;
  3571. size_t m_current = 0;
  3572. void populate(GeneratorWrapper<T> &&generator)
  3573. {
  3574. m_generators.emplace_back(std::move(generator));
  3575. }
  3576. void populate(T &&val)
  3577. {
  3578. m_generators.emplace_back(value(std::move(val)));
  3579. }
  3580. template<typename U>
  3581. void populate(U &&val)
  3582. {
  3583. populate(T(std::move(val)));
  3584. }
  3585. template<typename U, typename... Gs>
  3586. void populate(U &&valueOrGenerator, Gs... moreGenerators)
  3587. {
  3588. populate(std::forward<U>(valueOrGenerator));
  3589. populate(std::forward<Gs>(moreGenerators)...);
  3590. }
  3591. public:
  3592. template<typename... Gs>
  3593. Generators(Gs... moreGenerators)
  3594. {
  3595. m_generators.reserve(sizeof...(Gs));
  3596. populate(std::forward<Gs>(moreGenerators)...);
  3597. }
  3598. T const &get() const override
  3599. {
  3600. return m_generators[m_current].get();
  3601. }
  3602. bool next() override
  3603. {
  3604. if (m_current >= m_generators.size()) {
  3605. return false;
  3606. }
  3607. const bool current_status = m_generators[m_current].next();
  3608. if (!current_status) {
  3609. ++m_current;
  3610. }
  3611. return m_current < m_generators.size();
  3612. }
  3613. };
  3614. template<typename... Ts>
  3615. GeneratorWrapper<std::tuple<Ts...>> table(std::initializer_list<std::tuple<typename std::decay<Ts>::type...>> tuples)
  3616. {
  3617. return values<std::tuple<Ts...>>(tuples);
  3618. }
  3619. // Tag type to signal that a generator sequence should convert arguments to a specific type
  3620. template<typename T>
  3621. struct as
  3622. {
  3623. };
  3624. template<typename T, typename... Gs>
  3625. auto makeGenerators(GeneratorWrapper<T> &&generator, Gs... moreGenerators) -> Generators<T>
  3626. {
  3627. return Generators<T>(std::move(generator), std::forward<Gs>(moreGenerators)...);
  3628. }
  3629. template<typename T>
  3630. auto makeGenerators(GeneratorWrapper<T> &&generator) -> Generators<T>
  3631. {
  3632. return Generators<T>(std::move(generator));
  3633. }
  3634. template<typename T, typename... Gs>
  3635. auto makeGenerators(T &&val, Gs... moreGenerators) -> Generators<T>
  3636. {
  3637. return makeGenerators(value(std::forward<T>(val)), std::forward<Gs>(moreGenerators)...);
  3638. }
  3639. template<typename T, typename U, typename... Gs>
  3640. auto makeGenerators(as<T>, U &&val, Gs... moreGenerators) -> Generators<T>
  3641. {
  3642. return makeGenerators(value(T(std::forward<U>(val))), std::forward<Gs>(moreGenerators)...);
  3643. }
  3644. auto acquireGeneratorTracker(SourceLineInfo const &lineInfo) -> IGeneratorTracker &;
  3645. template<typename L>
  3646. // Note: The type after -> is weird, because VS2015 cannot parse
  3647. // the expression used in the typedef inside, when it is in
  3648. // return type. Yeah.
  3649. auto generate(SourceLineInfo const &lineInfo,
  3650. L const &generatorExpression) -> decltype(std::declval<decltype(generatorExpression())>()
  3651. .get())
  3652. {
  3653. using UnderlyingType = typename decltype(generatorExpression())::type;
  3654. IGeneratorTracker &tracker = acquireGeneratorTracker(lineInfo);
  3655. if (!tracker.hasGenerator()) {
  3656. tracker.setGenerator(pf::make_unique<Generators<UnderlyingType>>(generatorExpression()));
  3657. }
  3658. auto const &generator = static_cast<IGenerator<UnderlyingType> const &>( *tracker.getGenerator());
  3659. return generator.get();
  3660. }
  3661. } // namespace Generators
  3662. } // namespace Catch
  3663. #define GENERATE(...) \
  3664. Catch::Generators::generate( CATCH_INTERNAL_LINEINFO, [ ]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } )
  3665. #define GENERATE_COPY(...) \
  3666. Catch::Generators::generate( CATCH_INTERNAL_LINEINFO, [=]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } )
  3667. #define GENERATE_REF(...) \
  3668. Catch::Generators::generate( CATCH_INTERNAL_LINEINFO, [&]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } )
  3669. // end catch_generators.hpp
  3670. // start catch_generators_generic.hpp
  3671. namespace Catch {
  3672. namespace Generators {
  3673. template<typename T>
  3674. class TakeGenerator : public IGenerator<T>
  3675. {
  3676. GeneratorWrapper<T> m_generator;
  3677. size_t m_returned = 0;
  3678. size_t m_target;
  3679. public:
  3680. TakeGenerator(size_t target, GeneratorWrapper<T> &&generator) :
  3681. m_generator(std::move(generator)),
  3682. m_target(target)
  3683. {
  3684. assert(target != 0 && "Empty generators are not allowed");
  3685. }
  3686. T const &get() const override
  3687. {
  3688. return m_generator.get();
  3689. }
  3690. bool next() override
  3691. {
  3692. ++m_returned;
  3693. if (m_returned >= m_target) {
  3694. return false;
  3695. }
  3696. const auto success = m_generator.next();
  3697. // If the underlying generator does not contain enough values
  3698. // then we cut short as well
  3699. if (!success) {
  3700. m_returned = m_target;
  3701. }
  3702. return success;
  3703. }
  3704. };
  3705. template<typename T>
  3706. GeneratorWrapper<T> take(size_t target, GeneratorWrapper<T> &&generator)
  3707. {
  3708. return GeneratorWrapper<T>(pf::make_unique<TakeGenerator<T>>(target, std::move(generator)));
  3709. }
  3710. template<typename T, typename Predicate>
  3711. class FilterGenerator : public IGenerator<T>
  3712. {
  3713. GeneratorWrapper<T> m_generator;
  3714. Predicate m_predicate;
  3715. public:
  3716. template<typename P = Predicate>
  3717. FilterGenerator(P &&pred, GeneratorWrapper<T> &&generator):
  3718. m_generator(std::move(generator)),
  3719. m_predicate(std::forward<P>(pred))
  3720. {
  3721. if (!m_predicate(m_generator.get())) {
  3722. // It might happen that there are no values that pass the
  3723. // filter. In that case we throw an exception.
  3724. auto has_initial_value = next();
  3725. if (!has_initial_value) {
  3726. Catch::throw_exception(GeneratorException("No valid value found in filtered generator"));
  3727. }
  3728. }
  3729. }
  3730. T const &get() const override
  3731. {
  3732. return m_generator.get();
  3733. }
  3734. bool next() override
  3735. {
  3736. bool success = m_generator.next();
  3737. if (!success) {
  3738. return false;
  3739. }
  3740. while (!m_predicate(m_generator.get()) && (success = m_generator.next()) == true);
  3741. return success;
  3742. }
  3743. };
  3744. template<typename T, typename Predicate>
  3745. GeneratorWrapper<T> filter(Predicate &&pred, GeneratorWrapper<T> &&generator)
  3746. {
  3747. return GeneratorWrapper<T>(std::unique_ptr<IGenerator<T>>(pf::make_unique<FilterGenerator<T,
  3748. Predicate>>(
  3749. std::forward<Predicate>(pred),
  3750. std::move(generator))));
  3751. }
  3752. template<typename T>
  3753. class RepeatGenerator : public IGenerator<T>
  3754. {
  3755. static_assert(!std::is_same<T, bool>::value,
  3756. "RepeatGenerator currently does not support bools"
  3757. "because of std::vector<bool> specialization");
  3758. GeneratorWrapper<T> m_generator;
  3759. mutable std::vector<T> m_returned;
  3760. size_t m_target_repeats;
  3761. size_t m_current_repeat = 0;
  3762. size_t m_repeat_index = 0;
  3763. public:
  3764. RepeatGenerator(size_t repeats, GeneratorWrapper<T> &&generator) :
  3765. m_generator(std::move(generator)),
  3766. m_target_repeats(repeats)
  3767. {
  3768. assert(m_target_repeats > 0 && "Repeat generator must repeat at least once");
  3769. }
  3770. T const &get() const override
  3771. {
  3772. if (m_current_repeat == 0) {
  3773. m_returned.push_back(m_generator.get());
  3774. return m_returned.back();
  3775. }
  3776. return m_returned[m_repeat_index];
  3777. }
  3778. bool next() override
  3779. {
  3780. // There are 2 basic cases:
  3781. // 1) We are still reading the generator
  3782. // 2) We are reading our own cache
  3783. // In the first case, we need to poke the underlying generator.
  3784. // If it happily moves, we are left in that state, otherwise it is time to start reading from our cache
  3785. if (m_current_repeat == 0) {
  3786. const auto success = m_generator.next();
  3787. if (!success) {
  3788. ++m_current_repeat;
  3789. }
  3790. return m_current_repeat < m_target_repeats;
  3791. }
  3792. // In the second case, we need to move indices forward and check that we haven't run up against the end
  3793. ++m_repeat_index;
  3794. if (m_repeat_index == m_returned.size()) {
  3795. m_repeat_index = 0;
  3796. ++m_current_repeat;
  3797. }
  3798. return m_current_repeat < m_target_repeats;
  3799. }
  3800. };
  3801. template<typename T>
  3802. GeneratorWrapper<T> repeat(size_t repeats, GeneratorWrapper<T> &&generator)
  3803. {
  3804. return GeneratorWrapper<T>(pf::make_unique<RepeatGenerator<T>>(repeats, std::move(generator)));
  3805. }
  3806. template<typename T, typename U, typename Func>
  3807. class MapGenerator : public IGenerator<T>
  3808. {
  3809. // TBD: provide static assert for mapping function, for friendly error message
  3810. GeneratorWrapper<U> m_generator;
  3811. Func m_function;
  3812. // To avoid returning dangling reference, we have to save the values
  3813. T m_cache;
  3814. public:
  3815. template<typename F2 = Func>
  3816. MapGenerator(F2 &&function, GeneratorWrapper<U> &&generator) :
  3817. m_generator(std::move(generator)),
  3818. m_function(std::forward<F2>(function)),
  3819. m_cache(m_function(m_generator.get()))
  3820. {}
  3821. T const &get() const override
  3822. {
  3823. return m_cache;
  3824. }
  3825. bool next() override
  3826. {
  3827. const auto success = m_generator.next();
  3828. if (success) {
  3829. m_cache = m_function(m_generator.get());
  3830. }
  3831. return success;
  3832. }
  3833. };
  3834. #if defined(__cpp_lib_is_invocable) && __cpp_lib_is_invocable >= 201703
  3835. // std::result_of is deprecated in C++17 and removed in C++20. Hence, it is
  3836. // replaced with std::invoke_result here. Also *_t format is preferred over
  3837. // typename *::type format.
  3838. template <typename Func, typename U>
  3839. using MapFunctionReturnType = std::remove_reference_t<std::remove_cv_t<std::invoke_result_t<Func, U>>>;
  3840. #else
  3841. template<typename Func, typename U>
  3842. using MapFunctionReturnType = typename std::remove_reference<typename std::remove_cv<typename std::result_of<
  3843. Func(U)>::type>::type>::type;
  3844. #endif
  3845. template<typename Func, typename U, typename T = MapFunctionReturnType<Func, U>>
  3846. GeneratorWrapper<T> map(Func &&function, GeneratorWrapper<U> &&generator)
  3847. {
  3848. return GeneratorWrapper<T>(
  3849. pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(function), std::move(generator))
  3850. );
  3851. }
  3852. template<typename T, typename U, typename Func>
  3853. GeneratorWrapper<T> map(Func &&function, GeneratorWrapper<U> &&generator)
  3854. {
  3855. return GeneratorWrapper<T>(
  3856. pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(function), std::move(generator))
  3857. );
  3858. }
  3859. template<typename T>
  3860. class ChunkGenerator final : public IGenerator<std::vector<T>>
  3861. {
  3862. std::vector<T> m_chunk;
  3863. size_t m_chunk_size;
  3864. GeneratorWrapper<T> m_generator;
  3865. bool m_used_up = false;
  3866. public:
  3867. ChunkGenerator(size_t size, GeneratorWrapper<T> generator) :
  3868. m_chunk_size(size), m_generator(std::move(generator))
  3869. {
  3870. m_chunk.reserve(m_chunk_size);
  3871. if (m_chunk_size != 0) {
  3872. m_chunk.push_back(m_generator.get());
  3873. for (size_t i = 1; i < m_chunk_size; ++i) {
  3874. if (!m_generator.next()) {
  3875. Catch::throw_exception(GeneratorException(
  3876. "Not enough values to initialize the first chunk"));
  3877. }
  3878. m_chunk.push_back(m_generator.get());
  3879. }
  3880. }
  3881. }
  3882. std::vector<T> const &get() const override
  3883. {
  3884. return m_chunk;
  3885. }
  3886. bool next() override
  3887. {
  3888. m_chunk.clear();
  3889. for (size_t idx = 0; idx < m_chunk_size; ++idx) {
  3890. if (!m_generator.next()) {
  3891. return false;
  3892. }
  3893. m_chunk.push_back(m_generator.get());
  3894. }
  3895. return true;
  3896. }
  3897. };
  3898. template<typename T>
  3899. GeneratorWrapper<std::vector<T>> chunk(size_t size, GeneratorWrapper<T> &&generator)
  3900. {
  3901. return GeneratorWrapper<std::vector<T>>(
  3902. pf::make_unique<ChunkGenerator<T>>(size, std::move(generator))
  3903. );
  3904. }
  3905. } // namespace Generators
  3906. } // namespace Catch
  3907. // end catch_generators_generic.hpp
  3908. // start catch_generators_specific.hpp
  3909. // start catch_context.h
  3910. #include <memory>
  3911. namespace Catch {
  3912. struct IResultCapture;
  3913. struct IRunner;
  3914. struct IConfig;
  3915. struct IMutableContext;
  3916. using IConfigPtr = std::shared_ptr<IConfig const>;
  3917. struct IContext
  3918. {
  3919. virtual ~IContext();
  3920. virtual IResultCapture *getResultCapture() = 0;
  3921. virtual IRunner *getRunner() = 0;
  3922. virtual IConfigPtr const &getConfig() const = 0;
  3923. };
  3924. struct IMutableContext : IContext
  3925. {
  3926. virtual ~IMutableContext();
  3927. virtual void setResultCapture(IResultCapture *resultCapture) = 0;
  3928. virtual void setRunner(IRunner *runner) = 0;
  3929. virtual void setConfig(IConfigPtr const &config) = 0;
  3930. private:
  3931. static IMutableContext *currentContext;
  3932. friend IMutableContext &getCurrentMutableContext();
  3933. friend void cleanUpContext();
  3934. static void createContext();
  3935. };
  3936. inline IMutableContext &getCurrentMutableContext()
  3937. {
  3938. if (!IMutableContext::currentContext)
  3939. IMutableContext::createContext();
  3940. return *IMutableContext::currentContext;
  3941. }
  3942. inline IContext &getCurrentContext()
  3943. {
  3944. return getCurrentMutableContext();
  3945. }
  3946. void cleanUpContext();
  3947. }
  3948. // end catch_context.h
  3949. // start catch_interfaces_config.h
  3950. // start catch_option.hpp
  3951. namespace Catch {
  3952. // An optional type
  3953. template<typename T>
  3954. class Option
  3955. {
  3956. public:
  3957. Option() : nullableValue(nullptr)
  3958. {}
  3959. Option(T const &_value)
  3960. : nullableValue(new(storage) T(_value))
  3961. {}
  3962. Option(Option const &_other)
  3963. : nullableValue(_other ? new(storage) T(*_other) : nullptr)
  3964. {}
  3965. ~Option()
  3966. {
  3967. reset();
  3968. }
  3969. Option &operator=(Option const &_other)
  3970. {
  3971. if (&_other != this) {
  3972. reset();
  3973. if (_other)
  3974. nullableValue = new(storage) T(*_other);
  3975. }
  3976. return *this;
  3977. }
  3978. Option &operator=(T const &_value)
  3979. {
  3980. reset();
  3981. nullableValue = new(storage) T(_value);
  3982. return *this;
  3983. }
  3984. void reset()
  3985. {
  3986. if (nullableValue)
  3987. nullableValue->~T();
  3988. nullableValue = nullptr;
  3989. }
  3990. T &operator*()
  3991. { return *nullableValue; }
  3992. T const &operator*() const
  3993. { return *nullableValue; }
  3994. T *operator->()
  3995. { return nullableValue; }
  3996. const T *operator->() const
  3997. { return nullableValue; }
  3998. T valueOr(T const &defaultValue) const
  3999. {
  4000. return nullableValue ? *nullableValue : defaultValue;
  4001. }
  4002. bool some() const
  4003. { return nullableValue != nullptr; }
  4004. bool none() const
  4005. { return nullableValue == nullptr; }
  4006. bool operator!() const
  4007. { return nullableValue == nullptr; }
  4008. explicit operator bool() const
  4009. {
  4010. return some();
  4011. }
  4012. private:
  4013. T *nullableValue;
  4014. alignas(alignof(T)) char storage[sizeof(T)];
  4015. };
  4016. } // end namespace Catch
  4017. // end catch_option.hpp
  4018. #include <iosfwd>
  4019. #include <string>
  4020. #include <vector>
  4021. #include <memory>
  4022. namespace Catch {
  4023. enum class Verbosity
  4024. {
  4025. Quiet = 0,
  4026. Normal,
  4027. High
  4028. };
  4029. struct WarnAbout
  4030. {
  4031. enum What
  4032. {
  4033. Nothing = 0x00,
  4034. NoAssertions = 0x01,
  4035. NoTests = 0x02
  4036. };
  4037. };
  4038. struct ShowDurations
  4039. {
  4040. enum OrNot
  4041. {
  4042. DefaultForReporter,
  4043. Always,
  4044. Never
  4045. };
  4046. };
  4047. struct RunTests
  4048. {
  4049. enum InWhatOrder
  4050. {
  4051. InDeclarationOrder,
  4052. InLexicographicalOrder,
  4053. InRandomOrder
  4054. };
  4055. };
  4056. struct UseColour
  4057. {
  4058. enum YesOrNo
  4059. {
  4060. Auto,
  4061. Yes,
  4062. No
  4063. };
  4064. };
  4065. struct WaitForKeypress
  4066. {
  4067. enum When
  4068. {
  4069. Never,
  4070. BeforeStart = 1,
  4071. BeforeExit = 2,
  4072. BeforeStartAndExit = BeforeStart | BeforeExit
  4073. };
  4074. };
  4075. class TestSpec;
  4076. struct IConfig : NonCopyable
  4077. {
  4078. virtual ~IConfig();
  4079. virtual bool allowThrows() const = 0;
  4080. virtual std::ostream &stream() const = 0;
  4081. virtual std::string name() const = 0;
  4082. virtual bool includeSuccessfulResults() const = 0;
  4083. virtual bool shouldDebugBreak() const = 0;
  4084. virtual bool warnAboutMissingAssertions() const = 0;
  4085. virtual bool warnAboutNoTests() const = 0;
  4086. virtual int abortAfter() const = 0;
  4087. virtual bool showInvisibles() const = 0;
  4088. virtual ShowDurations::OrNot showDurations() const = 0;
  4089. virtual TestSpec const &testSpec() const = 0;
  4090. virtual bool hasTestFilters() const = 0;
  4091. virtual std::vector<std::string> const &getTestsOrTags() const = 0;
  4092. virtual RunTests::InWhatOrder runOrder() const = 0;
  4093. virtual unsigned int rngSeed() const = 0;
  4094. virtual UseColour::YesOrNo useColour() const = 0;
  4095. virtual std::vector<std::string> const &getSectionsToRun() const = 0;
  4096. virtual Verbosity verbosity() const = 0;
  4097. virtual bool benchmarkNoAnalysis() const = 0;
  4098. virtual int benchmarkSamples() const = 0;
  4099. virtual double benchmarkConfidenceInterval() const = 0;
  4100. virtual unsigned int benchmarkResamples() const = 0;
  4101. };
  4102. using IConfigPtr = std::shared_ptr<IConfig const>;
  4103. }
  4104. // end catch_interfaces_config.h
  4105. #include <random>
  4106. namespace Catch {
  4107. namespace Generators {
  4108. template<typename Float>
  4109. class RandomFloatingGenerator final : public IGenerator<Float>
  4110. {
  4111. // FIXME: What is the right seed?
  4112. std::minstd_rand m_rand;
  4113. std::uniform_real_distribution<Float> m_dist;
  4114. Float m_current_number;
  4115. public:
  4116. RandomFloatingGenerator(Float a, Float b) :
  4117. m_rand(getCurrentContext().getConfig()->rngSeed()),
  4118. m_dist(a, b)
  4119. {
  4120. static_cast<void>(next());
  4121. }
  4122. Float const &get() const override
  4123. {
  4124. return m_current_number;
  4125. }
  4126. bool next() override
  4127. {
  4128. m_current_number = m_dist(m_rand);
  4129. return true;
  4130. }
  4131. };
  4132. template<typename Integer>
  4133. class RandomIntegerGenerator final : public IGenerator<Integer>
  4134. {
  4135. std::minstd_rand m_rand;
  4136. std::uniform_int_distribution<Integer> m_dist;
  4137. Integer m_current_number;
  4138. public:
  4139. RandomIntegerGenerator(Integer a, Integer b) :
  4140. m_rand(getCurrentContext().getConfig()->rngSeed()),
  4141. m_dist(a, b)
  4142. {
  4143. static_cast<void>(next());
  4144. }
  4145. Integer const &get() const override
  4146. {
  4147. return m_current_number;
  4148. }
  4149. bool next() override
  4150. {
  4151. m_current_number = m_dist(m_rand);
  4152. return true;
  4153. }
  4154. };
  4155. // TODO: Ideally this would be also constrained against the various char types,
  4156. // but I don't expect users to run into that in practice.
  4157. template<typename T>
  4158. typename std::enable_if<std::is_integral<T>::value && !std::is_same<T, bool>::value,
  4159. GeneratorWrapper<T>>::type
  4160. random(T a, T b)
  4161. {
  4162. return GeneratorWrapper<T>(
  4163. pf::make_unique<RandomIntegerGenerator<T>>(a, b)
  4164. );
  4165. }
  4166. template<typename T>
  4167. typename std::enable_if<std::is_floating_point<T>::value,
  4168. GeneratorWrapper<T>>::type
  4169. random(T a, T b)
  4170. {
  4171. return GeneratorWrapper<T>(
  4172. pf::make_unique<RandomFloatingGenerator<T>>(a, b)
  4173. );
  4174. }
  4175. template<typename T>
  4176. class RangeGenerator final : public IGenerator<T>
  4177. {
  4178. T m_current;
  4179. T m_end;
  4180. T m_step;
  4181. bool m_positive;
  4182. public:
  4183. RangeGenerator(T const &start, T const &end, T const &step) :
  4184. m_current(start),
  4185. m_end(end),
  4186. m_step(step),
  4187. m_positive(m_step > T(0))
  4188. {
  4189. assert(m_current != m_end && "Range start and end cannot be equal");
  4190. assert(m_step != T(0) && "Step size cannot be zero");
  4191. assert(((m_positive && m_current <= m_end) || (!m_positive && m_current >= m_end))
  4192. && "Step moves away from end");
  4193. }
  4194. RangeGenerator(T const &start, T const &end) :
  4195. RangeGenerator(start, end, (start < end) ? T(1) : T(-1))
  4196. {}
  4197. T const &get() const override
  4198. {
  4199. return m_current;
  4200. }
  4201. bool next() override
  4202. {
  4203. m_current += m_step;
  4204. return (m_positive) ? (m_current < m_end) : (m_current > m_end);
  4205. }
  4206. };
  4207. template<typename T>
  4208. GeneratorWrapper<T> range(T const &start, T const &end, T const &step)
  4209. {
  4210. static_assert(std::is_integral<T>::value && !std::is_same<T, bool>::value,
  4211. "Type must be an integer");
  4212. return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end, step));
  4213. }
  4214. template<typename T>
  4215. GeneratorWrapper<T> range(T const &start, T const &end)
  4216. {
  4217. static_assert(std::is_integral<T>::value && !std::is_same<T, bool>::value,
  4218. "Type must be an integer");
  4219. return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end));
  4220. }
  4221. } // namespace Generators
  4222. } // namespace Catch
  4223. // end catch_generators_specific.hpp
  4224. // These files are included here so the single_include script doesn't put them
  4225. // in the conditionally compiled sections
  4226. // start catch_test_case_info.h
  4227. #include <string>
  4228. #include <vector>
  4229. #include <memory>
  4230. #ifdef __clang__
  4231. #pragma clang diagnostic push
  4232. #pragma clang diagnostic ignored "-Wpadded"
  4233. #endif
  4234. namespace Catch {
  4235. struct ITestInvoker;
  4236. struct TestCaseInfo
  4237. {
  4238. enum SpecialProperties
  4239. {
  4240. None = 0,
  4241. IsHidden = 1 << 1,
  4242. ShouldFail = 1 << 2,
  4243. MayFail = 1 << 3,
  4244. Throws = 1 << 4,
  4245. NonPortable = 1 << 5,
  4246. Benchmark = 1 << 6
  4247. };
  4248. TestCaseInfo(std::string const &_name,
  4249. std::string const &_className,
  4250. std::string const &_description,
  4251. std::vector<std::string> const &_tags,
  4252. SourceLineInfo const &_lineInfo);
  4253. friend void setTags(TestCaseInfo &testCaseInfo, std::vector<std::string> tags);
  4254. bool isHidden() const;
  4255. bool throws() const;
  4256. bool okToFail() const;
  4257. bool expectedToFail() const;
  4258. std::string tagsAsString() const;
  4259. std::string name;
  4260. std::string className;
  4261. std::string description;
  4262. std::vector<std::string> tags;
  4263. std::vector<std::string> lcaseTags;
  4264. SourceLineInfo lineInfo;
  4265. SpecialProperties properties;
  4266. };
  4267. class TestCase : public TestCaseInfo
  4268. {
  4269. public:
  4270. TestCase(ITestInvoker *testCase, TestCaseInfo &&info);
  4271. TestCase withName(std::string const &_newName) const;
  4272. void invoke() const;
  4273. TestCaseInfo const &getTestCaseInfo() const;
  4274. bool operator==(TestCase const &other) const;
  4275. bool operator<(TestCase const &other) const;
  4276. private:
  4277. std::shared_ptr<ITestInvoker> test;
  4278. };
  4279. TestCase makeTestCase(ITestInvoker *testCase,
  4280. std::string const &className,
  4281. NameAndTags const &nameAndTags,
  4282. SourceLineInfo const &lineInfo);
  4283. }
  4284. #ifdef __clang__
  4285. #pragma clang diagnostic pop
  4286. #endif
  4287. // end catch_test_case_info.h
  4288. // start catch_interfaces_runner.h
  4289. namespace Catch {
  4290. struct IRunner
  4291. {
  4292. virtual ~IRunner();
  4293. virtual bool aborting() const = 0;
  4294. };
  4295. }
  4296. // end catch_interfaces_runner.h
  4297. #ifdef __OBJC__
  4298. // start catch_objc.hpp
  4299. #import <objc/runtime.h>
  4300. #include <string>
  4301. // NB. Any general catch headers included here must be included
  4302. // in catch.hpp first to make sure they are included by the single
  4303. // header for non obj-usage
  4304. ///////////////////////////////////////////////////////////////////////////////
  4305. // This protocol is really only here for (self) documenting purposes, since
  4306. // all its methods are optional.
  4307. @protocol OcFixture
  4308. @optional
  4309. -(void) setUp;
  4310. -(void) tearDown;
  4311. @end
  4312. namespace Catch {
  4313. class OcMethod : public ITestInvoker {
  4314. public:
  4315. OcMethod( Class cls, SEL sel ) : m_cls( cls ), m_sel( sel ) {}
  4316. virtual void invoke() const {
  4317. id obj = [[m_cls alloc] init];
  4318. performOptionalSelector( obj, @selector(setUp) );
  4319. performOptionalSelector( obj, m_sel );
  4320. performOptionalSelector( obj, @selector(tearDown) );
  4321. arcSafeRelease( obj );
  4322. }
  4323. private:
  4324. virtual ~OcMethod() {}
  4325. Class m_cls;
  4326. SEL m_sel;
  4327. };
  4328. namespace Detail{
  4329. inline std::string getAnnotation( Class cls,
  4330. std::string const& annotationName,
  4331. std::string const& testCaseName ) {
  4332. NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()];
  4333. SEL sel = NSSelectorFromString( selStr );
  4334. arcSafeRelease( selStr );
  4335. id value = performOptionalSelector( cls, sel );
  4336. if( value )
  4337. return [(NSString*)value UTF8String];
  4338. return "";
  4339. }
  4340. }
  4341. inline std::size_t registerTestMethods() {
  4342. std::size_t noTestMethods = 0;
  4343. int noClasses = objc_getClassList( nullptr, 0 );
  4344. Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc( sizeof(Class) * noClasses);
  4345. objc_getClassList( classes, noClasses );
  4346. for( int c = 0; c < noClasses; c++ ) {
  4347. Class cls = classes[c];
  4348. {
  4349. u_int count;
  4350. Method* methods = class_copyMethodList( cls, &count );
  4351. for( u_int m = 0; m < count ; m++ ) {
  4352. SEL selector = method_getName(methods[m]);
  4353. std::string methodName = sel_getName(selector);
  4354. if( startsWith( methodName, "Catch_TestCase_" ) ) {
  4355. std::string testCaseName = methodName.substr( 15 );
  4356. std::string name = Detail::getAnnotation( cls, "Name", testCaseName );
  4357. std::string desc = Detail::getAnnotation( cls, "Description", testCaseName );
  4358. const char* className = class_getName( cls );
  4359. getMutableRegistryHub().registerTest( makeTestCase( new OcMethod( cls, selector ), className, NameAndTags( name.c_str(), desc.c_str() ), SourceLineInfo("",0) ) );
  4360. noTestMethods++;
  4361. }
  4362. }
  4363. free(methods);
  4364. }
  4365. }
  4366. return noTestMethods;
  4367. }
  4368. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  4369. namespace Matchers {
  4370. namespace Impl {
  4371. namespace NSStringMatchers {
  4372. struct StringHolder : MatcherBase<NSString*>{
  4373. StringHolder( NSString* substr ) : m_substr( [substr copy] ){}
  4374. StringHolder( StringHolder const& other ) : m_substr( [other.m_substr copy] ){}
  4375. StringHolder() {
  4376. arcSafeRelease( m_substr );
  4377. }
  4378. bool match( NSString* str ) const override {
  4379. return false;
  4380. }
  4381. NSString* CATCH_ARC_STRONG m_substr;
  4382. };
  4383. struct Equals : StringHolder {
  4384. Equals( NSString* substr ) : StringHolder( substr ){}
  4385. bool match( NSString* str ) const override {
  4386. return (str != nil || m_substr == nil ) &&
  4387. [str isEqualToString:m_substr];
  4388. }
  4389. std::string describe() const override {
  4390. return "equals string: " + Catch::Detail::stringify( m_substr );
  4391. }
  4392. };
  4393. struct Contains : StringHolder {
  4394. Contains( NSString* substr ) : StringHolder( substr ){}
  4395. bool match( NSString* str ) const override {
  4396. return (str != nil || m_substr == nil ) &&
  4397. [str rangeOfString:m_substr].location != NSNotFound;
  4398. }
  4399. std::string describe() const override {
  4400. return "contains string: " + Catch::Detail::stringify( m_substr );
  4401. }
  4402. };
  4403. struct StartsWith : StringHolder {
  4404. StartsWith( NSString* substr ) : StringHolder( substr ){}
  4405. bool match( NSString* str ) const override {
  4406. return (str != nil || m_substr == nil ) &&
  4407. [str rangeOfString:m_substr].location == 0;
  4408. }
  4409. std::string describe() const override {
  4410. return "starts with: " + Catch::Detail::stringify( m_substr );
  4411. }
  4412. };
  4413. struct EndsWith : StringHolder {
  4414. EndsWith( NSString* substr ) : StringHolder( substr ){}
  4415. bool match( NSString* str ) const override {
  4416. return (str != nil || m_substr == nil ) &&
  4417. [str rangeOfString:m_substr].location == [str length] - [m_substr length];
  4418. }
  4419. std::string describe() const override {
  4420. return "ends with: " + Catch::Detail::stringify( m_substr );
  4421. }
  4422. };
  4423. } // namespace NSStringMatchers
  4424. } // namespace Impl
  4425. inline Impl::NSStringMatchers::Equals
  4426. Equals( NSString* substr ){ return Impl::NSStringMatchers::Equals( substr ); }
  4427. inline Impl::NSStringMatchers::Contains
  4428. Contains( NSString* substr ){ return Impl::NSStringMatchers::Contains( substr ); }
  4429. inline Impl::NSStringMatchers::StartsWith
  4430. StartsWith( NSString* substr ){ return Impl::NSStringMatchers::StartsWith( substr ); }
  4431. inline Impl::NSStringMatchers::EndsWith
  4432. EndsWith( NSString* substr ){ return Impl::NSStringMatchers::EndsWith( substr ); }
  4433. } // namespace Matchers
  4434. using namespace Matchers;
  4435. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  4436. } // namespace Catch
  4437. ///////////////////////////////////////////////////////////////////////////////
  4438. #define OC_MAKE_UNIQUE_NAME( root, uniqueSuffix ) root##uniqueSuffix
  4439. #define OC_TEST_CASE2( name, desc, uniqueSuffix ) \
  4440. +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Name_test_, uniqueSuffix ) \
  4441. { \
  4442. return @ name; \
  4443. } \
  4444. +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Description_test_, uniqueSuffix ) \
  4445. { \
  4446. return @ desc; \
  4447. } \
  4448. -(void) OC_MAKE_UNIQUE_NAME( Catch_TestCase_test_, uniqueSuffix )
  4449. #define OC_TEST_CASE( name, desc ) OC_TEST_CASE2( name, desc, __LINE__ )
  4450. // end catch_objc.hpp
  4451. #endif
  4452. // Benchmarking needs the externally-facing parts of reporters to work
  4453. #if defined(CATCH_CONFIG_EXTERNAL_INTERFACES) || defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  4454. // start catch_external_interfaces.h
  4455. // start catch_reporter_bases.hpp
  4456. // start catch_interfaces_reporter.h
  4457. // start catch_config.hpp
  4458. // start catch_test_spec_parser.h
  4459. #ifdef __clang__
  4460. #pragma clang diagnostic push
  4461. #pragma clang diagnostic ignored "-Wpadded"
  4462. #endif
  4463. // start catch_test_spec.h
  4464. #ifdef __clang__
  4465. #pragma clang diagnostic push
  4466. #pragma clang diagnostic ignored "-Wpadded"
  4467. #endif
  4468. // start catch_wildcard_pattern.h
  4469. namespace Catch
  4470. {
  4471. class WildcardPattern {
  4472. enum WildcardPosition {
  4473. NoWildcard = 0,
  4474. WildcardAtStart = 1,
  4475. WildcardAtEnd = 2,
  4476. WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd
  4477. };
  4478. public:
  4479. WildcardPattern( std::string const& pattern, CaseSensitive::Choice caseSensitivity );
  4480. virtual ~WildcardPattern() = default;
  4481. virtual bool matches( std::string const& str ) const;
  4482. private:
  4483. std::string adjustCase( std::string const& str ) const;
  4484. CaseSensitive::Choice m_caseSensitivity;
  4485. WildcardPosition m_wildcard = NoWildcard;
  4486. std::string m_pattern;
  4487. };
  4488. }
  4489. // end catch_wildcard_pattern.h
  4490. #include <string>
  4491. #include <vector>
  4492. #include <memory>
  4493. namespace Catch {
  4494. struct IConfig;
  4495. class TestSpec {
  4496. class Pattern {
  4497. public:
  4498. explicit Pattern( std::string const& name );
  4499. virtual ~Pattern();
  4500. virtual bool matches( TestCaseInfo const& testCase ) const = 0;
  4501. std::string const& name() const;
  4502. private:
  4503. std::string const m_name;
  4504. };
  4505. using PatternPtr = std::shared_ptr<Pattern>;
  4506. class NamePattern : public Pattern {
  4507. public:
  4508. explicit NamePattern( std::string const& name, std::string const& filterString );
  4509. bool matches( TestCaseInfo const& testCase ) const override;
  4510. private:
  4511. WildcardPattern m_wildcardPattern;
  4512. };
  4513. class TagPattern : public Pattern {
  4514. public:
  4515. explicit TagPattern( std::string const& tag, std::string const& filterString );
  4516. bool matches( TestCaseInfo const& testCase ) const override;
  4517. private:
  4518. std::string m_tag;
  4519. };
  4520. class ExcludedPattern : public Pattern {
  4521. public:
  4522. explicit ExcludedPattern( PatternPtr const& underlyingPattern );
  4523. bool matches( TestCaseInfo const& testCase ) const override;
  4524. private:
  4525. PatternPtr m_underlyingPattern;
  4526. };
  4527. struct Filter {
  4528. std::vector<PatternPtr> m_patterns;
  4529. bool matches( TestCaseInfo const& testCase ) const;
  4530. std::string name() const;
  4531. };
  4532. public:
  4533. struct FilterMatch {
  4534. std::string name;
  4535. std::vector<TestCase const*> tests;
  4536. };
  4537. using Matches = std::vector<FilterMatch>;
  4538. bool hasFilters() const;
  4539. bool matches( TestCaseInfo const& testCase ) const;
  4540. Matches matchesByFilter( std::vector<TestCase> const& testCases, IConfig const& config ) const;
  4541. private:
  4542. std::vector<Filter> m_filters;
  4543. friend class TestSpecParser;
  4544. };
  4545. }
  4546. #ifdef __clang__
  4547. #pragma clang diagnostic pop
  4548. #endif
  4549. // end catch_test_spec.h
  4550. // start catch_interfaces_tag_alias_registry.h
  4551. #include <string>
  4552. namespace Catch {
  4553. struct TagAlias;
  4554. struct ITagAliasRegistry {
  4555. virtual ~ITagAliasRegistry();
  4556. // Nullptr if not present
  4557. virtual TagAlias const* find( std::string const& alias ) const = 0;
  4558. virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const = 0;
  4559. static ITagAliasRegistry const& get();
  4560. };
  4561. } // end namespace Catch
  4562. // end catch_interfaces_tag_alias_registry.h
  4563. namespace Catch {
  4564. class TestSpecParser {
  4565. enum Mode{ None, Name, QuotedName, Tag, EscapedName };
  4566. Mode m_mode = None;
  4567. bool m_exclusion = false;
  4568. std::size_t m_pos = 0;
  4569. std::string m_arg;
  4570. std::string m_substring;
  4571. std::string m_patternName;
  4572. std::vector<std::size_t> m_escapeChars;
  4573. TestSpec::Filter m_currentFilter;
  4574. TestSpec m_testSpec;
  4575. ITagAliasRegistry const* m_tagAliases = nullptr;
  4576. public:
  4577. TestSpecParser( ITagAliasRegistry const& tagAliases );
  4578. TestSpecParser& parse( std::string const& arg );
  4579. TestSpec testSpec();
  4580. private:
  4581. void visitChar( char c );
  4582. void startNewMode( Mode mode );
  4583. bool processNoneChar( char c );
  4584. void processNameChar( char c );
  4585. bool processOtherChar( char c );
  4586. void endMode();
  4587. void escape();
  4588. bool isControlChar( char c ) const;
  4589. template<typename T>
  4590. void addPattern() {
  4591. std::string token = m_patternName;
  4592. for( std::size_t i = 0; i < m_escapeChars.size(); ++i )
  4593. token = token.substr( 0, m_escapeChars[i] - i ) + token.substr( m_escapeChars[i] -i +1 );
  4594. m_escapeChars.clear();
  4595. if( startsWith( token, "exclude:" ) ) {
  4596. m_exclusion = true;
  4597. token = token.substr( 8 );
  4598. }
  4599. if( !token.empty() ) {
  4600. TestSpec::PatternPtr pattern = std::make_shared<T>( token, m_substring );
  4601. if( m_exclusion )
  4602. pattern = std::make_shared<TestSpec::ExcludedPattern>( pattern );
  4603. m_currentFilter.m_patterns.push_back( pattern );
  4604. }
  4605. m_substring.clear();
  4606. m_patternName.clear();
  4607. m_exclusion = false;
  4608. m_mode = None;
  4609. }
  4610. void addFilter();
  4611. };
  4612. TestSpec parseTestSpec( std::string const& arg );
  4613. } // namespace Catch
  4614. #ifdef __clang__
  4615. #pragma clang diagnostic pop
  4616. #endif
  4617. // end catch_test_spec_parser.h
  4618. // Libstdc++ doesn't like incomplete classes for unique_ptr
  4619. #include <memory>
  4620. #include <vector>
  4621. #include <string>
  4622. #ifndef CATCH_CONFIG_CONSOLE_WIDTH
  4623. #define CATCH_CONFIG_CONSOLE_WIDTH 80
  4624. #endif
  4625. namespace Catch {
  4626. struct IStream;
  4627. struct ConfigData {
  4628. bool listTests = false;
  4629. bool listTags = false;
  4630. bool listReporters = false;
  4631. bool listTestNamesOnly = false;
  4632. bool showSuccessfulTests = false;
  4633. bool shouldDebugBreak = false;
  4634. bool noThrow = false;
  4635. bool showHelp = false;
  4636. bool showInvisibles = false;
  4637. bool filenamesAsTags = false;
  4638. bool libIdentify = false;
  4639. int abortAfter = -1;
  4640. unsigned int rngSeed = 0;
  4641. bool benchmarkNoAnalysis = false;
  4642. unsigned int benchmarkSamples = 100;
  4643. double benchmarkConfidenceInterval = 0.95;
  4644. unsigned int benchmarkResamples = 100000;
  4645. Verbosity verbosity = Verbosity::Normal;
  4646. WarnAbout::What warnings = WarnAbout::Nothing;
  4647. ShowDurations::OrNot showDurations = ShowDurations::DefaultForReporter;
  4648. RunTests::InWhatOrder runOrder = RunTests::InDeclarationOrder;
  4649. UseColour::YesOrNo useColour = UseColour::Auto;
  4650. WaitForKeypress::When waitForKeypress = WaitForKeypress::Never;
  4651. std::string outputFilename;
  4652. std::string name;
  4653. std::string processName;
  4654. #ifndef CATCH_CONFIG_DEFAULT_REPORTER
  4655. #define CATCH_CONFIG_DEFAULT_REPORTER "console"
  4656. #endif
  4657. std::string reporterName = CATCH_CONFIG_DEFAULT_REPORTER;
  4658. #undef CATCH_CONFIG_DEFAULT_REPORTER
  4659. std::vector<std::string> testsOrTags;
  4660. std::vector<std::string> sectionsToRun;
  4661. };
  4662. class Config : public IConfig {
  4663. public:
  4664. Config() = default;
  4665. Config( ConfigData const& data );
  4666. virtual ~Config() = default;
  4667. std::string const& getFilename() const;
  4668. bool listTests() const;
  4669. bool listTestNamesOnly() const;
  4670. bool listTags() const;
  4671. bool listReporters() const;
  4672. std::string getProcessName() const;
  4673. std::string const& getReporterName() const;
  4674. std::vector<std::string> const& getTestsOrTags() const override;
  4675. std::vector<std::string> const& getSectionsToRun() const override;
  4676. TestSpec const& testSpec() const override;
  4677. bool hasTestFilters() const override;
  4678. bool showHelp() const;
  4679. // IConfig interface
  4680. bool allowThrows() const override;
  4681. std::ostream& stream() const override;
  4682. std::string name() const override;
  4683. bool includeSuccessfulResults() const override;
  4684. bool warnAboutMissingAssertions() const override;
  4685. bool warnAboutNoTests() const override;
  4686. ShowDurations::OrNot showDurations() const override;
  4687. RunTests::InWhatOrder runOrder() const override;
  4688. unsigned int rngSeed() const override;
  4689. UseColour::YesOrNo useColour() const override;
  4690. bool shouldDebugBreak() const override;
  4691. int abortAfter() const override;
  4692. bool showInvisibles() const override;
  4693. Verbosity verbosity() const override;
  4694. bool benchmarkNoAnalysis() const override;
  4695. int benchmarkSamples() const override;
  4696. double benchmarkConfidenceInterval() const override;
  4697. unsigned int benchmarkResamples() const override;
  4698. private:
  4699. IStream const* openStream();
  4700. ConfigData m_data;
  4701. std::unique_ptr<IStream const> m_stream;
  4702. TestSpec m_testSpec;
  4703. bool m_hasTestFilters = false;
  4704. };
  4705. } // end namespace Catch
  4706. // end catch_config.hpp
  4707. // start catch_assertionresult.h
  4708. #include <string>
  4709. namespace Catch {
  4710. struct AssertionResultData
  4711. {
  4712. AssertionResultData() = delete;
  4713. AssertionResultData( ResultWas::OfType _resultType, LazyExpression const& _lazyExpression );
  4714. std::string message;
  4715. mutable std::string reconstructedExpression;
  4716. LazyExpression lazyExpression;
  4717. ResultWas::OfType resultType;
  4718. std::string reconstructExpression() const;
  4719. };
  4720. class AssertionResult {
  4721. public:
  4722. AssertionResult() = delete;
  4723. AssertionResult( AssertionInfo const& info, AssertionResultData const& data );
  4724. bool isOk() const;
  4725. bool succeeded() const;
  4726. ResultWas::OfType getResultType() const;
  4727. bool hasExpression() const;
  4728. bool hasMessage() const;
  4729. std::string getExpression() const;
  4730. std::string getExpressionInMacro() const;
  4731. bool hasExpandedExpression() const;
  4732. std::string getExpandedExpression() const;
  4733. std::string getMessage() const;
  4734. SourceLineInfo getSourceInfo() const;
  4735. StringRef getTestMacroName() const;
  4736. //protected:
  4737. AssertionInfo m_info;
  4738. AssertionResultData m_resultData;
  4739. };
  4740. } // end namespace Catch
  4741. // end catch_assertionresult.h
  4742. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  4743. // start catch_estimate.hpp
  4744. // Statistics estimates
  4745. namespace Catch {
  4746. namespace Benchmark {
  4747. template <typename Duration>
  4748. struct Estimate {
  4749. Duration point;
  4750. Duration lower_bound;
  4751. Duration upper_bound;
  4752. double confidence_interval;
  4753. template <typename Duration2>
  4754. operator Estimate<Duration2>() const {
  4755. return { point, lower_bound, upper_bound, confidence_interval };
  4756. }
  4757. };
  4758. } // namespace Benchmark
  4759. } // namespace Catch
  4760. // end catch_estimate.hpp
  4761. // start catch_outlier_classification.hpp
  4762. // Outlier information
  4763. namespace Catch {
  4764. namespace Benchmark {
  4765. struct OutlierClassification {
  4766. int samples_seen = 0;
  4767. int low_severe = 0; // more than 3 times IQR below Q1
  4768. int low_mild = 0; // 1.5 to 3 times IQR below Q1
  4769. int high_mild = 0; // 1.5 to 3 times IQR above Q3
  4770. int high_severe = 0; // more than 3 times IQR above Q3
  4771. int total() const {
  4772. return low_severe + low_mild + high_mild + high_severe;
  4773. }
  4774. };
  4775. } // namespace Benchmark
  4776. } // namespace Catch
  4777. // end catch_outlier_classification.hpp
  4778. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  4779. #include <string>
  4780. #include <iosfwd>
  4781. #include <map>
  4782. #include <set>
  4783. #include <memory>
  4784. #include <algorithm>
  4785. namespace Catch {
  4786. struct ReporterConfig {
  4787. explicit ReporterConfig( IConfigPtr const& _fullConfig );
  4788. ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream );
  4789. std::ostream& stream() const;
  4790. IConfigPtr fullConfig() const;
  4791. private:
  4792. std::ostream* m_stream;
  4793. IConfigPtr m_fullConfig;
  4794. };
  4795. struct ReporterPreferences {
  4796. bool shouldRedirectStdOut = false;
  4797. bool shouldReportAllAssertions = false;
  4798. };
  4799. template<typename T>
  4800. struct LazyStat : Option<T> {
  4801. LazyStat& operator=( T const& _value ) {
  4802. Option<T>::operator=( _value );
  4803. used = false;
  4804. return *this;
  4805. }
  4806. void reset() {
  4807. Option<T>::reset();
  4808. used = false;
  4809. }
  4810. bool used = false;
  4811. };
  4812. struct TestRunInfo {
  4813. TestRunInfo( std::string const& _name );
  4814. std::string name;
  4815. };
  4816. struct GroupInfo {
  4817. GroupInfo( std::string const& _name,
  4818. std::size_t _groupIndex,
  4819. std::size_t _groupsCount );
  4820. std::string name;
  4821. std::size_t groupIndex;
  4822. std::size_t groupsCounts;
  4823. };
  4824. struct AssertionStats {
  4825. AssertionStats( AssertionResult const& _assertionResult,
  4826. std::vector<MessageInfo> const& _infoMessages,
  4827. Totals const& _totals );
  4828. AssertionStats( AssertionStats const& ) = default;
  4829. AssertionStats( AssertionStats && ) = default;
  4830. AssertionStats& operator = ( AssertionStats const& ) = delete;
  4831. AssertionStats& operator = ( AssertionStats && ) = delete;
  4832. virtual ~AssertionStats();
  4833. AssertionResult assertionResult;
  4834. std::vector<MessageInfo> infoMessages;
  4835. Totals totals;
  4836. };
  4837. struct SectionStats {
  4838. SectionStats( SectionInfo const& _sectionInfo,
  4839. Counts const& _assertions,
  4840. double _durationInSeconds,
  4841. bool _missingAssertions );
  4842. SectionStats( SectionStats const& ) = default;
  4843. SectionStats( SectionStats && ) = default;
  4844. SectionStats& operator = ( SectionStats const& ) = default;
  4845. SectionStats& operator = ( SectionStats && ) = default;
  4846. virtual ~SectionStats();
  4847. SectionInfo sectionInfo;
  4848. Counts assertions;
  4849. double durationInSeconds;
  4850. bool missingAssertions;
  4851. };
  4852. struct TestCaseStats {
  4853. TestCaseStats( TestCaseInfo const& _testInfo,
  4854. Totals const& _totals,
  4855. std::string const& _stdOut,
  4856. std::string const& _stdErr,
  4857. bool _aborting );
  4858. TestCaseStats( TestCaseStats const& ) = default;
  4859. TestCaseStats( TestCaseStats && ) = default;
  4860. TestCaseStats& operator = ( TestCaseStats const& ) = default;
  4861. TestCaseStats& operator = ( TestCaseStats && ) = default;
  4862. virtual ~TestCaseStats();
  4863. TestCaseInfo testInfo;
  4864. Totals totals;
  4865. std::string stdOut;
  4866. std::string stdErr;
  4867. bool aborting;
  4868. };
  4869. struct TestGroupStats {
  4870. TestGroupStats( GroupInfo const& _groupInfo,
  4871. Totals const& _totals,
  4872. bool _aborting );
  4873. TestGroupStats( GroupInfo const& _groupInfo );
  4874. TestGroupStats( TestGroupStats const& ) = default;
  4875. TestGroupStats( TestGroupStats && ) = default;
  4876. TestGroupStats& operator = ( TestGroupStats const& ) = default;
  4877. TestGroupStats& operator = ( TestGroupStats && ) = default;
  4878. virtual ~TestGroupStats();
  4879. GroupInfo groupInfo;
  4880. Totals totals;
  4881. bool aborting;
  4882. };
  4883. struct TestRunStats {
  4884. TestRunStats( TestRunInfo const& _runInfo,
  4885. Totals const& _totals,
  4886. bool _aborting );
  4887. TestRunStats( TestRunStats const& ) = default;
  4888. TestRunStats( TestRunStats && ) = default;
  4889. TestRunStats& operator = ( TestRunStats const& ) = default;
  4890. TestRunStats& operator = ( TestRunStats && ) = default;
  4891. virtual ~TestRunStats();
  4892. TestRunInfo runInfo;
  4893. Totals totals;
  4894. bool aborting;
  4895. };
  4896. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  4897. struct BenchmarkInfo {
  4898. std::string name;
  4899. double estimatedDuration;
  4900. int iterations;
  4901. int samples;
  4902. unsigned int resamples;
  4903. double clockResolution;
  4904. double clockCost;
  4905. };
  4906. template <class Duration>
  4907. struct BenchmarkStats {
  4908. BenchmarkInfo info;
  4909. std::vector<Duration> samples;
  4910. Benchmark::Estimate<Duration> mean;
  4911. Benchmark::Estimate<Duration> standardDeviation;
  4912. Benchmark::OutlierClassification outliers;
  4913. double outlierVariance;
  4914. template <typename Duration2>
  4915. operator BenchmarkStats<Duration2>() const {
  4916. std::vector<Duration2> samples2;
  4917. samples2.reserve(samples.size());
  4918. std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration d) { return Duration2(d); });
  4919. return {
  4920. info,
  4921. std::move(samples2),
  4922. mean,
  4923. standardDeviation,
  4924. outliers,
  4925. outlierVariance,
  4926. };
  4927. }
  4928. };
  4929. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  4930. struct IStreamingReporter {
  4931. virtual ~IStreamingReporter() = default;
  4932. // Implementing class must also provide the following static methods:
  4933. // static std::string getDescription();
  4934. // static std::set<Verbosity> getSupportedVerbosities()
  4935. virtual ReporterPreferences getPreferences() const = 0;
  4936. virtual void noMatchingTestCases( std::string const& spec ) = 0;
  4937. virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0;
  4938. virtual void testGroupStarting( GroupInfo const& groupInfo ) = 0;
  4939. virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0;
  4940. virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0;
  4941. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  4942. virtual void benchmarkPreparing( std::string const& ) {}
  4943. virtual void benchmarkStarting( BenchmarkInfo const& ) {}
  4944. virtual void benchmarkEnded( BenchmarkStats<> const& ) {}
  4945. virtual void benchmarkFailed( std::string const& ) {}
  4946. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  4947. virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0;
  4948. // The return value indicates if the messages buffer should be cleared:
  4949. virtual bool assertionEnded( AssertionStats const& assertionStats ) = 0;
  4950. virtual void sectionEnded( SectionStats const& sectionStats ) = 0;
  4951. virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0;
  4952. virtual void testGroupEnded( TestGroupStats const& testGroupStats ) = 0;
  4953. virtual void testRunEnded( TestRunStats const& testRunStats ) = 0;
  4954. virtual void skipTest( TestCaseInfo const& testInfo ) = 0;
  4955. // Default empty implementation provided
  4956. virtual void fatalErrorEncountered( StringRef name );
  4957. virtual bool isMulti() const;
  4958. };
  4959. using IStreamingReporterPtr = std::unique_ptr<IStreamingReporter>;
  4960. struct IReporterFactory {
  4961. virtual ~IReporterFactory();
  4962. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const = 0;
  4963. virtual std::string getDescription() const = 0;
  4964. };
  4965. using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
  4966. struct IReporterRegistry {
  4967. using FactoryMap = std::map<std::string, IReporterFactoryPtr>;
  4968. using Listeners = std::vector<IReporterFactoryPtr>;
  4969. virtual ~IReporterRegistry();
  4970. virtual IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const = 0;
  4971. virtual FactoryMap const& getFactories() const = 0;
  4972. virtual Listeners const& getListeners() const = 0;
  4973. };
  4974. } // end namespace Catch
  4975. // end catch_interfaces_reporter.h
  4976. #include <algorithm>
  4977. #include <cstring>
  4978. #include <cfloat>
  4979. #include <cstdio>
  4980. #include <cassert>
  4981. #include <memory>
  4982. #include <ostream>
  4983. namespace Catch {
  4984. void prepareExpandedExpression(AssertionResult& result);
  4985. // Returns double formatted as %.3f (format expected on output)
  4986. std::string getFormattedDuration( double duration );
  4987. std::string serializeFilters( std::vector<std::string> const& container );
  4988. template<typename DerivedT>
  4989. struct StreamingReporterBase : IStreamingReporter {
  4990. StreamingReporterBase( ReporterConfig const& _config )
  4991. : m_config( _config.fullConfig() ),
  4992. stream( _config.stream() )
  4993. {
  4994. m_reporterPrefs.shouldRedirectStdOut = false;
  4995. if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
  4996. CATCH_ERROR( "Verbosity level not supported by this reporter" );
  4997. }
  4998. ReporterPreferences getPreferences() const override {
  4999. return m_reporterPrefs;
  5000. }
  5001. static std::set<Verbosity> getSupportedVerbosities() {
  5002. return { Verbosity::Normal };
  5003. }
  5004. ~StreamingReporterBase() override = default;
  5005. void noMatchingTestCases(std::string const&) override {}
  5006. void testRunStarting(TestRunInfo const& _testRunInfo) override {
  5007. currentTestRunInfo = _testRunInfo;
  5008. }
  5009. void testGroupStarting(GroupInfo const& _groupInfo) override {
  5010. currentGroupInfo = _groupInfo;
  5011. }
  5012. void testCaseStarting(TestCaseInfo const& _testInfo) override {
  5013. currentTestCaseInfo = _testInfo;
  5014. }
  5015. void sectionStarting(SectionInfo const& _sectionInfo) override {
  5016. m_sectionStack.push_back(_sectionInfo);
  5017. }
  5018. void sectionEnded(SectionStats const& /* _sectionStats */) override {
  5019. m_sectionStack.pop_back();
  5020. }
  5021. void testCaseEnded(TestCaseStats const& /* _testCaseStats */) override {
  5022. currentTestCaseInfo.reset();
  5023. }
  5024. void testGroupEnded(TestGroupStats const& /* _testGroupStats */) override {
  5025. currentGroupInfo.reset();
  5026. }
  5027. void testRunEnded(TestRunStats const& /* _testRunStats */) override {
  5028. currentTestCaseInfo.reset();
  5029. currentGroupInfo.reset();
  5030. currentTestRunInfo.reset();
  5031. }
  5032. void skipTest(TestCaseInfo const&) override {
  5033. // Don't do anything with this by default.
  5034. // It can optionally be overridden in the derived class.
  5035. }
  5036. IConfigPtr m_config;
  5037. std::ostream& stream;
  5038. LazyStat<TestRunInfo> currentTestRunInfo;
  5039. LazyStat<GroupInfo> currentGroupInfo;
  5040. LazyStat<TestCaseInfo> currentTestCaseInfo;
  5041. std::vector<SectionInfo> m_sectionStack;
  5042. ReporterPreferences m_reporterPrefs;
  5043. };
  5044. template<typename DerivedT>
  5045. struct CumulativeReporterBase : IStreamingReporter {
  5046. template<typename T, typename ChildNodeT>
  5047. struct Node {
  5048. explicit Node( T const& _value ) : value( _value ) {}
  5049. virtual ~Node() {}
  5050. using ChildNodes = std::vector<std::shared_ptr<ChildNodeT>>;
  5051. T value;
  5052. ChildNodes children;
  5053. };
  5054. struct SectionNode {
  5055. explicit SectionNode(SectionStats const& _stats) : stats(_stats) {}
  5056. virtual ~SectionNode() = default;
  5057. bool operator == (SectionNode const& other) const {
  5058. return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;
  5059. }
  5060. bool operator == (std::shared_ptr<SectionNode> const& other) const {
  5061. return operator==(*other);
  5062. }
  5063. SectionStats stats;
  5064. using ChildSections = std::vector<std::shared_ptr<SectionNode>>;
  5065. using Assertions = std::vector<AssertionStats>;
  5066. ChildSections childSections;
  5067. Assertions assertions;
  5068. std::string stdOut;
  5069. std::string stdErr;
  5070. };
  5071. struct BySectionInfo {
  5072. BySectionInfo( SectionInfo const& other ) : m_other( other ) {}
  5073. BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {}
  5074. bool operator() (std::shared_ptr<SectionNode> const& node) const {
  5075. return ((node->stats.sectionInfo.name == m_other.name) &&
  5076. (node->stats.sectionInfo.lineInfo == m_other.lineInfo));
  5077. }
  5078. void operator=(BySectionInfo const&) = delete;
  5079. private:
  5080. SectionInfo const& m_other;
  5081. };
  5082. using TestCaseNode = Node<TestCaseStats, SectionNode>;
  5083. using TestGroupNode = Node<TestGroupStats, TestCaseNode>;
  5084. using TestRunNode = Node<TestRunStats, TestGroupNode>;
  5085. CumulativeReporterBase( ReporterConfig const& _config )
  5086. : m_config( _config.fullConfig() ),
  5087. stream( _config.stream() )
  5088. {
  5089. m_reporterPrefs.shouldRedirectStdOut = false;
  5090. if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
  5091. CATCH_ERROR( "Verbosity level not supported by this reporter" );
  5092. }
  5093. ~CumulativeReporterBase() override = default;
  5094. ReporterPreferences getPreferences() const override {
  5095. return m_reporterPrefs;
  5096. }
  5097. static std::set<Verbosity> getSupportedVerbosities() {
  5098. return { Verbosity::Normal };
  5099. }
  5100. void testRunStarting( TestRunInfo const& ) override {}
  5101. void testGroupStarting( GroupInfo const& ) override {}
  5102. void testCaseStarting( TestCaseInfo const& ) override {}
  5103. void sectionStarting( SectionInfo const& sectionInfo ) override {
  5104. SectionStats incompleteStats( sectionInfo, Counts(), 0, false );
  5105. std::shared_ptr<SectionNode> node;
  5106. if( m_sectionStack.empty() ) {
  5107. if( !m_rootSection )
  5108. m_rootSection = std::make_shared<SectionNode>( incompleteStats );
  5109. node = m_rootSection;
  5110. }
  5111. else {
  5112. SectionNode& parentNode = *m_sectionStack.back();
  5113. auto it =
  5114. std::find_if( parentNode.childSections.begin(),
  5115. parentNode.childSections.end(),
  5116. BySectionInfo( sectionInfo ) );
  5117. if( it == parentNode.childSections.end() ) {
  5118. node = std::make_shared<SectionNode>( incompleteStats );
  5119. parentNode.childSections.push_back( node );
  5120. }
  5121. else
  5122. node = *it;
  5123. }
  5124. m_sectionStack.push_back( node );
  5125. m_deepestSection = std::move(node);
  5126. }
  5127. void assertionStarting(AssertionInfo const&) override {}
  5128. bool assertionEnded(AssertionStats const& assertionStats) override {
  5129. assert(!m_sectionStack.empty());
  5130. // AssertionResult holds a pointer to a temporary DecomposedExpression,
  5131. // which getExpandedExpression() calls to build the expression string.
  5132. // Our section stack copy of the assertionResult will likely outlive the
  5133. // temporary, so it must be expanded or discarded now to avoid calling
  5134. // a destroyed object later.
  5135. prepareExpandedExpression(const_cast<AssertionResult&>( assertionStats.assertionResult ) );
  5136. SectionNode& sectionNode = *m_sectionStack.back();
  5137. sectionNode.assertions.push_back(assertionStats);
  5138. return true;
  5139. }
  5140. void sectionEnded(SectionStats const& sectionStats) override {
  5141. assert(!m_sectionStack.empty());
  5142. SectionNode& node = *m_sectionStack.back();
  5143. node.stats = sectionStats;
  5144. m_sectionStack.pop_back();
  5145. }
  5146. void testCaseEnded(TestCaseStats const& testCaseStats) override {
  5147. auto node = std::make_shared<TestCaseNode>(testCaseStats);
  5148. assert(m_sectionStack.size() == 0);
  5149. node->children.push_back(m_rootSection);
  5150. m_testCases.push_back(node);
  5151. m_rootSection.reset();
  5152. assert(m_deepestSection);
  5153. m_deepestSection->stdOut = testCaseStats.stdOut;
  5154. m_deepestSection->stdErr = testCaseStats.stdErr;
  5155. }
  5156. void testGroupEnded(TestGroupStats const& testGroupStats) override {
  5157. auto node = std::make_shared<TestGroupNode>(testGroupStats);
  5158. node->children.swap(m_testCases);
  5159. m_testGroups.push_back(node);
  5160. }
  5161. void testRunEnded(TestRunStats const& testRunStats) override {
  5162. auto node = std::make_shared<TestRunNode>(testRunStats);
  5163. node->children.swap(m_testGroups);
  5164. m_testRuns.push_back(node);
  5165. testRunEndedCumulative();
  5166. }
  5167. virtual void testRunEndedCumulative() = 0;
  5168. void skipTest(TestCaseInfo const&) override {}
  5169. IConfigPtr m_config;
  5170. std::ostream& stream;
  5171. std::vector<AssertionStats> m_assertions;
  5172. std::vector<std::vector<std::shared_ptr<SectionNode>>> m_sections;
  5173. std::vector<std::shared_ptr<TestCaseNode>> m_testCases;
  5174. std::vector<std::shared_ptr<TestGroupNode>> m_testGroups;
  5175. std::vector<std::shared_ptr<TestRunNode>> m_testRuns;
  5176. std::shared_ptr<SectionNode> m_rootSection;
  5177. std::shared_ptr<SectionNode> m_deepestSection;
  5178. std::vector<std::shared_ptr<SectionNode>> m_sectionStack;
  5179. ReporterPreferences m_reporterPrefs;
  5180. };
  5181. template<char C>
  5182. char const* getLineOfChars() {
  5183. static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
  5184. if( !*line ) {
  5185. std::memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 );
  5186. line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0;
  5187. }
  5188. return line;
  5189. }
  5190. struct TestEventListenerBase : StreamingReporterBase<TestEventListenerBase> {
  5191. TestEventListenerBase( ReporterConfig const& _config );
  5192. static std::set<Verbosity> getSupportedVerbosities();
  5193. void assertionStarting(AssertionInfo const&) override;
  5194. bool assertionEnded(AssertionStats const&) override;
  5195. };
  5196. } // end namespace Catch
  5197. // end catch_reporter_bases.hpp
  5198. // start catch_console_colour.h
  5199. namespace Catch {
  5200. struct Colour {
  5201. enum Code {
  5202. None = 0,
  5203. White,
  5204. Red,
  5205. Green,
  5206. Blue,
  5207. Cyan,
  5208. Yellow,
  5209. Grey,
  5210. Bright = 0x10,
  5211. BrightRed = Bright | Red,
  5212. BrightGreen = Bright | Green,
  5213. LightGrey = Bright | Grey,
  5214. BrightWhite = Bright | White,
  5215. BrightYellow = Bright | Yellow,
  5216. // By intention
  5217. FileName = LightGrey,
  5218. Warning = BrightYellow,
  5219. ResultError = BrightRed,
  5220. ResultSuccess = BrightGreen,
  5221. ResultExpectedFailure = Warning,
  5222. Error = BrightRed,
  5223. Success = Green,
  5224. OriginalExpression = Cyan,
  5225. ReconstructedExpression = BrightYellow,
  5226. SecondaryText = LightGrey,
  5227. Headers = White
  5228. };
  5229. // Use constructed object for RAII guard
  5230. Colour( Code _colourCode );
  5231. Colour( Colour&& other ) noexcept;
  5232. Colour& operator=( Colour&& other ) noexcept;
  5233. ~Colour();
  5234. // Use static method for one-shot changes
  5235. static void use( Code _colourCode );
  5236. private:
  5237. bool m_moved = false;
  5238. };
  5239. std::ostream& operator << ( std::ostream& os, Colour const& );
  5240. } // end namespace Catch
  5241. // end catch_console_colour.h
  5242. // start catch_reporter_registrars.hpp
  5243. namespace Catch {
  5244. template<typename T>
  5245. class ReporterRegistrar {
  5246. class ReporterFactory : public IReporterFactory {
  5247. IStreamingReporterPtr create( ReporterConfig const& config ) const override {
  5248. return std::unique_ptr<T>( new T( config ) );
  5249. }
  5250. std::string getDescription() const override {
  5251. return T::getDescription();
  5252. }
  5253. };
  5254. public:
  5255. explicit ReporterRegistrar( std::string const& name ) {
  5256. getMutableRegistryHub().registerReporter( name, std::make_shared<ReporterFactory>() );
  5257. }
  5258. };
  5259. template<typename T>
  5260. class ListenerRegistrar {
  5261. class ListenerFactory : public IReporterFactory {
  5262. IStreamingReporterPtr create( ReporterConfig const& config ) const override {
  5263. return std::unique_ptr<T>( new T( config ) );
  5264. }
  5265. std::string getDescription() const override {
  5266. return std::string();
  5267. }
  5268. };
  5269. public:
  5270. ListenerRegistrar() {
  5271. getMutableRegistryHub().registerListener( std::make_shared<ListenerFactory>() );
  5272. }
  5273. };
  5274. }
  5275. #if !defined(CATCH_CONFIG_DISABLE)
  5276. #define CATCH_REGISTER_REPORTER( name, reporterType ) \
  5277. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  5278. namespace{ Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); } \
  5279. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  5280. #define CATCH_REGISTER_LISTENER( listenerType ) \
  5281. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  5282. namespace{ Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; } \
  5283. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  5284. #else // CATCH_CONFIG_DISABLE
  5285. #define CATCH_REGISTER_REPORTER(name, reporterType)
  5286. #define CATCH_REGISTER_LISTENER(listenerType)
  5287. #endif // CATCH_CONFIG_DISABLE
  5288. // end catch_reporter_registrars.hpp
  5289. // Allow users to base their work off existing reporters
  5290. // start catch_reporter_compact.h
  5291. namespace Catch {
  5292. struct CompactReporter : StreamingReporterBase<CompactReporter> {
  5293. using StreamingReporterBase::StreamingReporterBase;
  5294. ~CompactReporter() override;
  5295. static std::string getDescription();
  5296. ReporterPreferences getPreferences() const override;
  5297. void noMatchingTestCases(std::string const& spec) override;
  5298. void assertionStarting(AssertionInfo const&) override;
  5299. bool assertionEnded(AssertionStats const& _assertionStats) override;
  5300. void sectionEnded(SectionStats const& _sectionStats) override;
  5301. void testRunEnded(TestRunStats const& _testRunStats) override;
  5302. };
  5303. } // end namespace Catch
  5304. // end catch_reporter_compact.h
  5305. // start catch_reporter_console.h
  5306. #if defined(_MSC_VER)
  5307. #pragma warning(push)
  5308. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  5309. // Note that 4062 (not all labels are handled
  5310. // and default is missing) is enabled
  5311. #endif
  5312. namespace Catch {
  5313. // Fwd decls
  5314. struct SummaryColumn;
  5315. class TablePrinter;
  5316. struct ConsoleReporter : StreamingReporterBase<ConsoleReporter> {
  5317. std::unique_ptr<TablePrinter> m_tablePrinter;
  5318. ConsoleReporter(ReporterConfig const& config);
  5319. ~ConsoleReporter() override;
  5320. static std::string getDescription();
  5321. void noMatchingTestCases(std::string const& spec) override;
  5322. void assertionStarting(AssertionInfo const&) override;
  5323. bool assertionEnded(AssertionStats const& _assertionStats) override;
  5324. void sectionStarting(SectionInfo const& _sectionInfo) override;
  5325. void sectionEnded(SectionStats const& _sectionStats) override;
  5326. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  5327. void benchmarkPreparing(std::string const& name) override;
  5328. void benchmarkStarting(BenchmarkInfo const& info) override;
  5329. void benchmarkEnded(BenchmarkStats<> const& stats) override;
  5330. void benchmarkFailed(std::string const& error) override;
  5331. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  5332. void testCaseEnded(TestCaseStats const& _testCaseStats) override;
  5333. void testGroupEnded(TestGroupStats const& _testGroupStats) override;
  5334. void testRunEnded(TestRunStats const& _testRunStats) override;
  5335. void testRunStarting(TestRunInfo const& _testRunInfo) override;
  5336. private:
  5337. void lazyPrint();
  5338. void lazyPrintWithoutClosingBenchmarkTable();
  5339. void lazyPrintRunInfo();
  5340. void lazyPrintGroupInfo();
  5341. void printTestCaseAndSectionHeader();
  5342. void printClosedHeader(std::string const& _name);
  5343. void printOpenHeader(std::string const& _name);
  5344. // if string has a : in first line will set indent to follow it on
  5345. // subsequent lines
  5346. void printHeaderString(std::string const& _string, std::size_t indent = 0);
  5347. void printTotals(Totals const& totals);
  5348. void printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row);
  5349. void printTotalsDivider(Totals const& totals);
  5350. void printSummaryDivider();
  5351. void printTestFilters();
  5352. private:
  5353. bool m_headerPrinted = false;
  5354. };
  5355. } // end namespace Catch
  5356. #if defined(_MSC_VER)
  5357. #pragma warning(pop)
  5358. #endif
  5359. // end catch_reporter_console.h
  5360. // start catch_reporter_junit.h
  5361. // start catch_xmlwriter.h
  5362. #include <vector>
  5363. namespace Catch {
  5364. class XmlEncode {
  5365. public:
  5366. enum ForWhat { ForTextNodes, ForAttributes };
  5367. XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes );
  5368. void encodeTo( std::ostream& os ) const;
  5369. friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode );
  5370. private:
  5371. std::string m_str;
  5372. ForWhat m_forWhat;
  5373. };
  5374. class XmlWriter {
  5375. public:
  5376. class ScopedElement {
  5377. public:
  5378. ScopedElement( XmlWriter* writer );
  5379. ScopedElement( ScopedElement&& other ) noexcept;
  5380. ScopedElement& operator=( ScopedElement&& other ) noexcept;
  5381. ~ScopedElement();
  5382. ScopedElement& writeText( std::string const& text, bool indent = true );
  5383. template<typename T>
  5384. ScopedElement& writeAttribute( std::string const& name, T const& attribute ) {
  5385. m_writer->writeAttribute( name, attribute );
  5386. return *this;
  5387. }
  5388. private:
  5389. mutable XmlWriter* m_writer = nullptr;
  5390. };
  5391. XmlWriter( std::ostream& os = Catch::cout() );
  5392. ~XmlWriter();
  5393. XmlWriter( XmlWriter const& ) = delete;
  5394. XmlWriter& operator=( XmlWriter const& ) = delete;
  5395. XmlWriter& startElement( std::string const& name );
  5396. ScopedElement scopedElement( std::string const& name );
  5397. XmlWriter& endElement();
  5398. XmlWriter& writeAttribute( std::string const& name, std::string const& attribute );
  5399. XmlWriter& writeAttribute( std::string const& name, bool attribute );
  5400. template<typename T>
  5401. XmlWriter& writeAttribute( std::string const& name, T const& attribute ) {
  5402. ReusableStringStream rss;
  5403. rss << attribute;
  5404. return writeAttribute( name, rss.str() );
  5405. }
  5406. XmlWriter& writeText( std::string const& text, bool indent = true );
  5407. XmlWriter& writeComment( std::string const& text );
  5408. void writeStylesheetRef( std::string const& url );
  5409. XmlWriter& writeBlankLine();
  5410. void ensureTagClosed();
  5411. private:
  5412. void writeDeclaration();
  5413. void newlineIfNecessary();
  5414. bool m_tagIsOpen = false;
  5415. bool m_needsNewline = false;
  5416. std::vector<std::string> m_tags;
  5417. std::string m_indent;
  5418. std::ostream& m_os;
  5419. };
  5420. }
  5421. // end catch_xmlwriter.h
  5422. namespace Catch {
  5423. class JunitReporter : public CumulativeReporterBase<JunitReporter> {
  5424. public:
  5425. JunitReporter(ReporterConfig const& _config);
  5426. ~JunitReporter() override;
  5427. static std::string getDescription();
  5428. void noMatchingTestCases(std::string const& /*spec*/) override;
  5429. void testRunStarting(TestRunInfo const& runInfo) override;
  5430. void testGroupStarting(GroupInfo const& groupInfo) override;
  5431. void testCaseStarting(TestCaseInfo const& testCaseInfo) override;
  5432. bool assertionEnded(AssertionStats const& assertionStats) override;
  5433. void testCaseEnded(TestCaseStats const& testCaseStats) override;
  5434. void testGroupEnded(TestGroupStats const& testGroupStats) override;
  5435. void testRunEndedCumulative() override;
  5436. void writeGroup(TestGroupNode const& groupNode, double suiteTime);
  5437. void writeTestCase(TestCaseNode const& testCaseNode);
  5438. void writeSection(std::string const& className,
  5439. std::string const& rootName,
  5440. SectionNode const& sectionNode);
  5441. void writeAssertions(SectionNode const& sectionNode);
  5442. void writeAssertion(AssertionStats const& stats);
  5443. XmlWriter xml;
  5444. Timer suiteTimer;
  5445. std::string stdOutForSuite;
  5446. std::string stdErrForSuite;
  5447. unsigned int unexpectedExceptions = 0;
  5448. bool m_okToFail = false;
  5449. };
  5450. } // end namespace Catch
  5451. // end catch_reporter_junit.h
  5452. // start catch_reporter_xml.h
  5453. namespace Catch {
  5454. class XmlReporter : public StreamingReporterBase<XmlReporter> {
  5455. public:
  5456. XmlReporter(ReporterConfig const& _config);
  5457. ~XmlReporter() override;
  5458. static std::string getDescription();
  5459. virtual std::string getStylesheetRef() const;
  5460. void writeSourceInfo(SourceLineInfo const& sourceInfo);
  5461. public: // StreamingReporterBase
  5462. void noMatchingTestCases(std::string const& s) override;
  5463. void testRunStarting(TestRunInfo const& testInfo) override;
  5464. void testGroupStarting(GroupInfo const& groupInfo) override;
  5465. void testCaseStarting(TestCaseInfo const& testInfo) override;
  5466. void sectionStarting(SectionInfo const& sectionInfo) override;
  5467. void assertionStarting(AssertionInfo const&) override;
  5468. bool assertionEnded(AssertionStats const& assertionStats) override;
  5469. void sectionEnded(SectionStats const& sectionStats) override;
  5470. void testCaseEnded(TestCaseStats const& testCaseStats) override;
  5471. void testGroupEnded(TestGroupStats const& testGroupStats) override;
  5472. void testRunEnded(TestRunStats const& testRunStats) override;
  5473. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  5474. void benchmarkPreparing(std::string const& name) override;
  5475. void benchmarkStarting(BenchmarkInfo const&) override;
  5476. void benchmarkEnded(BenchmarkStats<> const&) override;
  5477. void benchmarkFailed(std::string const&) override;
  5478. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  5479. private:
  5480. Timer m_testCaseTimer;
  5481. XmlWriter m_xml;
  5482. int m_sectionDepth = 0;
  5483. };
  5484. } // end namespace Catch
  5485. // end catch_reporter_xml.h
  5486. // end catch_external_interfaces.h
  5487. #endif
  5488. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  5489. // start catch_benchmark.hpp
  5490. // Benchmark
  5491. // start catch_chronometer.hpp
  5492. // User-facing chronometer
  5493. // start catch_clock.hpp
  5494. // Clocks
  5495. #include <chrono>
  5496. #include <ratio>
  5497. namespace Catch {
  5498. namespace Benchmark {
  5499. template <typename Clock>
  5500. using ClockDuration = typename Clock::duration;
  5501. template <typename Clock>
  5502. using FloatDuration = std::chrono::duration<double, typename Clock::period>;
  5503. template <typename Clock>
  5504. using TimePoint = typename Clock::time_point;
  5505. using default_clock = std::chrono::steady_clock;
  5506. template <typename Clock>
  5507. struct now {
  5508. TimePoint<Clock> operator()() const {
  5509. return Clock::now();
  5510. }
  5511. };
  5512. using fp_seconds = std::chrono::duration<double, std::ratio<1>>;
  5513. } // namespace Benchmark
  5514. } // namespace Catch
  5515. // end catch_clock.hpp
  5516. // start catch_optimizer.hpp
  5517. // Hinting the optimizer
  5518. #if defined(_MSC_VER)
  5519. # include <atomic> // atomic_thread_fence
  5520. #endif
  5521. namespace Catch {
  5522. namespace Benchmark {
  5523. #if defined(__GNUC__) || defined(__clang__)
  5524. template <typename T>
  5525. inline void keep_memory(T* p) {
  5526. asm volatile("" : : "g"(p) : "memory");
  5527. }
  5528. inline void keep_memory() {
  5529. asm volatile("" : : : "memory");
  5530. }
  5531. namespace Detail {
  5532. inline void optimizer_barrier() { keep_memory(); }
  5533. } // namespace Detail
  5534. #elif defined(_MSC_VER)
  5535. #pragma optimize("", off)
  5536. template <typename T>
  5537. inline void keep_memory(T* p) {
  5538. // thanks @milleniumbug
  5539. *reinterpret_cast<char volatile*>(p) = *reinterpret_cast<char const volatile*>(p);
  5540. }
  5541. // TODO equivalent keep_memory()
  5542. #pragma optimize("", on)
  5543. namespace Detail {
  5544. inline void optimizer_barrier() {
  5545. std::atomic_thread_fence(std::memory_order_seq_cst);
  5546. }
  5547. } // namespace Detail
  5548. #endif
  5549. template <typename T>
  5550. inline void deoptimize_value(T&& x) {
  5551. keep_memory(&x);
  5552. }
  5553. template <typename Fn, typename... Args>
  5554. inline auto invoke_deoptimized(Fn&& fn, Args&&... args) -> typename std::enable_if<!std::is_same<void, decltype(fn(args...))>::value>::type {
  5555. deoptimize_value(std::forward<Fn>(fn) (std::forward<Args...>(args...)));
  5556. }
  5557. template <typename Fn, typename... Args>
  5558. inline auto invoke_deoptimized(Fn&& fn, Args&&... args) -> typename std::enable_if<std::is_same<void, decltype(fn(args...))>::value>::type {
  5559. std::forward<Fn>(fn) (std::forward<Args...>(args...));
  5560. }
  5561. } // namespace Benchmark
  5562. } // namespace Catch
  5563. // end catch_optimizer.hpp
  5564. // start catch_complete_invoke.hpp
  5565. // Invoke with a special case for void
  5566. #include <type_traits>
  5567. #include <utility>
  5568. namespace Catch {
  5569. namespace Benchmark {
  5570. namespace Detail {
  5571. template <typename T>
  5572. struct CompleteType { using type = T; };
  5573. template <>
  5574. struct CompleteType<void> { struct type {}; };
  5575. template <typename T>
  5576. using CompleteType_t = typename CompleteType<T>::type;
  5577. template <typename Result>
  5578. struct CompleteInvoker {
  5579. template <typename Fun, typename... Args>
  5580. static Result invoke(Fun&& fun, Args&&... args) {
  5581. return std::forward<Fun>(fun)(std::forward<Args>(args)...);
  5582. }
  5583. };
  5584. template <>
  5585. struct CompleteInvoker<void> {
  5586. template <typename Fun, typename... Args>
  5587. static CompleteType_t<void> invoke(Fun&& fun, Args&&... args) {
  5588. std::forward<Fun>(fun)(std::forward<Args>(args)...);
  5589. return {};
  5590. }
  5591. };
  5592. template <typename Sig>
  5593. using ResultOf_t = typename std::result_of<Sig>::type;
  5594. // invoke and not return void :(
  5595. template <typename Fun, typename... Args>
  5596. CompleteType_t<ResultOf_t<Fun(Args...)>> complete_invoke(Fun&& fun, Args&&... args) {
  5597. return CompleteInvoker<ResultOf_t<Fun(Args...)>>::invoke(std::forward<Fun>(fun), std::forward<Args>(args)...);
  5598. }
  5599. const std::string benchmarkErrorMsg = "a benchmark failed to run successfully";
  5600. } // namespace Detail
  5601. template <typename Fun>
  5602. Detail::CompleteType_t<Detail::ResultOf_t<Fun()>> user_code(Fun&& fun) {
  5603. CATCH_TRY{
  5604. return Detail::complete_invoke(std::forward<Fun>(fun));
  5605. } CATCH_CATCH_ALL{
  5606. getResultCapture().benchmarkFailed(translateActiveException());
  5607. CATCH_RUNTIME_ERROR(Detail::benchmarkErrorMsg);
  5608. }
  5609. }
  5610. } // namespace Benchmark
  5611. } // namespace Catch
  5612. // end catch_complete_invoke.hpp
  5613. namespace Catch {
  5614. namespace Benchmark {
  5615. namespace Detail {
  5616. struct ChronometerConcept {
  5617. virtual void start() = 0;
  5618. virtual void finish() = 0;
  5619. virtual ~ChronometerConcept() = default;
  5620. };
  5621. template <typename Clock>
  5622. struct ChronometerModel final : public ChronometerConcept {
  5623. void start() override { started = Clock::now(); }
  5624. void finish() override { finished = Clock::now(); }
  5625. ClockDuration<Clock> elapsed() const { return finished - started; }
  5626. TimePoint<Clock> started;
  5627. TimePoint<Clock> finished;
  5628. };
  5629. } // namespace Detail
  5630. struct Chronometer {
  5631. public:
  5632. template <typename Fun>
  5633. void measure(Fun&& fun) { measure(std::forward<Fun>(fun), is_callable<Fun(int)>()); }
  5634. int runs() const { return k; }
  5635. Chronometer(Detail::ChronometerConcept& meter, int k)
  5636. : impl(&meter)
  5637. , k(k) {}
  5638. private:
  5639. template <typename Fun>
  5640. void measure(Fun&& fun, std::false_type) {
  5641. measure([&fun](int) { return fun(); }, std::true_type());
  5642. }
  5643. template <typename Fun>
  5644. void measure(Fun&& fun, std::true_type) {
  5645. Detail::optimizer_barrier();
  5646. impl->start();
  5647. for (int i = 0; i < k; ++i) invoke_deoptimized(fun, i);
  5648. impl->finish();
  5649. Detail::optimizer_barrier();
  5650. }
  5651. Detail::ChronometerConcept* impl;
  5652. int k;
  5653. };
  5654. } // namespace Benchmark
  5655. } // namespace Catch
  5656. // end catch_chronometer.hpp
  5657. // start catch_environment.hpp
  5658. // Environment information
  5659. namespace Catch {
  5660. namespace Benchmark {
  5661. template <typename Duration>
  5662. struct EnvironmentEstimate {
  5663. Duration mean;
  5664. OutlierClassification outliers;
  5665. template <typename Duration2>
  5666. operator EnvironmentEstimate<Duration2>() const {
  5667. return { mean, outliers };
  5668. }
  5669. };
  5670. template <typename Clock>
  5671. struct Environment {
  5672. using clock_type = Clock;
  5673. EnvironmentEstimate<FloatDuration<Clock>> clock_resolution;
  5674. EnvironmentEstimate<FloatDuration<Clock>> clock_cost;
  5675. };
  5676. } // namespace Benchmark
  5677. } // namespace Catch
  5678. // end catch_environment.hpp
  5679. // start catch_execution_plan.hpp
  5680. // Execution plan
  5681. // start catch_benchmark_function.hpp
  5682. // Dumb std::function implementation for consistent call overhead
  5683. #include <cassert>
  5684. #include <type_traits>
  5685. #include <utility>
  5686. #include <memory>
  5687. namespace Catch {
  5688. namespace Benchmark {
  5689. namespace Detail {
  5690. template <typename T>
  5691. using Decay = typename std::decay<T>::type;
  5692. template <typename T, typename U>
  5693. struct is_related
  5694. : std::is_same<Decay<T>, Decay<U>> {};
  5695. /// We need to reinvent std::function because every piece of code that might add overhead
  5696. /// in a measurement context needs to have consistent performance characteristics so that we
  5697. /// can account for it in the measurement.
  5698. /// Implementations of std::function with optimizations that aren't always applicable, like
  5699. /// small buffer optimizations, are not uncommon.
  5700. /// This is effectively an implementation of std::function without any such optimizations;
  5701. /// it may be slow, but it is consistently slow.
  5702. struct BenchmarkFunction {
  5703. private:
  5704. struct callable {
  5705. virtual void call(Chronometer meter) const = 0;
  5706. virtual callable* clone() const = 0;
  5707. virtual ~callable() = default;
  5708. };
  5709. template <typename Fun>
  5710. struct model : public callable {
  5711. model(Fun&& fun) : fun(std::move(fun)) {}
  5712. model(Fun const& fun) : fun(fun) {}
  5713. model<Fun>* clone() const override { return new model<Fun>(*this); }
  5714. void call(Chronometer meter) const override {
  5715. call(meter, is_callable<Fun(Chronometer)>());
  5716. }
  5717. void call(Chronometer meter, std::true_type) const {
  5718. fun(meter);
  5719. }
  5720. void call(Chronometer meter, std::false_type) const {
  5721. meter.measure(fun);
  5722. }
  5723. Fun fun;
  5724. };
  5725. struct do_nothing { void operator()() const {} };
  5726. template <typename T>
  5727. BenchmarkFunction(model<T>* c) : f(c) {}
  5728. public:
  5729. BenchmarkFunction()
  5730. : f(new model<do_nothing>{ {} }) {}
  5731. template <typename Fun,
  5732. typename std::enable_if<!is_related<Fun, BenchmarkFunction>::value, int>::type = 0>
  5733. BenchmarkFunction(Fun&& fun)
  5734. : f(new model<typename std::decay<Fun>::type>(std::forward<Fun>(fun))) {}
  5735. BenchmarkFunction(BenchmarkFunction&& that)
  5736. : f(std::move(that.f)) {}
  5737. BenchmarkFunction(BenchmarkFunction const& that)
  5738. : f(that.f->clone()) {}
  5739. BenchmarkFunction& operator=(BenchmarkFunction&& that) {
  5740. f = std::move(that.f);
  5741. return *this;
  5742. }
  5743. BenchmarkFunction& operator=(BenchmarkFunction const& that) {
  5744. f.reset(that.f->clone());
  5745. return *this;
  5746. }
  5747. void operator()(Chronometer meter) const { f->call(meter); }
  5748. private:
  5749. std::unique_ptr<callable> f;
  5750. };
  5751. } // namespace Detail
  5752. } // namespace Benchmark
  5753. } // namespace Catch
  5754. // end catch_benchmark_function.hpp
  5755. // start catch_repeat.hpp
  5756. // repeat algorithm
  5757. #include <type_traits>
  5758. #include <utility>
  5759. namespace Catch {
  5760. namespace Benchmark {
  5761. namespace Detail {
  5762. template <typename Fun>
  5763. struct repeater {
  5764. void operator()(int k) const {
  5765. for (int i = 0; i < k; ++i) {
  5766. fun();
  5767. }
  5768. }
  5769. Fun fun;
  5770. };
  5771. template <typename Fun>
  5772. repeater<typename std::decay<Fun>::type> repeat(Fun&& fun) {
  5773. return { std::forward<Fun>(fun) };
  5774. }
  5775. } // namespace Detail
  5776. } // namespace Benchmark
  5777. } // namespace Catch
  5778. // end catch_repeat.hpp
  5779. // start catch_run_for_at_least.hpp
  5780. // Run a function for a minimum amount of time
  5781. // start catch_measure.hpp
  5782. // Measure
  5783. // start catch_timing.hpp
  5784. // Timing
  5785. #include <tuple>
  5786. #include <type_traits>
  5787. namespace Catch {
  5788. namespace Benchmark {
  5789. template <typename Duration, typename Result>
  5790. struct Timing {
  5791. Duration elapsed;
  5792. Result result;
  5793. int iterations;
  5794. };
  5795. template <typename Clock, typename Sig>
  5796. using TimingOf = Timing<ClockDuration<Clock>, Detail::CompleteType_t<Detail::ResultOf_t<Sig>>>;
  5797. } // namespace Benchmark
  5798. } // namespace Catch
  5799. // end catch_timing.hpp
  5800. #include <utility>
  5801. namespace Catch {
  5802. namespace Benchmark {
  5803. namespace Detail {
  5804. template <typename Clock, typename Fun, typename... Args>
  5805. TimingOf<Clock, Fun(Args...)> measure(Fun&& fun, Args&&... args) {
  5806. auto start = Clock::now();
  5807. auto&& r = Detail::complete_invoke(fun, std::forward<Args>(args)...);
  5808. auto end = Clock::now();
  5809. auto delta = end - start;
  5810. return { delta, std::forward<decltype(r)>(r), 1 };
  5811. }
  5812. } // namespace Detail
  5813. } // namespace Benchmark
  5814. } // namespace Catch
  5815. // end catch_measure.hpp
  5816. #include <utility>
  5817. #include <type_traits>
  5818. namespace Catch {
  5819. namespace Benchmark {
  5820. namespace Detail {
  5821. template <typename Clock, typename Fun>
  5822. TimingOf<Clock, Fun(int)> measure_one(Fun&& fun, int iters, std::false_type) {
  5823. return Detail::measure<Clock>(fun, iters);
  5824. }
  5825. template <typename Clock, typename Fun>
  5826. TimingOf<Clock, Fun(Chronometer)> measure_one(Fun&& fun, int iters, std::true_type) {
  5827. Detail::ChronometerModel<Clock> meter;
  5828. auto&& result = Detail::complete_invoke(fun, Chronometer(meter, iters));
  5829. return { meter.elapsed(), std::move(result), iters };
  5830. }
  5831. template <typename Clock, typename Fun>
  5832. using run_for_at_least_argument_t = typename std::conditional<is_callable<Fun(Chronometer)>::value, Chronometer, int>::type;
  5833. struct optimized_away_error : std::exception {
  5834. const char* what() const noexcept override {
  5835. return "could not measure benchmark, maybe it was optimized away";
  5836. }
  5837. };
  5838. template <typename Clock, typename Fun>
  5839. TimingOf<Clock, Fun(run_for_at_least_argument_t<Clock, Fun>)> run_for_at_least(ClockDuration<Clock> how_long, int seed, Fun&& fun) {
  5840. auto iters = seed;
  5841. while (iters < (1 << 30)) {
  5842. auto&& Timing = measure_one<Clock>(fun, iters, is_callable<Fun(Chronometer)>());
  5843. if (Timing.elapsed >= how_long) {
  5844. return { Timing.elapsed, std::move(Timing.result), iters };
  5845. }
  5846. iters *= 2;
  5847. }
  5848. throw optimized_away_error{};
  5849. }
  5850. } // namespace Detail
  5851. } // namespace Benchmark
  5852. } // namespace Catch
  5853. // end catch_run_for_at_least.hpp
  5854. #include <algorithm>
  5855. namespace Catch {
  5856. namespace Benchmark {
  5857. template <typename Duration>
  5858. struct ExecutionPlan {
  5859. int iterations_per_sample;
  5860. Duration estimated_duration;
  5861. Detail::BenchmarkFunction benchmark;
  5862. Duration warmup_time;
  5863. int warmup_iterations;
  5864. template <typename Duration2>
  5865. operator ExecutionPlan<Duration2>() const {
  5866. return { iterations_per_sample, estimated_duration, benchmark, warmup_time, warmup_iterations };
  5867. }
  5868. template <typename Clock>
  5869. std::vector<FloatDuration<Clock>> run(const IConfig &cfg, Environment<FloatDuration<Clock>> env) const {
  5870. // warmup a bit
  5871. Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_iterations, Detail::repeat(now<Clock>{}));
  5872. std::vector<FloatDuration<Clock>> times;
  5873. times.reserve(cfg.benchmarkSamples());
  5874. std::generate_n(std::back_inserter(times), cfg.benchmarkSamples(), [this, env] {
  5875. Detail::ChronometerModel<Clock> model;
  5876. this->benchmark(Chronometer(model, iterations_per_sample));
  5877. auto sample_time = model.elapsed() - env.clock_cost.mean;
  5878. if (sample_time < FloatDuration<Clock>::zero()) sample_time = FloatDuration<Clock>::zero();
  5879. return sample_time / iterations_per_sample;
  5880. });
  5881. return times;
  5882. }
  5883. };
  5884. } // namespace Benchmark
  5885. } // namespace Catch
  5886. // end catch_execution_plan.hpp
  5887. // start catch_estimate_clock.hpp
  5888. // Environment measurement
  5889. // start catch_stats.hpp
  5890. // Statistical analysis tools
  5891. #include <algorithm>
  5892. #include <functional>
  5893. #include <vector>
  5894. #include <numeric>
  5895. #include <tuple>
  5896. #include <cmath>
  5897. #include <utility>
  5898. #include <cstddef>
  5899. namespace Catch {
  5900. namespace Benchmark {
  5901. namespace Detail {
  5902. using sample = std::vector<double>;
  5903. double weighted_average_quantile(int k, int q, std::vector<double>::iterator first, std::vector<double>::iterator last);
  5904. template <typename Iterator>
  5905. OutlierClassification classify_outliers(Iterator first, Iterator last) {
  5906. std::vector<double> copy(first, last);
  5907. auto q1 = weighted_average_quantile(1, 4, copy.begin(), copy.end());
  5908. auto q3 = weighted_average_quantile(3, 4, copy.begin(), copy.end());
  5909. auto iqr = q3 - q1;
  5910. auto los = q1 - (iqr * 3.);
  5911. auto lom = q1 - (iqr * 1.5);
  5912. auto him = q3 + (iqr * 1.5);
  5913. auto his = q3 + (iqr * 3.);
  5914. OutlierClassification o;
  5915. for (; first != last; ++first) {
  5916. auto&& t = *first;
  5917. if (t < los) ++o.low_severe;
  5918. else if (t < lom) ++o.low_mild;
  5919. else if (t > his) ++o.high_severe;
  5920. else if (t > him) ++o.high_mild;
  5921. ++o.samples_seen;
  5922. }
  5923. return o;
  5924. }
  5925. template <typename Iterator>
  5926. double mean(Iterator first, Iterator last) {
  5927. auto count = last - first;
  5928. double sum = std::accumulate(first, last, 0.);
  5929. return sum / count;
  5930. }
  5931. template <typename URng, typename Iterator, typename Estimator>
  5932. sample resample(URng& rng, int resamples, Iterator first, Iterator last, Estimator& estimator) {
  5933. auto n = last - first;
  5934. std::uniform_int_distribution<decltype(n)> dist(0, n - 1);
  5935. sample out;
  5936. out.reserve(resamples);
  5937. std::generate_n(std::back_inserter(out), resamples, [n, first, &estimator, &dist, &rng] {
  5938. std::vector<double> resampled;
  5939. resampled.reserve(n);
  5940. std::generate_n(std::back_inserter(resampled), n, [first, &dist, &rng] { return first[dist(rng)]; });
  5941. return estimator(resampled.begin(), resampled.end());
  5942. });
  5943. std::sort(out.begin(), out.end());
  5944. return out;
  5945. }
  5946. template <typename Estimator, typename Iterator>
  5947. sample jackknife(Estimator&& estimator, Iterator first, Iterator last) {
  5948. auto n = last - first;
  5949. auto second = std::next(first);
  5950. sample results;
  5951. results.reserve(n);
  5952. for (auto it = first; it != last; ++it) {
  5953. std::iter_swap(it, first);
  5954. results.push_back(estimator(second, last));
  5955. }
  5956. return results;
  5957. }
  5958. inline double normal_cdf(double x) {
  5959. return std::erfc(-x / std::sqrt(2.0)) / 2.0;
  5960. }
  5961. double erfc_inv(double x);
  5962. double normal_quantile(double p);
  5963. template <typename Iterator, typename Estimator>
  5964. Estimate<double> bootstrap(double confidence_level, Iterator first, Iterator last, sample const& resample, Estimator&& estimator) {
  5965. auto n_samples = last - first;
  5966. double point = estimator(first, last);
  5967. // Degenerate case with a single sample
  5968. if (n_samples == 1) return { point, point, point, confidence_level };
  5969. sample jack = jackknife(estimator, first, last);
  5970. double jack_mean = mean(jack.begin(), jack.end());
  5971. double sum_squares, sum_cubes;
  5972. 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> {
  5973. auto d = jack_mean - x;
  5974. auto d2 = d * d;
  5975. auto d3 = d2 * d;
  5976. return { sqcb.first + d2, sqcb.second + d3 };
  5977. });
  5978. double accel = sum_cubes / (6 * std::pow(sum_squares, 1.5));
  5979. int n = static_cast<int>(resample.size());
  5980. double prob_n = std::count_if(resample.begin(), resample.end(), [point](double x) { return x < point; }) / (double)n;
  5981. // degenerate case with uniform samples
  5982. if (prob_n == 0) return { point, point, point, confidence_level };
  5983. double bias = normal_quantile(prob_n);
  5984. double z1 = normal_quantile((1. - confidence_level) / 2.);
  5985. auto cumn = [n](double x) -> int {
  5986. return std::lround(normal_cdf(x) * n); };
  5987. auto a = [bias, accel](double b) { return bias + b / (1. - accel * b); };
  5988. double b1 = bias + z1;
  5989. double b2 = bias - z1;
  5990. double a1 = a(b1);
  5991. double a2 = a(b2);
  5992. auto lo = std::max(cumn(a1), 0);
  5993. auto hi = std::min(cumn(a2), n - 1);
  5994. return { point, resample[lo], resample[hi], confidence_level };
  5995. }
  5996. double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n);
  5997. struct bootstrap_analysis {
  5998. Estimate<double> mean;
  5999. Estimate<double> standard_deviation;
  6000. double outlier_variance;
  6001. };
  6002. bootstrap_analysis analyse_samples(double confidence_level, int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last);
  6003. } // namespace Detail
  6004. } // namespace Benchmark
  6005. } // namespace Catch
  6006. // end catch_stats.hpp
  6007. #include <algorithm>
  6008. #include <iterator>
  6009. #include <tuple>
  6010. #include <vector>
  6011. #include <cmath>
  6012. namespace Catch {
  6013. namespace Benchmark {
  6014. namespace Detail {
  6015. template <typename Clock>
  6016. std::vector<double> resolution(int k) {
  6017. std::vector<TimePoint<Clock>> times;
  6018. times.reserve(k + 1);
  6019. std::generate_n(std::back_inserter(times), k + 1, now<Clock>{});
  6020. std::vector<double> deltas;
  6021. deltas.reserve(k);
  6022. std::transform(std::next(times.begin()), times.end(), times.begin(),
  6023. std::back_inserter(deltas),
  6024. [](TimePoint<Clock> a, TimePoint<Clock> b) { return static_cast<double>((a - b).count()); });
  6025. return deltas;
  6026. }
  6027. const auto warmup_iterations = 10000;
  6028. const auto warmup_time = std::chrono::milliseconds(100);
  6029. const auto minimum_ticks = 1000;
  6030. const auto warmup_seed = 10000;
  6031. const auto clock_resolution_estimation_time = std::chrono::milliseconds(500);
  6032. const auto clock_cost_estimation_time_limit = std::chrono::seconds(1);
  6033. const auto clock_cost_estimation_tick_limit = 100000;
  6034. const auto clock_cost_estimation_time = std::chrono::milliseconds(10);
  6035. const auto clock_cost_estimation_iterations = 10000;
  6036. template <typename Clock>
  6037. int warmup() {
  6038. return run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_seed, &resolution<Clock>)
  6039. .iterations;
  6040. }
  6041. template <typename Clock>
  6042. EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_resolution(int iterations) {
  6043. auto r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_resolution_estimation_time), iterations, &resolution<Clock>)
  6044. .result;
  6045. return {
  6046. FloatDuration<Clock>(mean(r.begin(), r.end())),
  6047. classify_outliers(r.begin(), r.end()),
  6048. };
  6049. }
  6050. template <typename Clock>
  6051. EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_cost(FloatDuration<Clock> resolution) {
  6052. auto time_limit = std::min(resolution * clock_cost_estimation_tick_limit, FloatDuration<Clock>(clock_cost_estimation_time_limit));
  6053. auto time_clock = [](int k) {
  6054. return Detail::measure<Clock>([k] {
  6055. for (int i = 0; i < k; ++i) {
  6056. volatile auto ignored = Clock::now();
  6057. (void)ignored;
  6058. }
  6059. }).elapsed;
  6060. };
  6061. time_clock(1);
  6062. int iters = clock_cost_estimation_iterations;
  6063. auto&& r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_cost_estimation_time), iters, time_clock);
  6064. std::vector<double> times;
  6065. int nsamples = static_cast<int>(std::ceil(time_limit / r.elapsed));
  6066. times.reserve(nsamples);
  6067. std::generate_n(std::back_inserter(times), nsamples, [time_clock, &r] {
  6068. return static_cast<double>((time_clock(r.iterations) / r.iterations).count());
  6069. });
  6070. return {
  6071. FloatDuration<Clock>(mean(times.begin(), times.end())),
  6072. classify_outliers(times.begin(), times.end()),
  6073. };
  6074. }
  6075. template <typename Clock>
  6076. Environment<FloatDuration<Clock>> measure_environment() {
  6077. static Environment<FloatDuration<Clock>>* env = nullptr;
  6078. if (env) {
  6079. return *env;
  6080. }
  6081. auto iters = Detail::warmup<Clock>();
  6082. auto resolution = Detail::estimate_clock_resolution<Clock>(iters);
  6083. auto cost = Detail::estimate_clock_cost<Clock>(resolution.mean);
  6084. env = new Environment<FloatDuration<Clock>>{ resolution, cost };
  6085. return *env;
  6086. }
  6087. } // namespace Detail
  6088. } // namespace Benchmark
  6089. } // namespace Catch
  6090. // end catch_estimate_clock.hpp
  6091. // start catch_analyse.hpp
  6092. // Run and analyse one benchmark
  6093. // start catch_sample_analysis.hpp
  6094. // Benchmark results
  6095. #include <algorithm>
  6096. #include <vector>
  6097. #include <string>
  6098. #include <iterator>
  6099. namespace Catch {
  6100. namespace Benchmark {
  6101. template <typename Duration>
  6102. struct SampleAnalysis {
  6103. std::vector<Duration> samples;
  6104. Estimate<Duration> mean;
  6105. Estimate<Duration> standard_deviation;
  6106. OutlierClassification outliers;
  6107. double outlier_variance;
  6108. template <typename Duration2>
  6109. operator SampleAnalysis<Duration2>() const {
  6110. std::vector<Duration2> samples2;
  6111. samples2.reserve(samples.size());
  6112. std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration d) { return Duration2(d); });
  6113. return {
  6114. std::move(samples2),
  6115. mean,
  6116. standard_deviation,
  6117. outliers,
  6118. outlier_variance,
  6119. };
  6120. }
  6121. };
  6122. } // namespace Benchmark
  6123. } // namespace Catch
  6124. // end catch_sample_analysis.hpp
  6125. #include <algorithm>
  6126. #include <iterator>
  6127. #include <vector>
  6128. namespace Catch {
  6129. namespace Benchmark {
  6130. namespace Detail {
  6131. template <typename Duration, typename Iterator>
  6132. SampleAnalysis<Duration> analyse(const IConfig &cfg, Environment<Duration>, Iterator first, Iterator last) {
  6133. if (!cfg.benchmarkNoAnalysis()) {
  6134. std::vector<double> samples;
  6135. samples.reserve(last - first);
  6136. std::transform(first, last, std::back_inserter(samples), [](Duration d) { return d.count(); });
  6137. auto analysis = Catch::Benchmark::Detail::analyse_samples(cfg.benchmarkConfidenceInterval(), cfg.benchmarkResamples(), samples.begin(), samples.end());
  6138. auto outliers = Catch::Benchmark::Detail::classify_outliers(samples.begin(), samples.end());
  6139. auto wrap_estimate = [](Estimate<double> e) {
  6140. return Estimate<Duration> {
  6141. Duration(e.point),
  6142. Duration(e.lower_bound),
  6143. Duration(e.upper_bound),
  6144. e.confidence_interval,
  6145. };
  6146. };
  6147. std::vector<Duration> samples2;
  6148. samples2.reserve(samples.size());
  6149. std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](double d) { return Duration(d); });
  6150. return {
  6151. std::move(samples2),
  6152. wrap_estimate(analysis.mean),
  6153. wrap_estimate(analysis.standard_deviation),
  6154. outliers,
  6155. analysis.outlier_variance,
  6156. };
  6157. } else {
  6158. std::vector<Duration> samples;
  6159. samples.reserve(last - first);
  6160. Duration mean = Duration(0);
  6161. int i = 0;
  6162. for (auto it = first; it < last; ++it, ++i) {
  6163. samples.push_back(Duration(*it));
  6164. mean += Duration(*it);
  6165. }
  6166. mean /= i;
  6167. return {
  6168. std::move(samples),
  6169. Estimate<Duration>{mean, mean, mean, 0.0},
  6170. Estimate<Duration>{Duration(0), Duration(0), Duration(0), 0.0},
  6171. OutlierClassification{},
  6172. 0.0
  6173. };
  6174. }
  6175. }
  6176. } // namespace Detail
  6177. } // namespace Benchmark
  6178. } // namespace Catch
  6179. // end catch_analyse.hpp
  6180. #include <algorithm>
  6181. #include <functional>
  6182. #include <string>
  6183. #include <vector>
  6184. #include <cmath>
  6185. namespace Catch {
  6186. namespace Benchmark {
  6187. struct Benchmark {
  6188. Benchmark(std::string &&name)
  6189. : name(std::move(name)) {}
  6190. template <class FUN>
  6191. Benchmark(std::string &&name, FUN &&func)
  6192. : fun(std::move(func)), name(std::move(name)) {}
  6193. template <typename Clock>
  6194. ExecutionPlan<FloatDuration<Clock>> prepare(const IConfig &cfg, Environment<FloatDuration<Clock>> env) const {
  6195. auto min_time = env.clock_resolution.mean * Detail::minimum_ticks;
  6196. auto run_time = std::max(min_time, std::chrono::duration_cast<decltype(min_time)>(Detail::warmup_time));
  6197. auto&& test = Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(run_time), 1, fun);
  6198. int new_iters = static_cast<int>(std::ceil(min_time * test.iterations / test.elapsed));
  6199. return { new_iters, test.elapsed / test.iterations * new_iters * cfg.benchmarkSamples(), fun, std::chrono::duration_cast<FloatDuration<Clock>>(Detail::warmup_time), Detail::warmup_iterations };
  6200. }
  6201. template <typename Clock = default_clock>
  6202. void run() {
  6203. IConfigPtr cfg = getCurrentContext().getConfig();
  6204. auto env = Detail::measure_environment<Clock>();
  6205. getResultCapture().benchmarkPreparing(name);
  6206. CATCH_TRY{
  6207. auto plan = user_code([&] {
  6208. return prepare<Clock>(*cfg, env);
  6209. });
  6210. BenchmarkInfo info {
  6211. name,
  6212. plan.estimated_duration.count(),
  6213. plan.iterations_per_sample,
  6214. cfg->benchmarkSamples(),
  6215. cfg->benchmarkResamples(),
  6216. env.clock_resolution.mean.count(),
  6217. env.clock_cost.mean.count()
  6218. };
  6219. getResultCapture().benchmarkStarting(info);
  6220. auto samples = user_code([&] {
  6221. return plan.template run<Clock>(*cfg, env);
  6222. });
  6223. auto analysis = Detail::analyse(*cfg, env, samples.begin(), samples.end());
  6224. BenchmarkStats<std::chrono::duration<double, std::nano>> stats{ info, analysis.samples, analysis.mean, analysis.standard_deviation, analysis.outliers, analysis.outlier_variance };
  6225. getResultCapture().benchmarkEnded(stats);
  6226. } CATCH_CATCH_ALL{
  6227. if (translateActiveException() != Detail::benchmarkErrorMsg) // benchmark errors have been reported, otherwise rethrow.
  6228. std::rethrow_exception(std::current_exception());
  6229. }
  6230. }
  6231. // sets lambda to be used in fun *and* executes benchmark!
  6232. template <typename Fun,
  6233. typename std::enable_if<!Detail::is_related<Fun, Benchmark>::value, int>::type = 0>
  6234. Benchmark & operator=(Fun func) {
  6235. fun = Detail::BenchmarkFunction(func);
  6236. run();
  6237. return *this;
  6238. }
  6239. explicit operator bool() {
  6240. return true;
  6241. }
  6242. private:
  6243. Detail::BenchmarkFunction fun;
  6244. std::string name;
  6245. };
  6246. }
  6247. } // namespace Catch
  6248. #define INTERNAL_CATCH_GET_1_ARG(arg1, arg2, ...) arg1
  6249. #define INTERNAL_CATCH_GET_2_ARG(arg1, arg2, ...) arg2
  6250. #define INTERNAL_CATCH_BENCHMARK(BenchmarkName, name, benchmarkIndex)\
  6251. if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \
  6252. BenchmarkName = [&](int benchmarkIndex)
  6253. #define INTERNAL_CATCH_BENCHMARK_ADVANCED(BenchmarkName, name)\
  6254. if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \
  6255. BenchmarkName = [&]
  6256. // end catch_benchmark.hpp
  6257. #endif
  6258. #endif // ! CATCH_CONFIG_IMPL_ONLY
  6259. #ifdef CATCH_IMPL
  6260. // start catch_impl.hpp
  6261. #ifdef __clang__
  6262. #pragma clang diagnostic push
  6263. #pragma clang diagnostic ignored "-Wweak-vtables"
  6264. #endif
  6265. // Keep these here for external reporters
  6266. // start catch_test_case_tracker.h
  6267. #include <string>
  6268. #include <vector>
  6269. #include <memory>
  6270. namespace Catch {
  6271. namespace TestCaseTracking {
  6272. struct NameAndLocation {
  6273. std::string name;
  6274. SourceLineInfo location;
  6275. NameAndLocation( std::string const& _name, SourceLineInfo const& _location );
  6276. };
  6277. struct ITracker;
  6278. using ITrackerPtr = std::shared_ptr<ITracker>;
  6279. struct ITracker {
  6280. virtual ~ITracker();
  6281. // static queries
  6282. virtual NameAndLocation const& nameAndLocation() const = 0;
  6283. // dynamic queries
  6284. virtual bool isComplete() const = 0; // Successfully completed or failed
  6285. virtual bool isSuccessfullyCompleted() const = 0;
  6286. virtual bool isOpen() const = 0; // Started but not complete
  6287. virtual bool hasChildren() const = 0;
  6288. virtual ITracker& parent() = 0;
  6289. // actions
  6290. virtual void close() = 0; // Successfully complete
  6291. virtual void fail() = 0;
  6292. virtual void markAsNeedingAnotherRun() = 0;
  6293. virtual void addChild( ITrackerPtr const& child ) = 0;
  6294. virtual ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) = 0;
  6295. virtual void openChild() = 0;
  6296. // Debug/ checking
  6297. virtual bool isSectionTracker() const = 0;
  6298. virtual bool isGeneratorTracker() const = 0;
  6299. };
  6300. class TrackerContext {
  6301. enum RunState {
  6302. NotStarted,
  6303. Executing,
  6304. CompletedCycle
  6305. };
  6306. ITrackerPtr m_rootTracker;
  6307. ITracker* m_currentTracker = nullptr;
  6308. RunState m_runState = NotStarted;
  6309. public:
  6310. ITracker& startRun();
  6311. void endRun();
  6312. void startCycle();
  6313. void completeCycle();
  6314. bool completedCycle() const;
  6315. ITracker& currentTracker();
  6316. void setCurrentTracker( ITracker* tracker );
  6317. };
  6318. class TrackerBase : public ITracker {
  6319. protected:
  6320. enum CycleState {
  6321. NotStarted,
  6322. Executing,
  6323. ExecutingChildren,
  6324. NeedsAnotherRun,
  6325. CompletedSuccessfully,
  6326. Failed
  6327. };
  6328. using Children = std::vector<ITrackerPtr>;
  6329. NameAndLocation m_nameAndLocation;
  6330. TrackerContext& m_ctx;
  6331. ITracker* m_parent;
  6332. Children m_children;
  6333. CycleState m_runState = NotStarted;
  6334. public:
  6335. TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  6336. NameAndLocation const& nameAndLocation() const override;
  6337. bool isComplete() const override;
  6338. bool isSuccessfullyCompleted() const override;
  6339. bool isOpen() const override;
  6340. bool hasChildren() const override;
  6341. void addChild( ITrackerPtr const& child ) override;
  6342. ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) override;
  6343. ITracker& parent() override;
  6344. void openChild() override;
  6345. bool isSectionTracker() const override;
  6346. bool isGeneratorTracker() const override;
  6347. void open();
  6348. void close() override;
  6349. void fail() override;
  6350. void markAsNeedingAnotherRun() override;
  6351. private:
  6352. void moveToParent();
  6353. void moveToThis();
  6354. };
  6355. class SectionTracker : public TrackerBase {
  6356. std::vector<std::string> m_filters;
  6357. public:
  6358. SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  6359. bool isSectionTracker() const override;
  6360. bool isComplete() const override;
  6361. static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation );
  6362. void tryOpen();
  6363. void addInitialFilters( std::vector<std::string> const& filters );
  6364. void addNextFilters( std::vector<std::string> const& filters );
  6365. };
  6366. } // namespace TestCaseTracking
  6367. using TestCaseTracking::ITracker;
  6368. using TestCaseTracking::TrackerContext;
  6369. using TestCaseTracking::SectionTracker;
  6370. } // namespace Catch
  6371. // end catch_test_case_tracker.h
  6372. // start catch_leak_detector.h
  6373. namespace Catch {
  6374. struct LeakDetector {
  6375. LeakDetector();
  6376. ~LeakDetector();
  6377. };
  6378. }
  6379. // end catch_leak_detector.h
  6380. // Cpp files will be included in the single-header file here
  6381. // start catch_stats.cpp
  6382. // Statistical analysis tools
  6383. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  6384. #include <cassert>
  6385. #include <random>
  6386. #if defined(CATCH_CONFIG_USE_ASYNC)
  6387. #include <future>
  6388. #endif
  6389. namespace {
  6390. double erf_inv(double x) {
  6391. // Code accompanying the article "Approximating the erfinv function" in GPU Computing Gems, Volume 2
  6392. double w, p;
  6393. w = -log((1.0 - x) * (1.0 + x));
  6394. if (w < 6.250000) {
  6395. w = w - 3.125000;
  6396. p = -3.6444120640178196996e-21;
  6397. p = -1.685059138182016589e-19 + p * w;
  6398. p = 1.2858480715256400167e-18 + p * w;
  6399. p = 1.115787767802518096e-17 + p * w;
  6400. p = -1.333171662854620906e-16 + p * w;
  6401. p = 2.0972767875968561637e-17 + p * w;
  6402. p = 6.6376381343583238325e-15 + p * w;
  6403. p = -4.0545662729752068639e-14 + p * w;
  6404. p = -8.1519341976054721522e-14 + p * w;
  6405. p = 2.6335093153082322977e-12 + p * w;
  6406. p = -1.2975133253453532498e-11 + p * w;
  6407. p = -5.4154120542946279317e-11 + p * w;
  6408. p = 1.051212273321532285e-09 + p * w;
  6409. p = -4.1126339803469836976e-09 + p * w;
  6410. p = -2.9070369957882005086e-08 + p * w;
  6411. p = 4.2347877827932403518e-07 + p * w;
  6412. p = -1.3654692000834678645e-06 + p * w;
  6413. p = -1.3882523362786468719e-05 + p * w;
  6414. p = 0.0001867342080340571352 + p * w;
  6415. p = -0.00074070253416626697512 + p * w;
  6416. p = -0.0060336708714301490533 + p * w;
  6417. p = 0.24015818242558961693 + p * w;
  6418. p = 1.6536545626831027356 + p * w;
  6419. } else if (w < 16.000000) {
  6420. w = sqrt(w) - 3.250000;
  6421. p = 2.2137376921775787049e-09;
  6422. p = 9.0756561938885390979e-08 + p * w;
  6423. p = -2.7517406297064545428e-07 + p * w;
  6424. p = 1.8239629214389227755e-08 + p * w;
  6425. p = 1.5027403968909827627e-06 + p * w;
  6426. p = -4.013867526981545969e-06 + p * w;
  6427. p = 2.9234449089955446044e-06 + p * w;
  6428. p = 1.2475304481671778723e-05 + p * w;
  6429. p = -4.7318229009055733981e-05 + p * w;
  6430. p = 6.8284851459573175448e-05 + p * w;
  6431. p = 2.4031110387097893999e-05 + p * w;
  6432. p = -0.0003550375203628474796 + p * w;
  6433. p = 0.00095328937973738049703 + p * w;
  6434. p = -0.0016882755560235047313 + p * w;
  6435. p = 0.0024914420961078508066 + p * w;
  6436. p = -0.0037512085075692412107 + p * w;
  6437. p = 0.005370914553590063617 + p * w;
  6438. p = 1.0052589676941592334 + p * w;
  6439. p = 3.0838856104922207635 + p * w;
  6440. } else {
  6441. w = sqrt(w) - 5.000000;
  6442. p = -2.7109920616438573243e-11;
  6443. p = -2.5556418169965252055e-10 + p * w;
  6444. p = 1.5076572693500548083e-09 + p * w;
  6445. p = -3.7894654401267369937e-09 + p * w;
  6446. p = 7.6157012080783393804e-09 + p * w;
  6447. p = -1.4960026627149240478e-08 + p * w;
  6448. p = 2.9147953450901080826e-08 + p * w;
  6449. p = -6.7711997758452339498e-08 + p * w;
  6450. p = 2.2900482228026654717e-07 + p * w;
  6451. p = -9.9298272942317002539e-07 + p * w;
  6452. p = 4.5260625972231537039e-06 + p * w;
  6453. p = -1.9681778105531670567e-05 + p * w;
  6454. p = 7.5995277030017761139e-05 + p * w;
  6455. p = -0.00021503011930044477347 + p * w;
  6456. p = -0.00013871931833623122026 + p * w;
  6457. p = 1.0103004648645343977 + p * w;
  6458. p = 4.8499064014085844221 + p * w;
  6459. }
  6460. return p * x;
  6461. }
  6462. double standard_deviation(std::vector<double>::iterator first, std::vector<double>::iterator last) {
  6463. auto m = Catch::Benchmark::Detail::mean(first, last);
  6464. double variance = std::accumulate(first, last, 0., [m](double a, double b) {
  6465. double diff = b - m;
  6466. return a + diff * diff;
  6467. }) / (last - first);
  6468. return std::sqrt(variance);
  6469. }
  6470. }
  6471. namespace Catch {
  6472. namespace Benchmark {
  6473. namespace Detail {
  6474. double weighted_average_quantile(int k, int q, std::vector<double>::iterator first, std::vector<double>::iterator last) {
  6475. auto count = last - first;
  6476. double idx = (count - 1) * k / static_cast<double>(q);
  6477. int j = static_cast<int>(idx);
  6478. double g = idx - j;
  6479. std::nth_element(first, first + j, last);
  6480. auto xj = first[j];
  6481. if (g == 0) return xj;
  6482. auto xj1 = *std::min_element(first + (j + 1), last);
  6483. return xj + g * (xj1 - xj);
  6484. }
  6485. double erfc_inv(double x) {
  6486. return erf_inv(1.0 - x);
  6487. }
  6488. double normal_quantile(double p) {
  6489. static const double ROOT_TWO = std::sqrt(2.0);
  6490. double result = 0.0;
  6491. assert(p >= 0 && p <= 1);
  6492. if (p < 0 || p > 1) {
  6493. return result;
  6494. }
  6495. result = -erfc_inv(2.0 * p);
  6496. // result *= normal distribution standard deviation (1.0) * sqrt(2)
  6497. result *= /*sd * */ ROOT_TWO;
  6498. // result += normal disttribution mean (0)
  6499. return result;
  6500. }
  6501. double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n) {
  6502. double sb = stddev.point;
  6503. double mn = mean.point / n;
  6504. double mg_min = mn / 2.;
  6505. double sg = std::min(mg_min / 4., sb / std::sqrt(n));
  6506. double sg2 = sg * sg;
  6507. double sb2 = sb * sb;
  6508. auto c_max = [n, mn, sb2, sg2](double x) -> double {
  6509. double k = mn - x;
  6510. double d = k * k;
  6511. double nd = n * d;
  6512. double k0 = -n * nd;
  6513. double k1 = sb2 - n * sg2 + nd;
  6514. double det = k1 * k1 - 4 * sg2 * k0;
  6515. return (int)(-2. * k0 / (k1 + std::sqrt(det)));
  6516. };
  6517. auto var_out = [n, sb2, sg2](double c) {
  6518. double nc = n - c;
  6519. return (nc / n) * (sb2 - nc * sg2);
  6520. };
  6521. return std::min(var_out(1), var_out(std::min(c_max(0.), c_max(mg_min)))) / sb2;
  6522. }
  6523. bootstrap_analysis analyse_samples(double confidence_level, int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last) {
  6524. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  6525. static std::random_device entropy;
  6526. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  6527. auto n = static_cast<int>(last - first); // seriously, one can't use integral types without hell in C++
  6528. auto mean = &Detail::mean<std::vector<double>::iterator>;
  6529. auto stddev = &standard_deviation;
  6530. #if defined(CATCH_CONFIG_USE_ASYNC)
  6531. auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
  6532. auto seed = entropy();
  6533. return std::async(std::launch::async, [=] {
  6534. std::mt19937 rng(seed);
  6535. auto resampled = resample(rng, n_resamples, first, last, f);
  6536. return bootstrap(confidence_level, first, last, resampled, f);
  6537. });
  6538. };
  6539. auto mean_future = Estimate(mean);
  6540. auto stddev_future = Estimate(stddev);
  6541. auto mean_estimate = mean_future.get();
  6542. auto stddev_estimate = stddev_future.get();
  6543. #else
  6544. auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
  6545. auto seed = entropy();
  6546. std::mt19937 rng(seed);
  6547. auto resampled = resample(rng, n_resamples, first, last, f);
  6548. return bootstrap(confidence_level, first, last, resampled, f);
  6549. };
  6550. auto mean_estimate = Estimate(mean);
  6551. auto stddev_estimate = Estimate(stddev);
  6552. #endif // CATCH_USE_ASYNC
  6553. double outlier_variance = Detail::outlier_variance(mean_estimate, stddev_estimate, n);
  6554. return { mean_estimate, stddev_estimate, outlier_variance };
  6555. }
  6556. } // namespace Detail
  6557. } // namespace Benchmark
  6558. } // namespace Catch
  6559. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  6560. // end catch_stats.cpp
  6561. // start catch_approx.cpp
  6562. #include <cmath>
  6563. #include <limits>
  6564. namespace {
  6565. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  6566. // But without the subtraction to allow for INFINITY in comparison
  6567. bool marginComparison(double lhs, double rhs, double margin) {
  6568. return (lhs + margin >= rhs) && (rhs + margin >= lhs);
  6569. }
  6570. }
  6571. namespace Catch {
  6572. namespace Detail {
  6573. Approx::Approx ( double value )
  6574. : m_epsilon( std::numeric_limits<float>::epsilon()*100 ),
  6575. m_margin( 0.0 ),
  6576. m_scale( 0.0 ),
  6577. m_value( value )
  6578. {}
  6579. Approx Approx::custom() {
  6580. return Approx( 0 );
  6581. }
  6582. Approx Approx::operator-() const {
  6583. auto temp(*this);
  6584. temp.m_value = -temp.m_value;
  6585. return temp;
  6586. }
  6587. std::string Approx::toString() const {
  6588. ReusableStringStream rss;
  6589. rss << "Approx( " << ::Catch::Detail::stringify( m_value ) << " )";
  6590. return rss.str();
  6591. }
  6592. bool Approx::equalityComparisonImpl(const double other) const {
  6593. // First try with fixed margin, then compute margin based on epsilon, scale and Approx's value
  6594. // Thanks to Richard Harris for his help refining the scaled margin value
  6595. return marginComparison(m_value, other, m_margin) || marginComparison(m_value, other, m_epsilon * (m_scale + std::fabs(m_value)));
  6596. }
  6597. void Approx::setMargin(double newMargin) {
  6598. CATCH_ENFORCE(newMargin >= 0,
  6599. "Invalid Approx::margin: " << newMargin << '.'
  6600. << " Approx::Margin has to be non-negative.");
  6601. m_margin = newMargin;
  6602. }
  6603. void Approx::setEpsilon(double newEpsilon) {
  6604. CATCH_ENFORCE(newEpsilon >= 0 && newEpsilon <= 1.0,
  6605. "Invalid Approx::epsilon: " << newEpsilon << '.'
  6606. << " Approx::epsilon has to be in [0, 1]");
  6607. m_epsilon = newEpsilon;
  6608. }
  6609. } // end namespace Detail
  6610. namespace literals {
  6611. Detail::Approx operator "" _a(long double val) {
  6612. return Detail::Approx(val);
  6613. }
  6614. Detail::Approx operator "" _a(unsigned long long val) {
  6615. return Detail::Approx(val);
  6616. }
  6617. } // end namespace literals
  6618. std::string StringMaker<Catch::Detail::Approx>::convert(Catch::Detail::Approx const& value) {
  6619. return value.toString();
  6620. }
  6621. } // end namespace Catch
  6622. // end catch_approx.cpp
  6623. // start catch_assertionhandler.cpp
  6624. // start catch_debugger.h
  6625. namespace Catch {
  6626. bool isDebuggerActive();
  6627. }
  6628. #ifdef CATCH_PLATFORM_MAC
  6629. #define CATCH_TRAP() __asm__("int $3\n" : : ) /* NOLINT */
  6630. #elif defined(CATCH_PLATFORM_LINUX)
  6631. // If we can use inline assembler, do it because this allows us to break
  6632. // directly at the location of the failing check instead of breaking inside
  6633. // raise() called from it, i.e. one stack frame below.
  6634. #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64))
  6635. #define CATCH_TRAP() asm volatile ("int $3") /* NOLINT */
  6636. #else // Fall back to the generic way.
  6637. #include <signal.h>
  6638. #define CATCH_TRAP() raise(SIGTRAP)
  6639. #endif
  6640. #elif defined(_MSC_VER)
  6641. #define CATCH_TRAP() __debugbreak()
  6642. #elif defined(__MINGW32__)
  6643. extern "C" __declspec(dllimport) void __stdcall DebugBreak();
  6644. #define CATCH_TRAP() DebugBreak()
  6645. #endif
  6646. #ifdef CATCH_TRAP
  6647. #define CATCH_BREAK_INTO_DEBUGGER() []{ if( Catch::isDebuggerActive() ) { CATCH_TRAP(); } }()
  6648. #else
  6649. #define CATCH_BREAK_INTO_DEBUGGER() []{}()
  6650. #endif
  6651. // end catch_debugger.h
  6652. // start catch_run_context.h
  6653. // start catch_fatal_condition.h
  6654. // start catch_windows_h_proxy.h
  6655. #if defined(CATCH_PLATFORM_WINDOWS)
  6656. #if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX)
  6657. # define CATCH_DEFINED_NOMINMAX
  6658. # define NOMINMAX
  6659. #endif
  6660. #if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN)
  6661. # define CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  6662. # define WIN32_LEAN_AND_MEAN
  6663. #endif
  6664. #ifdef __AFXDLL
  6665. #include <AfxWin.h>
  6666. #else
  6667. #include <windows.h>
  6668. #endif
  6669. #ifdef CATCH_DEFINED_NOMINMAX
  6670. # undef NOMINMAX
  6671. #endif
  6672. #ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  6673. # undef WIN32_LEAN_AND_MEAN
  6674. #endif
  6675. #endif // defined(CATCH_PLATFORM_WINDOWS)
  6676. // end catch_windows_h_proxy.h
  6677. #if defined( CATCH_CONFIG_WINDOWS_SEH )
  6678. namespace Catch {
  6679. struct FatalConditionHandler {
  6680. static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo);
  6681. FatalConditionHandler();
  6682. static void reset();
  6683. ~FatalConditionHandler();
  6684. private:
  6685. static bool isSet;
  6686. static ULONG guaranteeSize;
  6687. static PVOID exceptionHandlerHandle;
  6688. };
  6689. } // namespace Catch
  6690. #elif defined ( CATCH_CONFIG_POSIX_SIGNALS )
  6691. #include <signal.h>
  6692. namespace Catch {
  6693. struct FatalConditionHandler {
  6694. static bool isSet;
  6695. static struct sigaction oldSigActions[];
  6696. static stack_t oldSigStack;
  6697. static char altStackMem[];
  6698. static void handleSignal( int sig );
  6699. FatalConditionHandler();
  6700. ~FatalConditionHandler();
  6701. static void reset();
  6702. };
  6703. } // namespace Catch
  6704. #else
  6705. namespace Catch {
  6706. struct FatalConditionHandler {
  6707. void reset();
  6708. };
  6709. }
  6710. #endif
  6711. // end catch_fatal_condition.h
  6712. #include <string>
  6713. namespace Catch {
  6714. struct IMutableContext;
  6715. ///////////////////////////////////////////////////////////////////////////
  6716. class RunContext : public IResultCapture, public IRunner {
  6717. public:
  6718. RunContext( RunContext const& ) = delete;
  6719. RunContext& operator =( RunContext const& ) = delete;
  6720. explicit RunContext( IConfigPtr const& _config, IStreamingReporterPtr&& reporter );
  6721. ~RunContext() override;
  6722. void testGroupStarting( std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount );
  6723. void testGroupEnded( std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount );
  6724. Totals runTest(TestCase const& testCase);
  6725. IConfigPtr config() const;
  6726. IStreamingReporter& reporter() const;
  6727. public: // IResultCapture
  6728. // Assertion handlers
  6729. void handleExpr
  6730. ( AssertionInfo const& info,
  6731. ITransientExpression const& expr,
  6732. AssertionReaction& reaction ) override;
  6733. void handleMessage
  6734. ( AssertionInfo const& info,
  6735. ResultWas::OfType resultType,
  6736. StringRef const& message,
  6737. AssertionReaction& reaction ) override;
  6738. void handleUnexpectedExceptionNotThrown
  6739. ( AssertionInfo const& info,
  6740. AssertionReaction& reaction ) override;
  6741. void handleUnexpectedInflightException
  6742. ( AssertionInfo const& info,
  6743. std::string const& message,
  6744. AssertionReaction& reaction ) override;
  6745. void handleIncomplete
  6746. ( AssertionInfo const& info ) override;
  6747. void handleNonExpr
  6748. ( AssertionInfo const &info,
  6749. ResultWas::OfType resultType,
  6750. AssertionReaction &reaction ) override;
  6751. bool sectionStarted( SectionInfo const& sectionInfo, Counts& assertions ) override;
  6752. void sectionEnded( SectionEndInfo const& endInfo ) override;
  6753. void sectionEndedEarly( SectionEndInfo const& endInfo ) override;
  6754. auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& override;
  6755. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  6756. void benchmarkPreparing( std::string const& name ) override;
  6757. void benchmarkStarting( BenchmarkInfo const& info ) override;
  6758. void benchmarkEnded( BenchmarkStats<> const& stats ) override;
  6759. void benchmarkFailed( std::string const& error ) override;
  6760. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  6761. void pushScopedMessage( MessageInfo const& message ) override;
  6762. void popScopedMessage( MessageInfo const& message ) override;
  6763. void emplaceUnscopedMessage( MessageBuilder const& builder ) override;
  6764. std::string getCurrentTestName() const override;
  6765. const AssertionResult* getLastResult() const override;
  6766. void exceptionEarlyReported() override;
  6767. void handleFatalErrorCondition( StringRef message ) override;
  6768. bool lastAssertionPassed() override;
  6769. void assertionPassed() override;
  6770. public:
  6771. // !TBD We need to do this another way!
  6772. bool aborting() const final;
  6773. private:
  6774. void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr );
  6775. void invokeActiveTestCase();
  6776. void resetAssertionInfo();
  6777. bool testForMissingAssertions( Counts& assertions );
  6778. void assertionEnded( AssertionResult const& result );
  6779. void reportExpr
  6780. ( AssertionInfo const &info,
  6781. ResultWas::OfType resultType,
  6782. ITransientExpression const *expr,
  6783. bool negated );
  6784. void populateReaction( AssertionReaction& reaction );
  6785. private:
  6786. void handleUnfinishedSections();
  6787. TestRunInfo m_runInfo;
  6788. IMutableContext& m_context;
  6789. TestCase const* m_activeTestCase = nullptr;
  6790. ITracker* m_testCaseTracker = nullptr;
  6791. Option<AssertionResult> m_lastResult;
  6792. IConfigPtr m_config;
  6793. Totals m_totals;
  6794. IStreamingReporterPtr m_reporter;
  6795. std::vector<MessageInfo> m_messages;
  6796. std::vector<ScopedMessage> m_messageScopes; /* Keeps owners of so-called unscoped messages. */
  6797. AssertionInfo m_lastAssertionInfo;
  6798. std::vector<SectionEndInfo> m_unfinishedSections;
  6799. std::vector<ITracker*> m_activeSections;
  6800. TrackerContext m_trackerContext;
  6801. bool m_lastAssertionPassed = false;
  6802. bool m_shouldReportUnexpected = true;
  6803. bool m_includeSuccessfulResults;
  6804. };
  6805. } // end namespace Catch
  6806. // end catch_run_context.h
  6807. namespace Catch {
  6808. namespace {
  6809. auto operator <<( std::ostream& os, ITransientExpression const& expr ) -> std::ostream& {
  6810. expr.streamReconstructedExpression( os );
  6811. return os;
  6812. }
  6813. }
  6814. LazyExpression::LazyExpression( bool isNegated )
  6815. : m_isNegated( isNegated )
  6816. {}
  6817. LazyExpression::LazyExpression( LazyExpression const& other ) : m_isNegated( other.m_isNegated ) {}
  6818. LazyExpression::operator bool() const {
  6819. return m_transientExpression != nullptr;
  6820. }
  6821. auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream& {
  6822. if( lazyExpr.m_isNegated )
  6823. os << "!";
  6824. if( lazyExpr ) {
  6825. if( lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression() )
  6826. os << "(" << *lazyExpr.m_transientExpression << ")";
  6827. else
  6828. os << *lazyExpr.m_transientExpression;
  6829. }
  6830. else {
  6831. os << "{** error - unchecked empty expression requested **}";
  6832. }
  6833. return os;
  6834. }
  6835. AssertionHandler::AssertionHandler
  6836. ( StringRef const& macroName,
  6837. SourceLineInfo const& lineInfo,
  6838. StringRef capturedExpression,
  6839. ResultDisposition::Flags resultDisposition )
  6840. : m_assertionInfo{ macroName, lineInfo, capturedExpression, resultDisposition },
  6841. m_resultCapture( getResultCapture() )
  6842. {}
  6843. void AssertionHandler::handleExpr( ITransientExpression const& expr ) {
  6844. m_resultCapture.handleExpr( m_assertionInfo, expr, m_reaction );
  6845. }
  6846. void AssertionHandler::handleMessage(ResultWas::OfType resultType, StringRef const& message) {
  6847. m_resultCapture.handleMessage( m_assertionInfo, resultType, message, m_reaction );
  6848. }
  6849. auto AssertionHandler::allowThrows() const -> bool {
  6850. return getCurrentContext().getConfig()->allowThrows();
  6851. }
  6852. void AssertionHandler::complete() {
  6853. setCompleted();
  6854. if( m_reaction.shouldDebugBreak ) {
  6855. // If you find your debugger stopping you here then go one level up on the
  6856. // call-stack for the code that caused it (typically a failed assertion)
  6857. // (To go back to the test and change execution, jump over the throw, next)
  6858. CATCH_BREAK_INTO_DEBUGGER();
  6859. }
  6860. if (m_reaction.shouldThrow) {
  6861. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  6862. throw Catch::TestFailureException();
  6863. #else
  6864. CATCH_ERROR( "Test failure requires aborting test!" );
  6865. #endif
  6866. }
  6867. }
  6868. void AssertionHandler::setCompleted() {
  6869. m_completed = true;
  6870. }
  6871. void AssertionHandler::handleUnexpectedInflightException() {
  6872. m_resultCapture.handleUnexpectedInflightException( m_assertionInfo, Catch::translateActiveException(), m_reaction );
  6873. }
  6874. void AssertionHandler::handleExceptionThrownAsExpected() {
  6875. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  6876. }
  6877. void AssertionHandler::handleExceptionNotThrownAsExpected() {
  6878. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  6879. }
  6880. void AssertionHandler::handleUnexpectedExceptionNotThrown() {
  6881. m_resultCapture.handleUnexpectedExceptionNotThrown( m_assertionInfo, m_reaction );
  6882. }
  6883. void AssertionHandler::handleThrowingCallSkipped() {
  6884. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  6885. }
  6886. // This is the overload that takes a string and infers the Equals matcher from it
  6887. // The more general overload, that takes any string matcher, is in catch_capture_matchers.cpp
  6888. void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString ) {
  6889. handleExceptionMatchExpr( handler, Matchers::Equals( str ), matcherString );
  6890. }
  6891. } // namespace Catch
  6892. // end catch_assertionhandler.cpp
  6893. // start catch_assertionresult.cpp
  6894. namespace Catch {
  6895. AssertionResultData::AssertionResultData(ResultWas::OfType _resultType, LazyExpression const & _lazyExpression):
  6896. lazyExpression(_lazyExpression),
  6897. resultType(_resultType) {}
  6898. std::string AssertionResultData::reconstructExpression() const {
  6899. if( reconstructedExpression.empty() ) {
  6900. if( lazyExpression ) {
  6901. ReusableStringStream rss;
  6902. rss << lazyExpression;
  6903. reconstructedExpression = rss.str();
  6904. }
  6905. }
  6906. return reconstructedExpression;
  6907. }
  6908. AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data )
  6909. : m_info( info ),
  6910. m_resultData( data )
  6911. {}
  6912. // Result was a success
  6913. bool AssertionResult::succeeded() const {
  6914. return Catch::isOk( m_resultData.resultType );
  6915. }
  6916. // Result was a success, or failure is suppressed
  6917. bool AssertionResult::isOk() const {
  6918. return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition );
  6919. }
  6920. ResultWas::OfType AssertionResult::getResultType() const {
  6921. return m_resultData.resultType;
  6922. }
  6923. bool AssertionResult::hasExpression() const {
  6924. return m_info.capturedExpression[0] != 0;
  6925. }
  6926. bool AssertionResult::hasMessage() const {
  6927. return !m_resultData.message.empty();
  6928. }
  6929. std::string AssertionResult::getExpression() const {
  6930. if( isFalseTest( m_info.resultDisposition ) )
  6931. return "!(" + m_info.capturedExpression + ")";
  6932. else
  6933. return m_info.capturedExpression;
  6934. }
  6935. std::string AssertionResult::getExpressionInMacro() const {
  6936. std::string expr;
  6937. if( m_info.macroName[0] == 0 )
  6938. expr = m_info.capturedExpression;
  6939. else {
  6940. expr.reserve( m_info.macroName.size() + m_info.capturedExpression.size() + 4 );
  6941. expr += m_info.macroName;
  6942. expr += "( ";
  6943. expr += m_info.capturedExpression;
  6944. expr += " )";
  6945. }
  6946. return expr;
  6947. }
  6948. bool AssertionResult::hasExpandedExpression() const {
  6949. return hasExpression() && getExpandedExpression() != getExpression();
  6950. }
  6951. std::string AssertionResult::getExpandedExpression() const {
  6952. std::string expr = m_resultData.reconstructExpression();
  6953. return expr.empty()
  6954. ? getExpression()
  6955. : expr;
  6956. }
  6957. std::string AssertionResult::getMessage() const {
  6958. return m_resultData.message;
  6959. }
  6960. SourceLineInfo AssertionResult::getSourceInfo() const {
  6961. return m_info.lineInfo;
  6962. }
  6963. StringRef AssertionResult::getTestMacroName() const {
  6964. return m_info.macroName;
  6965. }
  6966. } // end namespace Catch
  6967. // end catch_assertionresult.cpp
  6968. // start catch_capture_matchers.cpp
  6969. namespace Catch {
  6970. using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
  6971. // This is the general overload that takes a any string matcher
  6972. // There is another overload, in catch_assertionhandler.h/.cpp, that only takes a string and infers
  6973. // the Equals matcher (so the header does not mention matchers)
  6974. void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString ) {
  6975. std::string exceptionMessage = Catch::translateActiveException();
  6976. MatchExpr<std::string, StringMatcher const&> expr( exceptionMessage, matcher, matcherString );
  6977. handler.handleExpr( expr );
  6978. }
  6979. } // namespace Catch
  6980. // end catch_capture_matchers.cpp
  6981. // start catch_commandline.cpp
  6982. // start catch_commandline.h
  6983. // start catch_clara.h
  6984. // Use Catch's value for console width (store Clara's off to the side, if present)
  6985. #ifdef CLARA_CONFIG_CONSOLE_WIDTH
  6986. #define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  6987. #undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  6988. #endif
  6989. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH-1
  6990. #ifdef __clang__
  6991. #pragma clang diagnostic push
  6992. #pragma clang diagnostic ignored "-Wweak-vtables"
  6993. #pragma clang diagnostic ignored "-Wexit-time-destructors"
  6994. #pragma clang diagnostic ignored "-Wshadow"
  6995. #endif
  6996. // start clara.hpp
  6997. // Copyright 2017 Two Blue Cubes Ltd. All rights reserved.
  6998. //
  6999. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  7000. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  7001. //
  7002. // See https://github.com/philsquared/Clara for more details
  7003. // Clara v1.1.5
  7004. #ifndef CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  7005. #define CATCH_CLARA_CONFIG_CONSOLE_WIDTH 80
  7006. #endif
  7007. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  7008. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  7009. #endif
  7010. #ifndef CLARA_CONFIG_OPTIONAL_TYPE
  7011. #ifdef __has_include
  7012. #if __has_include(<optional>) && __cplusplus >= 201703L
  7013. #include <optional>
  7014. #define CLARA_CONFIG_OPTIONAL_TYPE std::optional
  7015. #endif
  7016. #endif
  7017. #endif
  7018. // ----------- #included from clara_textflow.hpp -----------
  7019. // TextFlowCpp
  7020. //
  7021. // A single-header library for wrapping and laying out basic text, by Phil Nash
  7022. //
  7023. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  7024. // file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  7025. //
  7026. // This project is hosted at https://github.com/philsquared/textflowcpp
  7027. #include <cassert>
  7028. #include <ostream>
  7029. #include <sstream>
  7030. #include <vector>
  7031. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  7032. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80
  7033. #endif
  7034. namespace Catch {
  7035. namespace clara {
  7036. namespace TextFlow {
  7037. inline auto isWhitespace(char c) -> bool {
  7038. static std::string chars = " \t\n\r";
  7039. return chars.find(c) != std::string::npos;
  7040. }
  7041. inline auto isBreakableBefore(char c) -> bool {
  7042. static std::string chars = "[({<|";
  7043. return chars.find(c) != std::string::npos;
  7044. }
  7045. inline auto isBreakableAfter(char c) -> bool {
  7046. static std::string chars = "])}>.,:;*+-=&/\\";
  7047. return chars.find(c) != std::string::npos;
  7048. }
  7049. class Columns;
  7050. class Column {
  7051. std::vector<std::string> m_strings;
  7052. size_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH;
  7053. size_t m_indent = 0;
  7054. size_t m_initialIndent = std::string::npos;
  7055. public:
  7056. class iterator {
  7057. friend Column;
  7058. Column const& m_column;
  7059. size_t m_stringIndex = 0;
  7060. size_t m_pos = 0;
  7061. size_t m_len = 0;
  7062. size_t m_end = 0;
  7063. bool m_suffix = false;
  7064. iterator(Column const& column, size_t stringIndex)
  7065. : m_column(column),
  7066. m_stringIndex(stringIndex) {}
  7067. auto line() const -> std::string const& { return m_column.m_strings[m_stringIndex]; }
  7068. auto isBoundary(size_t at) const -> bool {
  7069. assert(at > 0);
  7070. assert(at <= line().size());
  7071. return at == line().size() ||
  7072. (isWhitespace(line()[at]) && !isWhitespace(line()[at - 1])) ||
  7073. isBreakableBefore(line()[at]) ||
  7074. isBreakableAfter(line()[at - 1]);
  7075. }
  7076. void calcLength() {
  7077. assert(m_stringIndex < m_column.m_strings.size());
  7078. m_suffix = false;
  7079. auto width = m_column.m_width - indent();
  7080. m_end = m_pos;
  7081. if (line()[m_pos] == '\n') {
  7082. ++m_end;
  7083. }
  7084. while (m_end < line().size() && line()[m_end] != '\n')
  7085. ++m_end;
  7086. if (m_end < m_pos + width) {
  7087. m_len = m_end - m_pos;
  7088. } else {
  7089. size_t len = width;
  7090. while (len > 0 && !isBoundary(m_pos + len))
  7091. --len;
  7092. while (len > 0 && isWhitespace(line()[m_pos + len - 1]))
  7093. --len;
  7094. if (len > 0) {
  7095. m_len = len;
  7096. } else {
  7097. m_suffix = true;
  7098. m_len = width - 1;
  7099. }
  7100. }
  7101. }
  7102. auto indent() const -> size_t {
  7103. auto initial = m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos;
  7104. return initial == std::string::npos ? m_column.m_indent : initial;
  7105. }
  7106. auto addIndentAndSuffix(std::string const &plain) const -> std::string {
  7107. return std::string(indent(), ' ') + (m_suffix ? plain + "-" : plain);
  7108. }
  7109. public:
  7110. using difference_type = std::ptrdiff_t;
  7111. using value_type = std::string;
  7112. using pointer = value_type * ;
  7113. using reference = value_type & ;
  7114. using iterator_category = std::forward_iterator_tag;
  7115. explicit iterator(Column const& column) : m_column(column) {
  7116. assert(m_column.m_width > m_column.m_indent);
  7117. assert(m_column.m_initialIndent == std::string::npos || m_column.m_width > m_column.m_initialIndent);
  7118. calcLength();
  7119. if (m_len == 0)
  7120. m_stringIndex++; // Empty string
  7121. }
  7122. auto operator *() const -> std::string {
  7123. assert(m_stringIndex < m_column.m_strings.size());
  7124. assert(m_pos <= m_end);
  7125. return addIndentAndSuffix(line().substr(m_pos, m_len));
  7126. }
  7127. auto operator ++() -> iterator& {
  7128. m_pos += m_len;
  7129. if (m_pos < line().size() && line()[m_pos] == '\n')
  7130. m_pos += 1;
  7131. else
  7132. while (m_pos < line().size() && isWhitespace(line()[m_pos]))
  7133. ++m_pos;
  7134. if (m_pos == line().size()) {
  7135. m_pos = 0;
  7136. ++m_stringIndex;
  7137. }
  7138. if (m_stringIndex < m_column.m_strings.size())
  7139. calcLength();
  7140. return *this;
  7141. }
  7142. auto operator ++(int) -> iterator {
  7143. iterator prev(*this);
  7144. operator++();
  7145. return prev;
  7146. }
  7147. auto operator ==(iterator const& other) const -> bool {
  7148. return
  7149. m_pos == other.m_pos &&
  7150. m_stringIndex == other.m_stringIndex &&
  7151. &m_column == &other.m_column;
  7152. }
  7153. auto operator !=(iterator const& other) const -> bool {
  7154. return !operator==(other);
  7155. }
  7156. };
  7157. using const_iterator = iterator;
  7158. explicit Column(std::string const& text) { m_strings.push_back(text); }
  7159. auto width(size_t newWidth) -> Column& {
  7160. assert(newWidth > 0);
  7161. m_width = newWidth;
  7162. return *this;
  7163. }
  7164. auto indent(size_t newIndent) -> Column& {
  7165. m_indent = newIndent;
  7166. return *this;
  7167. }
  7168. auto initialIndent(size_t newIndent) -> Column& {
  7169. m_initialIndent = newIndent;
  7170. return *this;
  7171. }
  7172. auto width() const -> size_t { return m_width; }
  7173. auto begin() const -> iterator { return iterator(*this); }
  7174. auto end() const -> iterator { return { *this, m_strings.size() }; }
  7175. inline friend std::ostream& operator << (std::ostream& os, Column const& col) {
  7176. bool first = true;
  7177. for (auto line : col) {
  7178. if (first)
  7179. first = false;
  7180. else
  7181. os << "\n";
  7182. os << line;
  7183. }
  7184. return os;
  7185. }
  7186. auto operator + (Column const& other)->Columns;
  7187. auto toString() const -> std::string {
  7188. std::ostringstream oss;
  7189. oss << *this;
  7190. return oss.str();
  7191. }
  7192. };
  7193. class Spacer : public Column {
  7194. public:
  7195. explicit Spacer(size_t spaceWidth) : Column("") {
  7196. width(spaceWidth);
  7197. }
  7198. };
  7199. class Columns {
  7200. std::vector<Column> m_columns;
  7201. public:
  7202. class iterator {
  7203. friend Columns;
  7204. struct EndTag {};
  7205. std::vector<Column> const& m_columns;
  7206. std::vector<Column::iterator> m_iterators;
  7207. size_t m_activeIterators;
  7208. iterator(Columns const& columns, EndTag)
  7209. : m_columns(columns.m_columns),
  7210. m_activeIterators(0) {
  7211. m_iterators.reserve(m_columns.size());
  7212. for (auto const& col : m_columns)
  7213. m_iterators.push_back(col.end());
  7214. }
  7215. public:
  7216. using difference_type = std::ptrdiff_t;
  7217. using value_type = std::string;
  7218. using pointer = value_type * ;
  7219. using reference = value_type & ;
  7220. using iterator_category = std::forward_iterator_tag;
  7221. explicit iterator(Columns const& columns)
  7222. : m_columns(columns.m_columns),
  7223. m_activeIterators(m_columns.size()) {
  7224. m_iterators.reserve(m_columns.size());
  7225. for (auto const& col : m_columns)
  7226. m_iterators.push_back(col.begin());
  7227. }
  7228. auto operator ==(iterator const& other) const -> bool {
  7229. return m_iterators == other.m_iterators;
  7230. }
  7231. auto operator !=(iterator const& other) const -> bool {
  7232. return m_iterators != other.m_iterators;
  7233. }
  7234. auto operator *() const -> std::string {
  7235. std::string row, padding;
  7236. for (size_t i = 0; i < m_columns.size(); ++i) {
  7237. auto width = m_columns[i].width();
  7238. if (m_iterators[i] != m_columns[i].end()) {
  7239. std::string col = *m_iterators[i];
  7240. row += padding + col;
  7241. if (col.size() < width)
  7242. padding = std::string(width - col.size(), ' ');
  7243. else
  7244. padding = "";
  7245. } else {
  7246. padding += std::string(width, ' ');
  7247. }
  7248. }
  7249. return row;
  7250. }
  7251. auto operator ++() -> iterator& {
  7252. for (size_t i = 0; i < m_columns.size(); ++i) {
  7253. if (m_iterators[i] != m_columns[i].end())
  7254. ++m_iterators[i];
  7255. }
  7256. return *this;
  7257. }
  7258. auto operator ++(int) -> iterator {
  7259. iterator prev(*this);
  7260. operator++();
  7261. return prev;
  7262. }
  7263. };
  7264. using const_iterator = iterator;
  7265. auto begin() const -> iterator { return iterator(*this); }
  7266. auto end() const -> iterator { return { *this, iterator::EndTag() }; }
  7267. auto operator += (Column const& col) -> Columns& {
  7268. m_columns.push_back(col);
  7269. return *this;
  7270. }
  7271. auto operator + (Column const& col) -> Columns {
  7272. Columns combined = *this;
  7273. combined += col;
  7274. return combined;
  7275. }
  7276. inline friend std::ostream& operator << (std::ostream& os, Columns const& cols) {
  7277. bool first = true;
  7278. for (auto line : cols) {
  7279. if (first)
  7280. first = false;
  7281. else
  7282. os << "\n";
  7283. os << line;
  7284. }
  7285. return os;
  7286. }
  7287. auto toString() const -> std::string {
  7288. std::ostringstream oss;
  7289. oss << *this;
  7290. return oss.str();
  7291. }
  7292. };
  7293. inline auto Column::operator + (Column const& other) -> Columns {
  7294. Columns cols;
  7295. cols += *this;
  7296. cols += other;
  7297. return cols;
  7298. }
  7299. }
  7300. }
  7301. }
  7302. // ----------- end of #include from clara_textflow.hpp -----------
  7303. // ........... back in clara.hpp
  7304. #include <cctype>
  7305. #include <string>
  7306. #include <memory>
  7307. #include <set>
  7308. #include <algorithm>
  7309. #if !defined(CATCH_PLATFORM_WINDOWS) && ( defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) )
  7310. #define CATCH_PLATFORM_WINDOWS
  7311. #endif
  7312. namespace Catch { namespace clara {
  7313. namespace detail {
  7314. // Traits for extracting arg and return type of lambdas (for single argument lambdas)
  7315. template<typename L>
  7316. struct UnaryLambdaTraits : UnaryLambdaTraits<decltype( &L::operator() )> {};
  7317. template<typename ClassT, typename ReturnT, typename... Args>
  7318. struct UnaryLambdaTraits<ReturnT( ClassT::* )( Args... ) const> {
  7319. static const bool isValid = false;
  7320. };
  7321. template<typename ClassT, typename ReturnT, typename ArgT>
  7322. struct UnaryLambdaTraits<ReturnT( ClassT::* )( ArgT ) const> {
  7323. static const bool isValid = true;
  7324. using ArgType = typename std::remove_const<typename std::remove_reference<ArgT>::type>::type;
  7325. using ReturnType = ReturnT;
  7326. };
  7327. class TokenStream;
  7328. // Transport for raw args (copied from main args, or supplied via init list for testing)
  7329. class Args {
  7330. friend TokenStream;
  7331. std::string m_exeName;
  7332. std::vector<std::string> m_args;
  7333. public:
  7334. Args( int argc, char const* const* argv )
  7335. : m_exeName(argv[0]),
  7336. m_args(argv + 1, argv + argc) {}
  7337. Args( std::initializer_list<std::string> args )
  7338. : m_exeName( *args.begin() ),
  7339. m_args( args.begin()+1, args.end() )
  7340. {}
  7341. auto exeName() const -> std::string {
  7342. return m_exeName;
  7343. }
  7344. };
  7345. // Wraps a token coming from a token stream. These may not directly correspond to strings as a single string
  7346. // may encode an option + its argument if the : or = form is used
  7347. enum class TokenType {
  7348. Option, Argument
  7349. };
  7350. struct Token {
  7351. TokenType type;
  7352. std::string token;
  7353. };
  7354. inline auto isOptPrefix( char c ) -> bool {
  7355. return c == '-'
  7356. #ifdef CATCH_PLATFORM_WINDOWS
  7357. || c == '/'
  7358. #endif
  7359. ;
  7360. }
  7361. // Abstracts iterators into args as a stream of tokens, with option arguments uniformly handled
  7362. class TokenStream {
  7363. using Iterator = std::vector<std::string>::const_iterator;
  7364. Iterator it;
  7365. Iterator itEnd;
  7366. std::vector<Token> m_tokenBuffer;
  7367. void loadBuffer() {
  7368. m_tokenBuffer.resize( 0 );
  7369. // Skip any empty strings
  7370. while( it != itEnd && it->empty() )
  7371. ++it;
  7372. if( it != itEnd ) {
  7373. auto const &next = *it;
  7374. if( isOptPrefix( next[0] ) ) {
  7375. auto delimiterPos = next.find_first_of( " :=" );
  7376. if( delimiterPos != std::string::npos ) {
  7377. m_tokenBuffer.push_back( { TokenType::Option, next.substr( 0, delimiterPos ) } );
  7378. m_tokenBuffer.push_back( { TokenType::Argument, next.substr( delimiterPos + 1 ) } );
  7379. } else {
  7380. if( next[1] != '-' && next.size() > 2 ) {
  7381. std::string opt = "- ";
  7382. for( size_t i = 1; i < next.size(); ++i ) {
  7383. opt[1] = next[i];
  7384. m_tokenBuffer.push_back( { TokenType::Option, opt } );
  7385. }
  7386. } else {
  7387. m_tokenBuffer.push_back( { TokenType::Option, next } );
  7388. }
  7389. }
  7390. } else {
  7391. m_tokenBuffer.push_back( { TokenType::Argument, next } );
  7392. }
  7393. }
  7394. }
  7395. public:
  7396. explicit TokenStream( Args const &args ) : TokenStream( args.m_args.begin(), args.m_args.end() ) {}
  7397. TokenStream( Iterator it, Iterator itEnd ) : it( it ), itEnd( itEnd ) {
  7398. loadBuffer();
  7399. }
  7400. explicit operator bool() const {
  7401. return !m_tokenBuffer.empty() || it != itEnd;
  7402. }
  7403. auto count() const -> size_t { return m_tokenBuffer.size() + (itEnd - it); }
  7404. auto operator*() const -> Token {
  7405. assert( !m_tokenBuffer.empty() );
  7406. return m_tokenBuffer.front();
  7407. }
  7408. auto operator->() const -> Token const * {
  7409. assert( !m_tokenBuffer.empty() );
  7410. return &m_tokenBuffer.front();
  7411. }
  7412. auto operator++() -> TokenStream & {
  7413. if( m_tokenBuffer.size() >= 2 ) {
  7414. m_tokenBuffer.erase( m_tokenBuffer.begin() );
  7415. } else {
  7416. if( it != itEnd )
  7417. ++it;
  7418. loadBuffer();
  7419. }
  7420. return *this;
  7421. }
  7422. };
  7423. class ResultBase {
  7424. public:
  7425. enum Type {
  7426. Ok, LogicError, RuntimeError
  7427. };
  7428. protected:
  7429. ResultBase( Type type ) : m_type( type ) {}
  7430. virtual ~ResultBase() = default;
  7431. virtual void enforceOk() const = 0;
  7432. Type m_type;
  7433. };
  7434. template<typename T>
  7435. class ResultValueBase : public ResultBase {
  7436. public:
  7437. auto value() const -> T const & {
  7438. enforceOk();
  7439. return m_value;
  7440. }
  7441. protected:
  7442. ResultValueBase( Type type ) : ResultBase( type ) {}
  7443. ResultValueBase( ResultValueBase const &other ) : ResultBase( other ) {
  7444. if( m_type == ResultBase::Ok )
  7445. new( &m_value ) T( other.m_value );
  7446. }
  7447. ResultValueBase( Type, T const &value ) : ResultBase( Ok ) {
  7448. new( &m_value ) T( value );
  7449. }
  7450. auto operator=( ResultValueBase const &other ) -> ResultValueBase & {
  7451. if( m_type == ResultBase::Ok )
  7452. m_value.~T();
  7453. ResultBase::operator=(other);
  7454. if( m_type == ResultBase::Ok )
  7455. new( &m_value ) T( other.m_value );
  7456. return *this;
  7457. }
  7458. ~ResultValueBase() override {
  7459. if( m_type == Ok )
  7460. m_value.~T();
  7461. }
  7462. union {
  7463. T m_value;
  7464. };
  7465. };
  7466. template<>
  7467. class ResultValueBase<void> : public ResultBase {
  7468. protected:
  7469. using ResultBase::ResultBase;
  7470. };
  7471. template<typename T = void>
  7472. class BasicResult : public ResultValueBase<T> {
  7473. public:
  7474. template<typename U>
  7475. explicit BasicResult( BasicResult<U> const &other )
  7476. : ResultValueBase<T>( other.type() ),
  7477. m_errorMessage( other.errorMessage() )
  7478. {
  7479. assert( type() != ResultBase::Ok );
  7480. }
  7481. template<typename U>
  7482. static auto ok( U const &value ) -> BasicResult { return { ResultBase::Ok, value }; }
  7483. static auto ok() -> BasicResult { return { ResultBase::Ok }; }
  7484. static auto logicError( std::string const &message ) -> BasicResult { return { ResultBase::LogicError, message }; }
  7485. static auto runtimeError( std::string const &message ) -> BasicResult { return { ResultBase::RuntimeError, message }; }
  7486. explicit operator bool() const { return m_type == ResultBase::Ok; }
  7487. auto type() const -> ResultBase::Type { return m_type; }
  7488. auto errorMessage() const -> std::string { return m_errorMessage; }
  7489. protected:
  7490. void enforceOk() const override {
  7491. // Errors shouldn't reach this point, but if they do
  7492. // the actual error message will be in m_errorMessage
  7493. assert( m_type != ResultBase::LogicError );
  7494. assert( m_type != ResultBase::RuntimeError );
  7495. if( m_type != ResultBase::Ok )
  7496. std::abort();
  7497. }
  7498. std::string m_errorMessage; // Only populated if resultType is an error
  7499. BasicResult( ResultBase::Type type, std::string const &message )
  7500. : ResultValueBase<T>(type),
  7501. m_errorMessage(message)
  7502. {
  7503. assert( m_type != ResultBase::Ok );
  7504. }
  7505. using ResultValueBase<T>::ResultValueBase;
  7506. using ResultBase::m_type;
  7507. };
  7508. enum class ParseResultType {
  7509. Matched, NoMatch, ShortCircuitAll, ShortCircuitSame
  7510. };
  7511. class ParseState {
  7512. public:
  7513. ParseState( ParseResultType type, TokenStream const &remainingTokens )
  7514. : m_type(type),
  7515. m_remainingTokens( remainingTokens )
  7516. {}
  7517. auto type() const -> ParseResultType { return m_type; }
  7518. auto remainingTokens() const -> TokenStream { return m_remainingTokens; }
  7519. private:
  7520. ParseResultType m_type;
  7521. TokenStream m_remainingTokens;
  7522. };
  7523. using Result = BasicResult<void>;
  7524. using ParserResult = BasicResult<ParseResultType>;
  7525. using InternalParseResult = BasicResult<ParseState>;
  7526. struct HelpColumns {
  7527. std::string left;
  7528. std::string right;
  7529. };
  7530. template<typename T>
  7531. inline auto convertInto( std::string const &source, T& target ) -> ParserResult {
  7532. std::stringstream ss;
  7533. ss << source;
  7534. ss >> target;
  7535. if( ss.fail() )
  7536. return ParserResult::runtimeError( "Unable to convert '" + source + "' to destination type" );
  7537. else
  7538. return ParserResult::ok( ParseResultType::Matched );
  7539. }
  7540. inline auto convertInto( std::string const &source, std::string& target ) -> ParserResult {
  7541. target = source;
  7542. return ParserResult::ok( ParseResultType::Matched );
  7543. }
  7544. inline auto convertInto( std::string const &source, bool &target ) -> ParserResult {
  7545. std::string srcLC = source;
  7546. std::transform( srcLC.begin(), srcLC.end(), srcLC.begin(), []( char c ) { return static_cast<char>( std::tolower(c) ); } );
  7547. if (srcLC == "y" || srcLC == "1" || srcLC == "true" || srcLC == "yes" || srcLC == "on")
  7548. target = true;
  7549. else if (srcLC == "n" || srcLC == "0" || srcLC == "false" || srcLC == "no" || srcLC == "off")
  7550. target = false;
  7551. else
  7552. return ParserResult::runtimeError( "Expected a boolean value but did not recognise: '" + source + "'" );
  7553. return ParserResult::ok( ParseResultType::Matched );
  7554. }
  7555. #ifdef CLARA_CONFIG_OPTIONAL_TYPE
  7556. template<typename T>
  7557. inline auto convertInto( std::string const &source, CLARA_CONFIG_OPTIONAL_TYPE<T>& target ) -> ParserResult {
  7558. T temp;
  7559. auto result = convertInto( source, temp );
  7560. if( result )
  7561. target = std::move(temp);
  7562. return result;
  7563. }
  7564. #endif // CLARA_CONFIG_OPTIONAL_TYPE
  7565. struct NonCopyable {
  7566. NonCopyable() = default;
  7567. NonCopyable( NonCopyable const & ) = delete;
  7568. NonCopyable( NonCopyable && ) = delete;
  7569. NonCopyable &operator=( NonCopyable const & ) = delete;
  7570. NonCopyable &operator=( NonCopyable && ) = delete;
  7571. };
  7572. struct BoundRef : NonCopyable {
  7573. virtual ~BoundRef() = default;
  7574. virtual auto isContainer() const -> bool { return false; }
  7575. virtual auto isFlag() const -> bool { return false; }
  7576. };
  7577. struct BoundValueRefBase : BoundRef {
  7578. virtual auto setValue( std::string const &arg ) -> ParserResult = 0;
  7579. };
  7580. struct BoundFlagRefBase : BoundRef {
  7581. virtual auto setFlag( bool flag ) -> ParserResult = 0;
  7582. virtual auto isFlag() const -> bool { return true; }
  7583. };
  7584. template<typename T>
  7585. struct BoundValueRef : BoundValueRefBase {
  7586. T &m_ref;
  7587. explicit BoundValueRef( T &ref ) : m_ref( ref ) {}
  7588. auto setValue( std::string const &arg ) -> ParserResult override {
  7589. return convertInto( arg, m_ref );
  7590. }
  7591. };
  7592. template<typename T>
  7593. struct BoundValueRef<std::vector<T>> : BoundValueRefBase {
  7594. std::vector<T> &m_ref;
  7595. explicit BoundValueRef( std::vector<T> &ref ) : m_ref( ref ) {}
  7596. auto isContainer() const -> bool override { return true; }
  7597. auto setValue( std::string const &arg ) -> ParserResult override {
  7598. T temp;
  7599. auto result = convertInto( arg, temp );
  7600. if( result )
  7601. m_ref.push_back( temp );
  7602. return result;
  7603. }
  7604. };
  7605. struct BoundFlagRef : BoundFlagRefBase {
  7606. bool &m_ref;
  7607. explicit BoundFlagRef( bool &ref ) : m_ref( ref ) {}
  7608. auto setFlag( bool flag ) -> ParserResult override {
  7609. m_ref = flag;
  7610. return ParserResult::ok( ParseResultType::Matched );
  7611. }
  7612. };
  7613. template<typename ReturnType>
  7614. struct LambdaInvoker {
  7615. static_assert( std::is_same<ReturnType, ParserResult>::value, "Lambda must return void or clara::ParserResult" );
  7616. template<typename L, typename ArgType>
  7617. static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
  7618. return lambda( arg );
  7619. }
  7620. };
  7621. template<>
  7622. struct LambdaInvoker<void> {
  7623. template<typename L, typename ArgType>
  7624. static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
  7625. lambda( arg );
  7626. return ParserResult::ok( ParseResultType::Matched );
  7627. }
  7628. };
  7629. template<typename ArgType, typename L>
  7630. inline auto invokeLambda( L const &lambda, std::string const &arg ) -> ParserResult {
  7631. ArgType temp{};
  7632. auto result = convertInto( arg, temp );
  7633. return !result
  7634. ? result
  7635. : LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( lambda, temp );
  7636. }
  7637. template<typename L>
  7638. struct BoundLambda : BoundValueRefBase {
  7639. L m_lambda;
  7640. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  7641. explicit BoundLambda( L const &lambda ) : m_lambda( lambda ) {}
  7642. auto setValue( std::string const &arg ) -> ParserResult override {
  7643. return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>( m_lambda, arg );
  7644. }
  7645. };
  7646. template<typename L>
  7647. struct BoundFlagLambda : BoundFlagRefBase {
  7648. L m_lambda;
  7649. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  7650. static_assert( std::is_same<typename UnaryLambdaTraits<L>::ArgType, bool>::value, "flags must be boolean" );
  7651. explicit BoundFlagLambda( L const &lambda ) : m_lambda( lambda ) {}
  7652. auto setFlag( bool flag ) -> ParserResult override {
  7653. return LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( m_lambda, flag );
  7654. }
  7655. };
  7656. enum class Optionality { Optional, Required };
  7657. struct Parser;
  7658. class ParserBase {
  7659. public:
  7660. virtual ~ParserBase() = default;
  7661. virtual auto validate() const -> Result { return Result::ok(); }
  7662. virtual auto parse( std::string const& exeName, TokenStream const &tokens) const -> InternalParseResult = 0;
  7663. virtual auto cardinality() const -> size_t { return 1; }
  7664. auto parse( Args const &args ) const -> InternalParseResult {
  7665. return parse( args.exeName(), TokenStream( args ) );
  7666. }
  7667. };
  7668. template<typename DerivedT>
  7669. class ComposableParserImpl : public ParserBase {
  7670. public:
  7671. template<typename T>
  7672. auto operator|( T const &other ) const -> Parser;
  7673. template<typename T>
  7674. auto operator+( T const &other ) const -> Parser;
  7675. };
  7676. // Common code and state for Args and Opts
  7677. template<typename DerivedT>
  7678. class ParserRefImpl : public ComposableParserImpl<DerivedT> {
  7679. protected:
  7680. Optionality m_optionality = Optionality::Optional;
  7681. std::shared_ptr<BoundRef> m_ref;
  7682. std::string m_hint;
  7683. std::string m_description;
  7684. explicit ParserRefImpl( std::shared_ptr<BoundRef> const &ref ) : m_ref( ref ) {}
  7685. public:
  7686. template<typename T>
  7687. ParserRefImpl( T &ref, std::string const &hint )
  7688. : m_ref( std::make_shared<BoundValueRef<T>>( ref ) ),
  7689. m_hint( hint )
  7690. {}
  7691. template<typename LambdaT>
  7692. ParserRefImpl( LambdaT const &ref, std::string const &hint )
  7693. : m_ref( std::make_shared<BoundLambda<LambdaT>>( ref ) ),
  7694. m_hint(hint)
  7695. {}
  7696. auto operator()( std::string const &description ) -> DerivedT & {
  7697. m_description = description;
  7698. return static_cast<DerivedT &>( *this );
  7699. }
  7700. auto optional() -> DerivedT & {
  7701. m_optionality = Optionality::Optional;
  7702. return static_cast<DerivedT &>( *this );
  7703. };
  7704. auto required() -> DerivedT & {
  7705. m_optionality = Optionality::Required;
  7706. return static_cast<DerivedT &>( *this );
  7707. };
  7708. auto isOptional() const -> bool {
  7709. return m_optionality == Optionality::Optional;
  7710. }
  7711. auto cardinality() const -> size_t override {
  7712. if( m_ref->isContainer() )
  7713. return 0;
  7714. else
  7715. return 1;
  7716. }
  7717. auto hint() const -> std::string { return m_hint; }
  7718. };
  7719. class ExeName : public ComposableParserImpl<ExeName> {
  7720. std::shared_ptr<std::string> m_name;
  7721. std::shared_ptr<BoundValueRefBase> m_ref;
  7722. template<typename LambdaT>
  7723. static auto makeRef(LambdaT const &lambda) -> std::shared_ptr<BoundValueRefBase> {
  7724. return std::make_shared<BoundLambda<LambdaT>>( lambda) ;
  7725. }
  7726. public:
  7727. ExeName() : m_name( std::make_shared<std::string>( "<executable>" ) ) {}
  7728. explicit ExeName( std::string &ref ) : ExeName() {
  7729. m_ref = std::make_shared<BoundValueRef<std::string>>( ref );
  7730. }
  7731. template<typename LambdaT>
  7732. explicit ExeName( LambdaT const& lambda ) : ExeName() {
  7733. m_ref = std::make_shared<BoundLambda<LambdaT>>( lambda );
  7734. }
  7735. // The exe name is not parsed out of the normal tokens, but is handled specially
  7736. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  7737. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
  7738. }
  7739. auto name() const -> std::string { return *m_name; }
  7740. auto set( std::string const& newName ) -> ParserResult {
  7741. auto lastSlash = newName.find_last_of( "\\/" );
  7742. auto filename = ( lastSlash == std::string::npos )
  7743. ? newName
  7744. : newName.substr( lastSlash+1 );
  7745. *m_name = filename;
  7746. if( m_ref )
  7747. return m_ref->setValue( filename );
  7748. else
  7749. return ParserResult::ok( ParseResultType::Matched );
  7750. }
  7751. };
  7752. class Arg : public ParserRefImpl<Arg> {
  7753. public:
  7754. using ParserRefImpl::ParserRefImpl;
  7755. auto parse( std::string const &, TokenStream const &tokens ) const -> InternalParseResult override {
  7756. auto validationResult = validate();
  7757. if( !validationResult )
  7758. return InternalParseResult( validationResult );
  7759. auto remainingTokens = tokens;
  7760. auto const &token = *remainingTokens;
  7761. if( token.type != TokenType::Argument )
  7762. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
  7763. assert( !m_ref->isFlag() );
  7764. auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
  7765. auto result = valueRef->setValue( remainingTokens->token );
  7766. if( !result )
  7767. return InternalParseResult( result );
  7768. else
  7769. return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
  7770. }
  7771. };
  7772. inline auto normaliseOpt( std::string const &optName ) -> std::string {
  7773. #ifdef CATCH_PLATFORM_WINDOWS
  7774. if( optName[0] == '/' )
  7775. return "-" + optName.substr( 1 );
  7776. else
  7777. #endif
  7778. return optName;
  7779. }
  7780. class Opt : public ParserRefImpl<Opt> {
  7781. protected:
  7782. std::vector<std::string> m_optNames;
  7783. public:
  7784. template<typename LambdaT>
  7785. explicit Opt( LambdaT const &ref ) : ParserRefImpl( std::make_shared<BoundFlagLambda<LambdaT>>( ref ) ) {}
  7786. explicit Opt( bool &ref ) : ParserRefImpl( std::make_shared<BoundFlagRef>( ref ) ) {}
  7787. template<typename LambdaT>
  7788. Opt( LambdaT const &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  7789. template<typename T>
  7790. Opt( T &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  7791. auto operator[]( std::string const &optName ) -> Opt & {
  7792. m_optNames.push_back( optName );
  7793. return *this;
  7794. }
  7795. auto getHelpColumns() const -> std::vector<HelpColumns> {
  7796. std::ostringstream oss;
  7797. bool first = true;
  7798. for( auto const &opt : m_optNames ) {
  7799. if (first)
  7800. first = false;
  7801. else
  7802. oss << ", ";
  7803. oss << opt;
  7804. }
  7805. if( !m_hint.empty() )
  7806. oss << " <" << m_hint << ">";
  7807. return { { oss.str(), m_description } };
  7808. }
  7809. auto isMatch( std::string const &optToken ) const -> bool {
  7810. auto normalisedToken = normaliseOpt( optToken );
  7811. for( auto const &name : m_optNames ) {
  7812. if( normaliseOpt( name ) == normalisedToken )
  7813. return true;
  7814. }
  7815. return false;
  7816. }
  7817. using ParserBase::parse;
  7818. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  7819. auto validationResult = validate();
  7820. if( !validationResult )
  7821. return InternalParseResult( validationResult );
  7822. auto remainingTokens = tokens;
  7823. if( remainingTokens && remainingTokens->type == TokenType::Option ) {
  7824. auto const &token = *remainingTokens;
  7825. if( isMatch(token.token ) ) {
  7826. if( m_ref->isFlag() ) {
  7827. auto flagRef = static_cast<detail::BoundFlagRefBase*>( m_ref.get() );
  7828. auto result = flagRef->setFlag( true );
  7829. if( !result )
  7830. return InternalParseResult( result );
  7831. if( result.value() == ParseResultType::ShortCircuitAll )
  7832. return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
  7833. } else {
  7834. auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
  7835. ++remainingTokens;
  7836. if( !remainingTokens )
  7837. return InternalParseResult::runtimeError( "Expected argument following " + token.token );
  7838. auto const &argToken = *remainingTokens;
  7839. if( argToken.type != TokenType::Argument )
  7840. return InternalParseResult::runtimeError( "Expected argument following " + token.token );
  7841. auto result = valueRef->setValue( argToken.token );
  7842. if( !result )
  7843. return InternalParseResult( result );
  7844. if( result.value() == ParseResultType::ShortCircuitAll )
  7845. return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
  7846. }
  7847. return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
  7848. }
  7849. }
  7850. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
  7851. }
  7852. auto validate() const -> Result override {
  7853. if( m_optNames.empty() )
  7854. return Result::logicError( "No options supplied to Opt" );
  7855. for( auto const &name : m_optNames ) {
  7856. if( name.empty() )
  7857. return Result::logicError( "Option name cannot be empty" );
  7858. #ifdef CATCH_PLATFORM_WINDOWS
  7859. if( name[0] != '-' && name[0] != '/' )
  7860. return Result::logicError( "Option name must begin with '-' or '/'" );
  7861. #else
  7862. if( name[0] != '-' )
  7863. return Result::logicError( "Option name must begin with '-'" );
  7864. #endif
  7865. }
  7866. return ParserRefImpl::validate();
  7867. }
  7868. };
  7869. struct Help : Opt {
  7870. Help( bool &showHelpFlag )
  7871. : Opt([&]( bool flag ) {
  7872. showHelpFlag = flag;
  7873. return ParserResult::ok( ParseResultType::ShortCircuitAll );
  7874. })
  7875. {
  7876. static_cast<Opt &>( *this )
  7877. ("display usage information")
  7878. ["-?"]["-h"]["--help"]
  7879. .optional();
  7880. }
  7881. };
  7882. struct Parser : ParserBase {
  7883. mutable ExeName m_exeName;
  7884. std::vector<Opt> m_options;
  7885. std::vector<Arg> m_args;
  7886. auto operator|=( ExeName const &exeName ) -> Parser & {
  7887. m_exeName = exeName;
  7888. return *this;
  7889. }
  7890. auto operator|=( Arg const &arg ) -> Parser & {
  7891. m_args.push_back(arg);
  7892. return *this;
  7893. }
  7894. auto operator|=( Opt const &opt ) -> Parser & {
  7895. m_options.push_back(opt);
  7896. return *this;
  7897. }
  7898. auto operator|=( Parser const &other ) -> Parser & {
  7899. m_options.insert(m_options.end(), other.m_options.begin(), other.m_options.end());
  7900. m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end());
  7901. return *this;
  7902. }
  7903. template<typename T>
  7904. auto operator|( T const &other ) const -> Parser {
  7905. return Parser( *this ) |= other;
  7906. }
  7907. // Forward deprecated interface with '+' instead of '|'
  7908. template<typename T>
  7909. auto operator+=( T const &other ) -> Parser & { return operator|=( other ); }
  7910. template<typename T>
  7911. auto operator+( T const &other ) const -> Parser { return operator|( other ); }
  7912. auto getHelpColumns() const -> std::vector<HelpColumns> {
  7913. std::vector<HelpColumns> cols;
  7914. for (auto const &o : m_options) {
  7915. auto childCols = o.getHelpColumns();
  7916. cols.insert( cols.end(), childCols.begin(), childCols.end() );
  7917. }
  7918. return cols;
  7919. }
  7920. void writeToStream( std::ostream &os ) const {
  7921. if (!m_exeName.name().empty()) {
  7922. os << "usage:\n" << " " << m_exeName.name() << " ";
  7923. bool required = true, first = true;
  7924. for( auto const &arg : m_args ) {
  7925. if (first)
  7926. first = false;
  7927. else
  7928. os << " ";
  7929. if( arg.isOptional() && required ) {
  7930. os << "[";
  7931. required = false;
  7932. }
  7933. os << "<" << arg.hint() << ">";
  7934. if( arg.cardinality() == 0 )
  7935. os << " ... ";
  7936. }
  7937. if( !required )
  7938. os << "]";
  7939. if( !m_options.empty() )
  7940. os << " options";
  7941. os << "\n\nwhere options are:" << std::endl;
  7942. }
  7943. auto rows = getHelpColumns();
  7944. size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH;
  7945. size_t optWidth = 0;
  7946. for( auto const &cols : rows )
  7947. optWidth = (std::max)(optWidth, cols.left.size() + 2);
  7948. optWidth = (std::min)(optWidth, consoleWidth/2);
  7949. for( auto const &cols : rows ) {
  7950. auto row =
  7951. TextFlow::Column( cols.left ).width( optWidth ).indent( 2 ) +
  7952. TextFlow::Spacer(4) +
  7953. TextFlow::Column( cols.right ).width( consoleWidth - 7 - optWidth );
  7954. os << row << std::endl;
  7955. }
  7956. }
  7957. friend auto operator<<( std::ostream &os, Parser const &parser ) -> std::ostream& {
  7958. parser.writeToStream( os );
  7959. return os;
  7960. }
  7961. auto validate() const -> Result override {
  7962. for( auto const &opt : m_options ) {
  7963. auto result = opt.validate();
  7964. if( !result )
  7965. return result;
  7966. }
  7967. for( auto const &arg : m_args ) {
  7968. auto result = arg.validate();
  7969. if( !result )
  7970. return result;
  7971. }
  7972. return Result::ok();
  7973. }
  7974. using ParserBase::parse;
  7975. auto parse( std::string const& exeName, TokenStream const &tokens ) const -> InternalParseResult override {
  7976. struct ParserInfo {
  7977. ParserBase const* parser = nullptr;
  7978. size_t count = 0;
  7979. };
  7980. const size_t totalParsers = m_options.size() + m_args.size();
  7981. assert( totalParsers < 512 );
  7982. // ParserInfo parseInfos[totalParsers]; // <-- this is what we really want to do
  7983. ParserInfo parseInfos[512];
  7984. {
  7985. size_t i = 0;
  7986. for (auto const &opt : m_options) parseInfos[i++].parser = &opt;
  7987. for (auto const &arg : m_args) parseInfos[i++].parser = &arg;
  7988. }
  7989. m_exeName.set( exeName );
  7990. auto result = InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
  7991. while( result.value().remainingTokens() ) {
  7992. bool tokenParsed = false;
  7993. for( size_t i = 0; i < totalParsers; ++i ) {
  7994. auto& parseInfo = parseInfos[i];
  7995. if( parseInfo.parser->cardinality() == 0 || parseInfo.count < parseInfo.parser->cardinality() ) {
  7996. result = parseInfo.parser->parse(exeName, result.value().remainingTokens());
  7997. if (!result)
  7998. return result;
  7999. if (result.value().type() != ParseResultType::NoMatch) {
  8000. tokenParsed = true;
  8001. ++parseInfo.count;
  8002. break;
  8003. }
  8004. }
  8005. }
  8006. if( result.value().type() == ParseResultType::ShortCircuitAll )
  8007. return result;
  8008. if( !tokenParsed )
  8009. return InternalParseResult::runtimeError( "Unrecognised token: " + result.value().remainingTokens()->token );
  8010. }
  8011. // !TBD Check missing required options
  8012. return result;
  8013. }
  8014. };
  8015. template<typename DerivedT>
  8016. template<typename T>
  8017. auto ComposableParserImpl<DerivedT>::operator|( T const &other ) const -> Parser {
  8018. return Parser() | static_cast<DerivedT const &>( *this ) | other;
  8019. }
  8020. } // namespace detail
  8021. // A Combined parser
  8022. using detail::Parser;
  8023. // A parser for options
  8024. using detail::Opt;
  8025. // A parser for arguments
  8026. using detail::Arg;
  8027. // Wrapper for argc, argv from main()
  8028. using detail::Args;
  8029. // Specifies the name of the executable
  8030. using detail::ExeName;
  8031. // Convenience wrapper for option parser that specifies the help option
  8032. using detail::Help;
  8033. // enum of result types from a parse
  8034. using detail::ParseResultType;
  8035. // Result type for parser operation
  8036. using detail::ParserResult;
  8037. }} // namespace Catch::clara
  8038. // end clara.hpp
  8039. #ifdef __clang__
  8040. #pragma clang diagnostic pop
  8041. #endif
  8042. // Restore Clara's value for console width, if present
  8043. #ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  8044. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  8045. #undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  8046. #endif
  8047. // end catch_clara.h
  8048. namespace Catch {
  8049. clara::Parser makeCommandLineParser( ConfigData& config );
  8050. } // end namespace Catch
  8051. // end catch_commandline.h
  8052. #include <fstream>
  8053. #include <ctime>
  8054. namespace Catch {
  8055. clara::Parser makeCommandLineParser( ConfigData& config ) {
  8056. using namespace clara;
  8057. auto const setWarning = [&]( std::string const& warning ) {
  8058. auto warningSet = [&]() {
  8059. if( warning == "NoAssertions" )
  8060. return WarnAbout::NoAssertions;
  8061. if ( warning == "NoTests" )
  8062. return WarnAbout::NoTests;
  8063. return WarnAbout::Nothing;
  8064. }();
  8065. if (warningSet == WarnAbout::Nothing)
  8066. return ParserResult::runtimeError( "Unrecognised warning: '" + warning + "'" );
  8067. config.warnings = static_cast<WarnAbout::What>( config.warnings | warningSet );
  8068. return ParserResult::ok( ParseResultType::Matched );
  8069. };
  8070. auto const loadTestNamesFromFile = [&]( std::string const& filename ) {
  8071. std::ifstream f( filename.c_str() );
  8072. if( !f.is_open() )
  8073. return ParserResult::runtimeError( "Unable to load input file: '" + filename + "'" );
  8074. std::string line;
  8075. while( std::getline( f, line ) ) {
  8076. line = trim(line);
  8077. if( !line.empty() && !startsWith( line, '#' ) ) {
  8078. if( !startsWith( line, '"' ) )
  8079. line = '"' + line + '"';
  8080. config.testsOrTags.push_back( line + ',' );
  8081. }
  8082. }
  8083. return ParserResult::ok( ParseResultType::Matched );
  8084. };
  8085. auto const setTestOrder = [&]( std::string const& order ) {
  8086. if( startsWith( "declared", order ) )
  8087. config.runOrder = RunTests::InDeclarationOrder;
  8088. else if( startsWith( "lexical", order ) )
  8089. config.runOrder = RunTests::InLexicographicalOrder;
  8090. else if( startsWith( "random", order ) )
  8091. config.runOrder = RunTests::InRandomOrder;
  8092. else
  8093. return clara::ParserResult::runtimeError( "Unrecognised ordering: '" + order + "'" );
  8094. return ParserResult::ok( ParseResultType::Matched );
  8095. };
  8096. auto const setRngSeed = [&]( std::string const& seed ) {
  8097. if( seed != "time" )
  8098. return clara::detail::convertInto( seed, config.rngSeed );
  8099. config.rngSeed = static_cast<unsigned int>( std::time(nullptr) );
  8100. return ParserResult::ok( ParseResultType::Matched );
  8101. };
  8102. auto const setColourUsage = [&]( std::string const& useColour ) {
  8103. auto mode = toLower( useColour );
  8104. if( mode == "yes" )
  8105. config.useColour = UseColour::Yes;
  8106. else if( mode == "no" )
  8107. config.useColour = UseColour::No;
  8108. else if( mode == "auto" )
  8109. config.useColour = UseColour::Auto;
  8110. else
  8111. return ParserResult::runtimeError( "colour mode must be one of: auto, yes or no. '" + useColour + "' not recognised" );
  8112. return ParserResult::ok( ParseResultType::Matched );
  8113. };
  8114. auto const setWaitForKeypress = [&]( std::string const& keypress ) {
  8115. auto keypressLc = toLower( keypress );
  8116. if( keypressLc == "start" )
  8117. config.waitForKeypress = WaitForKeypress::BeforeStart;
  8118. else if( keypressLc == "exit" )
  8119. config.waitForKeypress = WaitForKeypress::BeforeExit;
  8120. else if( keypressLc == "both" )
  8121. config.waitForKeypress = WaitForKeypress::BeforeStartAndExit;
  8122. else
  8123. return ParserResult::runtimeError( "keypress argument must be one of: start, exit or both. '" + keypress + "' not recognised" );
  8124. return ParserResult::ok( ParseResultType::Matched );
  8125. };
  8126. auto const setVerbosity = [&]( std::string const& verbosity ) {
  8127. auto lcVerbosity = toLower( verbosity );
  8128. if( lcVerbosity == "quiet" )
  8129. config.verbosity = Verbosity::Quiet;
  8130. else if( lcVerbosity == "normal" )
  8131. config.verbosity = Verbosity::Normal;
  8132. else if( lcVerbosity == "high" )
  8133. config.verbosity = Verbosity::High;
  8134. else
  8135. return ParserResult::runtimeError( "Unrecognised verbosity, '" + verbosity + "'" );
  8136. return ParserResult::ok( ParseResultType::Matched );
  8137. };
  8138. auto const setReporter = [&]( std::string const& reporter ) {
  8139. IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
  8140. auto lcReporter = toLower( reporter );
  8141. auto result = factories.find( lcReporter );
  8142. if( factories.end() != result )
  8143. config.reporterName = lcReporter;
  8144. else
  8145. return ParserResult::runtimeError( "Unrecognized reporter, '" + reporter + "'. Check available with --list-reporters" );
  8146. return ParserResult::ok( ParseResultType::Matched );
  8147. };
  8148. auto cli
  8149. = ExeName( config.processName )
  8150. | Help( config.showHelp )
  8151. | Opt( config.listTests )
  8152. ["-l"]["--list-tests"]
  8153. ( "list all/matching test cases" )
  8154. | Opt( config.listTags )
  8155. ["-t"]["--list-tags"]
  8156. ( "list all/matching tags" )
  8157. | Opt( config.showSuccessfulTests )
  8158. ["-s"]["--success"]
  8159. ( "include successful tests in output" )
  8160. | Opt( config.shouldDebugBreak )
  8161. ["-b"]["--break"]
  8162. ( "break into debugger on failure" )
  8163. | Opt( config.noThrow )
  8164. ["-e"]["--nothrow"]
  8165. ( "skip exception tests" )
  8166. | Opt( config.showInvisibles )
  8167. ["-i"]["--invisibles"]
  8168. ( "show invisibles (tabs, newlines)" )
  8169. | Opt( config.outputFilename, "filename" )
  8170. ["-o"]["--out"]
  8171. ( "output filename" )
  8172. | Opt( setReporter, "name" )
  8173. ["-r"]["--reporter"]
  8174. ( "reporter to use (defaults to console)" )
  8175. | Opt( config.name, "name" )
  8176. ["-n"]["--name"]
  8177. ( "suite name" )
  8178. | Opt( [&]( bool ){ config.abortAfter = 1; } )
  8179. ["-a"]["--abort"]
  8180. ( "abort at first failure" )
  8181. | Opt( [&]( int x ){ config.abortAfter = x; }, "no. failures" )
  8182. ["-x"]["--abortx"]
  8183. ( "abort after x failures" )
  8184. | Opt( setWarning, "warning name" )
  8185. ["-w"]["--warn"]
  8186. ( "enable warnings" )
  8187. | Opt( [&]( bool flag ) { config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never; }, "yes|no" )
  8188. ["-d"]["--durations"]
  8189. ( "show test durations" )
  8190. | Opt( loadTestNamesFromFile, "filename" )
  8191. ["-f"]["--input-file"]
  8192. ( "load test names to run from a file" )
  8193. | Opt( config.filenamesAsTags )
  8194. ["-#"]["--filenames-as-tags"]
  8195. ( "adds a tag for the filename" )
  8196. | Opt( config.sectionsToRun, "section name" )
  8197. ["-c"]["--section"]
  8198. ( "specify section to run" )
  8199. | Opt( setVerbosity, "quiet|normal|high" )
  8200. ["-v"]["--verbosity"]
  8201. ( "set output verbosity" )
  8202. | Opt( config.listTestNamesOnly )
  8203. ["--list-test-names-only"]
  8204. ( "list all/matching test cases names only" )
  8205. | Opt( config.listReporters )
  8206. ["--list-reporters"]
  8207. ( "list all reporters" )
  8208. | Opt( setTestOrder, "decl|lex|rand" )
  8209. ["--order"]
  8210. ( "test case order (defaults to decl)" )
  8211. | Opt( setRngSeed, "'time'|number" )
  8212. ["--rng-seed"]
  8213. ( "set a specific seed for random numbers" )
  8214. | Opt( setColourUsage, "yes|no" )
  8215. ["--use-colour"]
  8216. ( "should output be colourised" )
  8217. | Opt( config.libIdentify )
  8218. ["--libidentify"]
  8219. ( "report name and version according to libidentify standard" )
  8220. | Opt( setWaitForKeypress, "start|exit|both" )
  8221. ["--wait-for-keypress"]
  8222. ( "waits for a keypress before exiting" )
  8223. | Opt( config.benchmarkSamples, "samples" )
  8224. ["--benchmark-samples"]
  8225. ( "number of samples to collect (default: 100)" )
  8226. | Opt( config.benchmarkResamples, "resamples" )
  8227. ["--benchmark-resamples"]
  8228. ( "number of resamples for the bootstrap (default: 100000)" )
  8229. | Opt( config.benchmarkConfidenceInterval, "confidence interval" )
  8230. ["--benchmark-confidence-interval"]
  8231. ( "confidence interval for the bootstrap (between 0 and 1, default: 0.95)" )
  8232. | Opt( config.benchmarkNoAnalysis )
  8233. ["--benchmark-no-analysis"]
  8234. ( "perform only measurements; do not perform any analysis" )
  8235. | Arg( config.testsOrTags, "test name|pattern|tags" )
  8236. ( "which test or tests to use" );
  8237. return cli;
  8238. }
  8239. } // end namespace Catch
  8240. // end catch_commandline.cpp
  8241. // start catch_common.cpp
  8242. #include <cstring>
  8243. #include <ostream>
  8244. namespace Catch {
  8245. bool SourceLineInfo::empty() const noexcept {
  8246. return file[0] == '\0';
  8247. }
  8248. bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const noexcept {
  8249. return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0);
  8250. }
  8251. bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const noexcept {
  8252. // We can assume that the same file will usually have the same pointer.
  8253. // Thus, if the pointers are the same, there is no point in calling the strcmp
  8254. return line < other.line || ( line == other.line && file != other.file && (std::strcmp(file, other.file) < 0));
  8255. }
  8256. std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) {
  8257. #ifndef __GNUG__
  8258. os << info.file << '(' << info.line << ')';
  8259. #else
  8260. os << info.file << ':' << info.line;
  8261. #endif
  8262. return os;
  8263. }
  8264. std::string StreamEndStop::operator+() const {
  8265. return std::string();
  8266. }
  8267. NonCopyable::NonCopyable() = default;
  8268. NonCopyable::~NonCopyable() = default;
  8269. }
  8270. // end catch_common.cpp
  8271. // start catch_config.cpp
  8272. namespace Catch {
  8273. Config::Config( ConfigData const& data )
  8274. : m_data( data ),
  8275. m_stream( openStream() )
  8276. {
  8277. TestSpecParser parser(ITagAliasRegistry::get());
  8278. if (!data.testsOrTags.empty()) {
  8279. m_hasTestFilters = true;
  8280. for( auto const& testOrTags : data.testsOrTags )
  8281. parser.parse( testOrTags );
  8282. }
  8283. m_testSpec = parser.testSpec();
  8284. }
  8285. std::string const& Config::getFilename() const {
  8286. return m_data.outputFilename ;
  8287. }
  8288. bool Config::listTests() const { return m_data.listTests; }
  8289. bool Config::listTestNamesOnly() const { return m_data.listTestNamesOnly; }
  8290. bool Config::listTags() const { return m_data.listTags; }
  8291. bool Config::listReporters() const { return m_data.listReporters; }
  8292. std::string Config::getProcessName() const { return m_data.processName; }
  8293. std::string const& Config::getReporterName() const { return m_data.reporterName; }
  8294. std::vector<std::string> const& Config::getTestsOrTags() const { return m_data.testsOrTags; }
  8295. std::vector<std::string> const& Config::getSectionsToRun() const { return m_data.sectionsToRun; }
  8296. TestSpec const& Config::testSpec() const { return m_testSpec; }
  8297. bool Config::hasTestFilters() const { return m_hasTestFilters; }
  8298. bool Config::showHelp() const { return m_data.showHelp; }
  8299. // IConfig interface
  8300. bool Config::allowThrows() const { return !m_data.noThrow; }
  8301. std::ostream& Config::stream() const { return m_stream->stream(); }
  8302. std::string Config::name() const { return m_data.name.empty() ? m_data.processName : m_data.name; }
  8303. bool Config::includeSuccessfulResults() const { return m_data.showSuccessfulTests; }
  8304. bool Config::warnAboutMissingAssertions() const { return !!(m_data.warnings & WarnAbout::NoAssertions); }
  8305. bool Config::warnAboutNoTests() const { return !!(m_data.warnings & WarnAbout::NoTests); }
  8306. ShowDurations::OrNot Config::showDurations() const { return m_data.showDurations; }
  8307. RunTests::InWhatOrder Config::runOrder() const { return m_data.runOrder; }
  8308. unsigned int Config::rngSeed() const { return m_data.rngSeed; }
  8309. UseColour::YesOrNo Config::useColour() const { return m_data.useColour; }
  8310. bool Config::shouldDebugBreak() const { return m_data.shouldDebugBreak; }
  8311. int Config::abortAfter() const { return m_data.abortAfter; }
  8312. bool Config::showInvisibles() const { return m_data.showInvisibles; }
  8313. Verbosity Config::verbosity() const { return m_data.verbosity; }
  8314. bool Config::benchmarkNoAnalysis() const { return m_data.benchmarkNoAnalysis; }
  8315. int Config::benchmarkSamples() const { return m_data.benchmarkSamples; }
  8316. double Config::benchmarkConfidenceInterval() const { return m_data.benchmarkConfidenceInterval; }
  8317. unsigned int Config::benchmarkResamples() const { return m_data.benchmarkResamples; }
  8318. IStream const* Config::openStream() {
  8319. return Catch::makeStream(m_data.outputFilename);
  8320. }
  8321. } // end namespace Catch
  8322. // end catch_config.cpp
  8323. // start catch_console_colour.cpp
  8324. #if defined(__clang__)
  8325. # pragma clang diagnostic push
  8326. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  8327. #endif
  8328. // start catch_errno_guard.h
  8329. namespace Catch {
  8330. class ErrnoGuard {
  8331. public:
  8332. ErrnoGuard();
  8333. ~ErrnoGuard();
  8334. private:
  8335. int m_oldErrno;
  8336. };
  8337. }
  8338. // end catch_errno_guard.h
  8339. #include <sstream>
  8340. namespace Catch {
  8341. namespace {
  8342. struct IColourImpl {
  8343. virtual ~IColourImpl() = default;
  8344. virtual void use( Colour::Code _colourCode ) = 0;
  8345. };
  8346. struct NoColourImpl : IColourImpl {
  8347. void use( Colour::Code ) {}
  8348. static IColourImpl* instance() {
  8349. static NoColourImpl s_instance;
  8350. return &s_instance;
  8351. }
  8352. };
  8353. } // anon namespace
  8354. } // namespace Catch
  8355. #if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI )
  8356. # ifdef CATCH_PLATFORM_WINDOWS
  8357. # define CATCH_CONFIG_COLOUR_WINDOWS
  8358. # else
  8359. # define CATCH_CONFIG_COLOUR_ANSI
  8360. # endif
  8361. #endif
  8362. #if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) /////////////////////////////////////////
  8363. namespace Catch {
  8364. namespace {
  8365. class Win32ColourImpl : public IColourImpl {
  8366. public:
  8367. Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) )
  8368. {
  8369. CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
  8370. GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo );
  8371. originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY );
  8372. originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY );
  8373. }
  8374. void use( Colour::Code _colourCode ) override {
  8375. switch( _colourCode ) {
  8376. case Colour::None: return setTextAttribute( originalForegroundAttributes );
  8377. case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  8378. case Colour::Red: return setTextAttribute( FOREGROUND_RED );
  8379. case Colour::Green: return setTextAttribute( FOREGROUND_GREEN );
  8380. case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE );
  8381. case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN );
  8382. case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN );
  8383. case Colour::Grey: return setTextAttribute( 0 );
  8384. case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY );
  8385. case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED );
  8386. case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN );
  8387. case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  8388. case Colour::BrightYellow: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN );
  8389. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  8390. default:
  8391. CATCH_ERROR( "Unknown colour requested" );
  8392. }
  8393. }
  8394. private:
  8395. void setTextAttribute( WORD _textAttribute ) {
  8396. SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes );
  8397. }
  8398. HANDLE stdoutHandle;
  8399. WORD originalForegroundAttributes;
  8400. WORD originalBackgroundAttributes;
  8401. };
  8402. IColourImpl* platformColourInstance() {
  8403. static Win32ColourImpl s_instance;
  8404. IConfigPtr config = getCurrentContext().getConfig();
  8405. UseColour::YesOrNo colourMode = config
  8406. ? config->useColour()
  8407. : UseColour::Auto;
  8408. if( colourMode == UseColour::Auto )
  8409. colourMode = UseColour::Yes;
  8410. return colourMode == UseColour::Yes
  8411. ? &s_instance
  8412. : NoColourImpl::instance();
  8413. }
  8414. } // end anon namespace
  8415. } // end namespace Catch
  8416. #elif defined( CATCH_CONFIG_COLOUR_ANSI ) //////////////////////////////////////
  8417. #include <unistd.h>
  8418. namespace Catch {
  8419. namespace {
  8420. // use POSIX/ ANSI console terminal codes
  8421. // Thanks to Adam Strzelecki for original contribution
  8422. // (http://github.com/nanoant)
  8423. // https://github.com/philsquared/Catch/pull/131
  8424. class PosixColourImpl : public IColourImpl {
  8425. public:
  8426. void use( Colour::Code _colourCode ) override {
  8427. switch( _colourCode ) {
  8428. case Colour::None:
  8429. case Colour::White: return setColour( "[0m" );
  8430. case Colour::Red: return setColour( "[0;31m" );
  8431. case Colour::Green: return setColour( "[0;32m" );
  8432. case Colour::Blue: return setColour( "[0;34m" );
  8433. case Colour::Cyan: return setColour( "[0;36m" );
  8434. case Colour::Yellow: return setColour( "[0;33m" );
  8435. case Colour::Grey: return setColour( "[1;30m" );
  8436. case Colour::LightGrey: return setColour( "[0;37m" );
  8437. case Colour::BrightRed: return setColour( "[1;31m" );
  8438. case Colour::BrightGreen: return setColour( "[1;32m" );
  8439. case Colour::BrightWhite: return setColour( "[1;37m" );
  8440. case Colour::BrightYellow: return setColour( "[1;33m" );
  8441. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  8442. default: CATCH_INTERNAL_ERROR( "Unknown colour requested" );
  8443. }
  8444. }
  8445. static IColourImpl* instance() {
  8446. static PosixColourImpl s_instance;
  8447. return &s_instance;
  8448. }
  8449. private:
  8450. void setColour( const char* _escapeCode ) {
  8451. getCurrentContext().getConfig()->stream()
  8452. << '\033' << _escapeCode;
  8453. }
  8454. };
  8455. bool useColourOnPlatform() {
  8456. return
  8457. #ifdef CATCH_PLATFORM_MAC
  8458. !isDebuggerActive() &&
  8459. #endif
  8460. #if !(defined(__DJGPP__) && defined(__STRICT_ANSI__))
  8461. isatty(STDOUT_FILENO)
  8462. #else
  8463. false
  8464. #endif
  8465. ;
  8466. }
  8467. IColourImpl* platformColourInstance() {
  8468. ErrnoGuard guard;
  8469. IConfigPtr config = getCurrentContext().getConfig();
  8470. UseColour::YesOrNo colourMode = config
  8471. ? config->useColour()
  8472. : UseColour::Auto;
  8473. if( colourMode == UseColour::Auto )
  8474. colourMode = useColourOnPlatform()
  8475. ? UseColour::Yes
  8476. : UseColour::No;
  8477. return colourMode == UseColour::Yes
  8478. ? PosixColourImpl::instance()
  8479. : NoColourImpl::instance();
  8480. }
  8481. } // end anon namespace
  8482. } // end namespace Catch
  8483. #else // not Windows or ANSI ///////////////////////////////////////////////
  8484. namespace Catch {
  8485. static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); }
  8486. } // end namespace Catch
  8487. #endif // Windows/ ANSI/ None
  8488. namespace Catch {
  8489. Colour::Colour( Code _colourCode ) { use( _colourCode ); }
  8490. Colour::Colour( Colour&& rhs ) noexcept {
  8491. m_moved = rhs.m_moved;
  8492. rhs.m_moved = true;
  8493. }
  8494. Colour& Colour::operator=( Colour&& rhs ) noexcept {
  8495. m_moved = rhs.m_moved;
  8496. rhs.m_moved = true;
  8497. return *this;
  8498. }
  8499. Colour::~Colour(){ if( !m_moved ) use( None ); }
  8500. void Colour::use( Code _colourCode ) {
  8501. static IColourImpl* impl = platformColourInstance();
  8502. // Strictly speaking, this cannot possibly happen.
  8503. // However, under some conditions it does happen (see #1626),
  8504. // and this change is small enough that we can let practicality
  8505. // triumph over purity in this case.
  8506. if (impl != NULL) {
  8507. impl->use( _colourCode );
  8508. }
  8509. }
  8510. std::ostream& operator << ( std::ostream& os, Colour const& ) {
  8511. return os;
  8512. }
  8513. } // end namespace Catch
  8514. #if defined(__clang__)
  8515. # pragma clang diagnostic pop
  8516. #endif
  8517. // end catch_console_colour.cpp
  8518. // start catch_context.cpp
  8519. namespace Catch {
  8520. class Context : public IMutableContext, NonCopyable {
  8521. public: // IContext
  8522. IResultCapture* getResultCapture() override {
  8523. return m_resultCapture;
  8524. }
  8525. IRunner* getRunner() override {
  8526. return m_runner;
  8527. }
  8528. IConfigPtr const& getConfig() const override {
  8529. return m_config;
  8530. }
  8531. ~Context() override;
  8532. public: // IMutableContext
  8533. void setResultCapture( IResultCapture* resultCapture ) override {
  8534. m_resultCapture = resultCapture;
  8535. }
  8536. void setRunner( IRunner* runner ) override {
  8537. m_runner = runner;
  8538. }
  8539. void setConfig( IConfigPtr const& config ) override {
  8540. m_config = config;
  8541. }
  8542. friend IMutableContext& getCurrentMutableContext();
  8543. private:
  8544. IConfigPtr m_config;
  8545. IRunner* m_runner = nullptr;
  8546. IResultCapture* m_resultCapture = nullptr;
  8547. };
  8548. IMutableContext *IMutableContext::currentContext = nullptr;
  8549. void IMutableContext::createContext()
  8550. {
  8551. currentContext = new Context();
  8552. }
  8553. void cleanUpContext() {
  8554. delete IMutableContext::currentContext;
  8555. IMutableContext::currentContext = nullptr;
  8556. }
  8557. IContext::~IContext() = default;
  8558. IMutableContext::~IMutableContext() = default;
  8559. Context::~Context() = default;
  8560. }
  8561. // end catch_context.cpp
  8562. // start catch_debug_console.cpp
  8563. // start catch_debug_console.h
  8564. #include <string>
  8565. namespace Catch {
  8566. void writeToDebugConsole( std::string const& text );
  8567. }
  8568. // end catch_debug_console.h
  8569. #if defined(__ANDROID__)
  8570. #include <android/log.h>
  8571. namespace Catch {
  8572. void writeToDebugConsole( std::string const& text ) {
  8573. __android_log_print( ANDROID_LOG_DEBUG, "Catch", text.c_str() );
  8574. }
  8575. }
  8576. #elif defined(CATCH_PLATFORM_WINDOWS)
  8577. namespace Catch {
  8578. void writeToDebugConsole( std::string const& text ) {
  8579. ::OutputDebugStringA( text.c_str() );
  8580. }
  8581. }
  8582. #else
  8583. namespace Catch {
  8584. void writeToDebugConsole( std::string const& text ) {
  8585. // !TBD: Need a version for Mac/ XCode and other IDEs
  8586. Catch::cout() << text;
  8587. }
  8588. }
  8589. #endif // Platform
  8590. // end catch_debug_console.cpp
  8591. // start catch_debugger.cpp
  8592. #ifdef CATCH_PLATFORM_MAC
  8593. # include <assert.h>
  8594. # include <stdbool.h>
  8595. # include <sys/types.h>
  8596. # include <unistd.h>
  8597. # include <cstddef>
  8598. # include <ostream>
  8599. #ifdef __apple_build_version__
  8600. // These headers will only compile with AppleClang (XCode)
  8601. // For other compilers (Clang, GCC, ... ) we need to exclude them
  8602. # include <sys/sysctl.h>
  8603. #endif
  8604. namespace Catch {
  8605. #ifdef __apple_build_version__
  8606. // The following function is taken directly from the following technical note:
  8607. // https://developer.apple.com/library/archive/qa/qa1361/_index.html
  8608. // Returns true if the current process is being debugged (either
  8609. // running under the debugger or has a debugger attached post facto).
  8610. bool isDebuggerActive(){
  8611. int mib[4];
  8612. struct kinfo_proc info;
  8613. std::size_t size;
  8614. // Initialize the flags so that, if sysctl fails for some bizarre
  8615. // reason, we get a predictable result.
  8616. info.kp_proc.p_flag = 0;
  8617. // Initialize mib, which tells sysctl the info we want, in this case
  8618. // we're looking for information about a specific process ID.
  8619. mib[0] = CTL_KERN;
  8620. mib[1] = KERN_PROC;
  8621. mib[2] = KERN_PROC_PID;
  8622. mib[3] = getpid();
  8623. // Call sysctl.
  8624. size = sizeof(info);
  8625. if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0) != 0 ) {
  8626. Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl;
  8627. return false;
  8628. }
  8629. // We're being debugged if the P_TRACED flag is set.
  8630. return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
  8631. }
  8632. #else
  8633. bool isDebuggerActive() {
  8634. // We need to find another way to determine this for non-appleclang compilers on macOS
  8635. return false;
  8636. }
  8637. #endif
  8638. } // namespace Catch
  8639. #elif defined(CATCH_PLATFORM_LINUX)
  8640. #include <fstream>
  8641. #include <string>
  8642. namespace Catch{
  8643. // The standard POSIX way of detecting a debugger is to attempt to
  8644. // ptrace() the process, but this needs to be done from a child and not
  8645. // this process itself to still allow attaching to this process later
  8646. // if wanted, so is rather heavy. Under Linux we have the PID of the
  8647. // "debugger" (which doesn't need to be gdb, of course, it could also
  8648. // be strace, for example) in /proc/$PID/status, so just get it from
  8649. // there instead.
  8650. bool isDebuggerActive(){
  8651. // Libstdc++ has a bug, where std::ifstream sets errno to 0
  8652. // This way our users can properly assert over errno values
  8653. ErrnoGuard guard;
  8654. std::ifstream in("/proc/self/status");
  8655. for( std::string line; std::getline(in, line); ) {
  8656. static const int PREFIX_LEN = 11;
  8657. if( line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0 ) {
  8658. // We're traced if the PID is not 0 and no other PID starts
  8659. // with 0 digit, so it's enough to check for just a single
  8660. // character.
  8661. return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0';
  8662. }
  8663. }
  8664. return false;
  8665. }
  8666. } // namespace Catch
  8667. #elif defined(_MSC_VER)
  8668. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  8669. namespace Catch {
  8670. bool isDebuggerActive() {
  8671. return IsDebuggerPresent() != 0;
  8672. }
  8673. }
  8674. #elif defined(__MINGW32__)
  8675. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  8676. namespace Catch {
  8677. bool isDebuggerActive() {
  8678. return IsDebuggerPresent() != 0;
  8679. }
  8680. }
  8681. #else
  8682. namespace Catch {
  8683. bool isDebuggerActive() { return false; }
  8684. }
  8685. #endif // Platform
  8686. // end catch_debugger.cpp
  8687. // start catch_decomposer.cpp
  8688. namespace Catch {
  8689. ITransientExpression::~ITransientExpression() = default;
  8690. void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs ) {
  8691. if( lhs.size() + rhs.size() < 40 &&
  8692. lhs.find('\n') == std::string::npos &&
  8693. rhs.find('\n') == std::string::npos )
  8694. os << lhs << " " << op << " " << rhs;
  8695. else
  8696. os << lhs << "\n" << op << "\n" << rhs;
  8697. }
  8698. }
  8699. // end catch_decomposer.cpp
  8700. // start catch_enforce.cpp
  8701. #include <stdexcept>
  8702. namespace Catch {
  8703. #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS_CUSTOM_HANDLER)
  8704. [[noreturn]]
  8705. void throw_exception(std::exception const& e) {
  8706. Catch::cerr() << "Catch will terminate because it needed to throw an exception.\n"
  8707. << "The message was: " << e.what() << '\n';
  8708. std::terminate();
  8709. }
  8710. #endif
  8711. [[noreturn]]
  8712. void throw_logic_error(std::string const& msg) {
  8713. throw_exception(std::logic_error(msg));
  8714. }
  8715. [[noreturn]]
  8716. void throw_domain_error(std::string const& msg) {
  8717. throw_exception(std::domain_error(msg));
  8718. }
  8719. [[noreturn]]
  8720. void throw_runtime_error(std::string const& msg) {
  8721. throw_exception(std::runtime_error(msg));
  8722. }
  8723. } // namespace Catch;
  8724. // end catch_enforce.cpp
  8725. // start catch_enum_values_registry.cpp
  8726. // start catch_enum_values_registry.h
  8727. #include <vector>
  8728. #include <memory>
  8729. namespace Catch {
  8730. namespace Detail {
  8731. std::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int> const& values );
  8732. class EnumValuesRegistry : public IMutableEnumValuesRegistry {
  8733. std::vector<std::unique_ptr<EnumInfo>> m_enumInfos;
  8734. EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::vector<int> const& values) override;
  8735. };
  8736. std::vector<std::string> parseEnums( StringRef enums );
  8737. } // Detail
  8738. } // Catch
  8739. // end catch_enum_values_registry.h
  8740. #include <map>
  8741. #include <cassert>
  8742. namespace Catch {
  8743. IMutableEnumValuesRegistry::~IMutableEnumValuesRegistry() {}
  8744. namespace Detail {
  8745. std::vector<std::string> parseEnums( StringRef enums ) {
  8746. auto enumValues = splitStringRef( enums, ',' );
  8747. std::vector<std::string> parsed;
  8748. parsed.reserve( enumValues.size() );
  8749. for( auto const& enumValue : enumValues ) {
  8750. auto identifiers = splitStringRef( enumValue, ':' );
  8751. parsed.push_back( Catch::trim( identifiers.back() ) );
  8752. }
  8753. return parsed;
  8754. }
  8755. EnumInfo::~EnumInfo() {}
  8756. StringRef EnumInfo::lookup( int value ) const {
  8757. for( auto const& valueToName : m_values ) {
  8758. if( valueToName.first == value )
  8759. return valueToName.second;
  8760. }
  8761. return "{** unexpected enum value **}";
  8762. }
  8763. std::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ) {
  8764. std::unique_ptr<EnumInfo> enumInfo( new EnumInfo );
  8765. enumInfo->m_name = enumName;
  8766. enumInfo->m_values.reserve( values.size() );
  8767. const auto valueNames = Catch::Detail::parseEnums( allValueNames );
  8768. assert( valueNames.size() == values.size() );
  8769. std::size_t i = 0;
  8770. for( auto value : values )
  8771. enumInfo->m_values.push_back({ value, valueNames[i++] });
  8772. return enumInfo;
  8773. }
  8774. EnumInfo const& EnumValuesRegistry::registerEnum( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ) {
  8775. auto enumInfo = makeEnumInfo( enumName, allValueNames, values );
  8776. EnumInfo* raw = enumInfo.get();
  8777. m_enumInfos.push_back( std::move( enumInfo ) );
  8778. return *raw;
  8779. }
  8780. } // Detail
  8781. } // Catch
  8782. // end catch_enum_values_registry.cpp
  8783. // start catch_errno_guard.cpp
  8784. #include <cerrno>
  8785. namespace Catch {
  8786. ErrnoGuard::ErrnoGuard():m_oldErrno(errno){}
  8787. ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; }
  8788. }
  8789. // end catch_errno_guard.cpp
  8790. // start catch_exception_translator_registry.cpp
  8791. // start catch_exception_translator_registry.h
  8792. #include <vector>
  8793. #include <string>
  8794. #include <memory>
  8795. namespace Catch {
  8796. class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry {
  8797. public:
  8798. ~ExceptionTranslatorRegistry();
  8799. virtual void registerTranslator( const IExceptionTranslator* translator );
  8800. std::string translateActiveException() const override;
  8801. std::string tryTranslators() const;
  8802. private:
  8803. std::vector<std::unique_ptr<IExceptionTranslator const>> m_translators;
  8804. };
  8805. }
  8806. // end catch_exception_translator_registry.h
  8807. #ifdef __OBJC__
  8808. #import "Foundation/Foundation.h"
  8809. #endif
  8810. namespace Catch {
  8811. ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {
  8812. }
  8813. void ExceptionTranslatorRegistry::registerTranslator( const IExceptionTranslator* translator ) {
  8814. m_translators.push_back( std::unique_ptr<const IExceptionTranslator>( translator ) );
  8815. }
  8816. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  8817. std::string ExceptionTranslatorRegistry::translateActiveException() const {
  8818. try {
  8819. #ifdef __OBJC__
  8820. // In Objective-C try objective-c exceptions first
  8821. @try {
  8822. return tryTranslators();
  8823. }
  8824. @catch (NSException *exception) {
  8825. return Catch::Detail::stringify( [exception description] );
  8826. }
  8827. #else
  8828. // Compiling a mixed mode project with MSVC means that CLR
  8829. // exceptions will be caught in (...) as well. However, these
  8830. // do not fill-in std::current_exception and thus lead to crash
  8831. // when attempting rethrow.
  8832. // /EHa switch also causes structured exceptions to be caught
  8833. // here, but they fill-in current_exception properly, so
  8834. // at worst the output should be a little weird, instead of
  8835. // causing a crash.
  8836. if (std::current_exception() == nullptr) {
  8837. return "Non C++ exception. Possibly a CLR exception.";
  8838. }
  8839. return tryTranslators();
  8840. #endif
  8841. }
  8842. catch( TestFailureException& ) {
  8843. std::rethrow_exception(std::current_exception());
  8844. }
  8845. catch( std::exception& ex ) {
  8846. return ex.what();
  8847. }
  8848. catch( std::string& msg ) {
  8849. return msg;
  8850. }
  8851. catch( const char* msg ) {
  8852. return msg;
  8853. }
  8854. catch(...) {
  8855. return "Unknown exception";
  8856. }
  8857. }
  8858. std::string ExceptionTranslatorRegistry::tryTranslators() const {
  8859. if (m_translators.empty()) {
  8860. std::rethrow_exception(std::current_exception());
  8861. } else {
  8862. return m_translators[0]->translate(m_translators.begin() + 1, m_translators.end());
  8863. }
  8864. }
  8865. #else // ^^ Exceptions are enabled // Exceptions are disabled vv
  8866. std::string ExceptionTranslatorRegistry::translateActiveException() const {
  8867. CATCH_INTERNAL_ERROR("Attempted to translate active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
  8868. }
  8869. std::string ExceptionTranslatorRegistry::tryTranslators() const {
  8870. CATCH_INTERNAL_ERROR("Attempted to use exception translators under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
  8871. }
  8872. #endif
  8873. }
  8874. // end catch_exception_translator_registry.cpp
  8875. // start catch_fatal_condition.cpp
  8876. #if defined(__GNUC__)
  8877. # pragma GCC diagnostic push
  8878. # pragma GCC diagnostic ignored "-Wmissing-field-initializers"
  8879. #endif
  8880. #if defined( CATCH_CONFIG_WINDOWS_SEH ) || defined( CATCH_CONFIG_POSIX_SIGNALS )
  8881. namespace {
  8882. // Report the error condition
  8883. void reportFatal( char const * const message ) {
  8884. Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition( message );
  8885. }
  8886. }
  8887. #endif // signals/SEH handling
  8888. #if defined( CATCH_CONFIG_WINDOWS_SEH )
  8889. namespace Catch {
  8890. struct SignalDefs { DWORD id; const char* name; };
  8891. // There is no 1-1 mapping between signals and windows exceptions.
  8892. // Windows can easily distinguish between SO and SigSegV,
  8893. // but SigInt, SigTerm, etc are handled differently.
  8894. static SignalDefs signalDefs[] = {
  8895. { static_cast<DWORD>(EXCEPTION_ILLEGAL_INSTRUCTION), "SIGILL - Illegal instruction signal" },
  8896. { static_cast<DWORD>(EXCEPTION_STACK_OVERFLOW), "SIGSEGV - Stack overflow" },
  8897. { static_cast<DWORD>(EXCEPTION_ACCESS_VIOLATION), "SIGSEGV - Segmentation violation signal" },
  8898. { static_cast<DWORD>(EXCEPTION_INT_DIVIDE_BY_ZERO), "Divide by zero error" },
  8899. };
  8900. LONG CALLBACK FatalConditionHandler::handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {
  8901. for (auto const& def : signalDefs) {
  8902. if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) {
  8903. reportFatal(def.name);
  8904. }
  8905. }
  8906. // If its not an exception we care about, pass it along.
  8907. // This stops us from eating debugger breaks etc.
  8908. return EXCEPTION_CONTINUE_SEARCH;
  8909. }
  8910. FatalConditionHandler::FatalConditionHandler() {
  8911. isSet = true;
  8912. // 32k seems enough for Catch to handle stack overflow,
  8913. // but the value was found experimentally, so there is no strong guarantee
  8914. guaranteeSize = 32 * 1024;
  8915. exceptionHandlerHandle = nullptr;
  8916. // Register as first handler in current chain
  8917. exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);
  8918. // Pass in guarantee size to be filled
  8919. SetThreadStackGuarantee(&guaranteeSize);
  8920. }
  8921. void FatalConditionHandler::reset() {
  8922. if (isSet) {
  8923. RemoveVectoredExceptionHandler(exceptionHandlerHandle);
  8924. SetThreadStackGuarantee(&guaranteeSize);
  8925. exceptionHandlerHandle = nullptr;
  8926. isSet = false;
  8927. }
  8928. }
  8929. FatalConditionHandler::~FatalConditionHandler() {
  8930. reset();
  8931. }
  8932. bool FatalConditionHandler::isSet = false;
  8933. ULONG FatalConditionHandler::guaranteeSize = 0;
  8934. PVOID FatalConditionHandler::exceptionHandlerHandle = nullptr;
  8935. } // namespace Catch
  8936. #elif defined( CATCH_CONFIG_POSIX_SIGNALS )
  8937. namespace Catch {
  8938. struct SignalDefs {
  8939. int id;
  8940. const char* name;
  8941. };
  8942. // 32kb for the alternate stack seems to be sufficient. However, this value
  8943. // is experimentally determined, so that's not guaranteed.
  8944. static constexpr std::size_t sigStackSize = 32768 >= MINSIGSTKSZ ? 32768 : MINSIGSTKSZ;
  8945. static SignalDefs signalDefs[] = {
  8946. { SIGINT, "SIGINT - Terminal interrupt signal" },
  8947. { SIGILL, "SIGILL - Illegal instruction signal" },
  8948. { SIGFPE, "SIGFPE - Floating point error signal" },
  8949. { SIGSEGV, "SIGSEGV - Segmentation violation signal" },
  8950. { SIGTERM, "SIGTERM - Termination request signal" },
  8951. { SIGABRT, "SIGABRT - Abort (abnormal termination) signal" }
  8952. };
  8953. void FatalConditionHandler::handleSignal( int sig ) {
  8954. char const * name = "<unknown signal>";
  8955. for (auto const& def : signalDefs) {
  8956. if (sig == def.id) {
  8957. name = def.name;
  8958. break;
  8959. }
  8960. }
  8961. reset();
  8962. reportFatal(name);
  8963. raise( sig );
  8964. }
  8965. FatalConditionHandler::FatalConditionHandler() {
  8966. isSet = true;
  8967. stack_t sigStack;
  8968. sigStack.ss_sp = altStackMem;
  8969. sigStack.ss_size = sigStackSize;
  8970. sigStack.ss_flags = 0;
  8971. sigaltstack(&sigStack, &oldSigStack);
  8972. struct sigaction sa = { };
  8973. sa.sa_handler = handleSignal;
  8974. sa.sa_flags = SA_ONSTACK;
  8975. for (std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i) {
  8976. sigaction(signalDefs[i].id, &sa, &oldSigActions[i]);
  8977. }
  8978. }
  8979. FatalConditionHandler::~FatalConditionHandler() {
  8980. reset();
  8981. }
  8982. void FatalConditionHandler::reset() {
  8983. if( isSet ) {
  8984. // Set signals back to previous values -- hopefully nobody overwrote them in the meantime
  8985. for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) {
  8986. sigaction(signalDefs[i].id, &oldSigActions[i], nullptr);
  8987. }
  8988. // Return the old stack
  8989. sigaltstack(&oldSigStack, nullptr);
  8990. isSet = false;
  8991. }
  8992. }
  8993. bool FatalConditionHandler::isSet = false;
  8994. struct sigaction FatalConditionHandler::oldSigActions[sizeof(signalDefs)/sizeof(SignalDefs)] = {};
  8995. stack_t FatalConditionHandler::oldSigStack = {};
  8996. char FatalConditionHandler::altStackMem[sigStackSize] = {};
  8997. } // namespace Catch
  8998. #else
  8999. namespace Catch {
  9000. void FatalConditionHandler::reset() {}
  9001. }
  9002. #endif // signals/SEH handling
  9003. #if defined(__GNUC__)
  9004. # pragma GCC diagnostic pop
  9005. #endif
  9006. // end catch_fatal_condition.cpp
  9007. // start catch_generators.cpp
  9008. // start catch_random_number_generator.h
  9009. #include <algorithm>
  9010. #include <random>
  9011. namespace Catch {
  9012. struct IConfig;
  9013. std::mt19937& rng();
  9014. void seedRng( IConfig const& config );
  9015. unsigned int rngSeed();
  9016. }
  9017. // end catch_random_number_generator.h
  9018. #include <limits>
  9019. #include <set>
  9020. namespace Catch {
  9021. IGeneratorTracker::~IGeneratorTracker() {}
  9022. const char* GeneratorException::what() const noexcept {
  9023. return m_msg;
  9024. }
  9025. namespace Generators {
  9026. GeneratorUntypedBase::~GeneratorUntypedBase() {}
  9027. auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
  9028. return getResultCapture().acquireGeneratorTracker( lineInfo );
  9029. }
  9030. } // namespace Generators
  9031. } // namespace Catch
  9032. // end catch_generators.cpp
  9033. // start catch_interfaces_capture.cpp
  9034. namespace Catch {
  9035. IResultCapture::~IResultCapture() = default;
  9036. }
  9037. // end catch_interfaces_capture.cpp
  9038. // start catch_interfaces_config.cpp
  9039. namespace Catch {
  9040. IConfig::~IConfig() = default;
  9041. }
  9042. // end catch_interfaces_config.cpp
  9043. // start catch_interfaces_exception.cpp
  9044. namespace Catch {
  9045. IExceptionTranslator::~IExceptionTranslator() = default;
  9046. IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() = default;
  9047. }
  9048. // end catch_interfaces_exception.cpp
  9049. // start catch_interfaces_registry_hub.cpp
  9050. namespace Catch {
  9051. IRegistryHub::~IRegistryHub() = default;
  9052. IMutableRegistryHub::~IMutableRegistryHub() = default;
  9053. }
  9054. // end catch_interfaces_registry_hub.cpp
  9055. // start catch_interfaces_reporter.cpp
  9056. // start catch_reporter_listening.h
  9057. namespace Catch {
  9058. class ListeningReporter : public IStreamingReporter {
  9059. using Reporters = std::vector<IStreamingReporterPtr>;
  9060. Reporters m_listeners;
  9061. IStreamingReporterPtr m_reporter = nullptr;
  9062. ReporterPreferences m_preferences;
  9063. public:
  9064. ListeningReporter();
  9065. void addListener( IStreamingReporterPtr&& listener );
  9066. void addReporter( IStreamingReporterPtr&& reporter );
  9067. public: // IStreamingReporter
  9068. ReporterPreferences getPreferences() const override;
  9069. void noMatchingTestCases( std::string const& spec ) override;
  9070. static std::set<Verbosity> getSupportedVerbosities();
  9071. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  9072. void benchmarkPreparing(std::string const& name) override;
  9073. void benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) override;
  9074. void benchmarkEnded( BenchmarkStats<> const& benchmarkStats ) override;
  9075. void benchmarkFailed(std::string const&) override;
  9076. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  9077. void testRunStarting( TestRunInfo const& testRunInfo ) override;
  9078. void testGroupStarting( GroupInfo const& groupInfo ) override;
  9079. void testCaseStarting( TestCaseInfo const& testInfo ) override;
  9080. void sectionStarting( SectionInfo const& sectionInfo ) override;
  9081. void assertionStarting( AssertionInfo const& assertionInfo ) override;
  9082. // The return value indicates if the messages buffer should be cleared:
  9083. bool assertionEnded( AssertionStats const& assertionStats ) override;
  9084. void sectionEnded( SectionStats const& sectionStats ) override;
  9085. void testCaseEnded( TestCaseStats const& testCaseStats ) override;
  9086. void testGroupEnded( TestGroupStats const& testGroupStats ) override;
  9087. void testRunEnded( TestRunStats const& testRunStats ) override;
  9088. void skipTest( TestCaseInfo const& testInfo ) override;
  9089. bool isMulti() const override;
  9090. };
  9091. } // end namespace Catch
  9092. // end catch_reporter_listening.h
  9093. namespace Catch {
  9094. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig )
  9095. : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {}
  9096. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream )
  9097. : m_stream( &_stream ), m_fullConfig( _fullConfig ) {}
  9098. std::ostream& ReporterConfig::stream() const { return *m_stream; }
  9099. IConfigPtr ReporterConfig::fullConfig() const { return m_fullConfig; }
  9100. TestRunInfo::TestRunInfo( std::string const& _name ) : name( _name ) {}
  9101. GroupInfo::GroupInfo( std::string const& _name,
  9102. std::size_t _groupIndex,
  9103. std::size_t _groupsCount )
  9104. : name( _name ),
  9105. groupIndex( _groupIndex ),
  9106. groupsCounts( _groupsCount )
  9107. {}
  9108. AssertionStats::AssertionStats( AssertionResult const& _assertionResult,
  9109. std::vector<MessageInfo> const& _infoMessages,
  9110. Totals const& _totals )
  9111. : assertionResult( _assertionResult ),
  9112. infoMessages( _infoMessages ),
  9113. totals( _totals )
  9114. {
  9115. assertionResult.m_resultData.lazyExpression.m_transientExpression = _assertionResult.m_resultData.lazyExpression.m_transientExpression;
  9116. if( assertionResult.hasMessage() ) {
  9117. // Copy message into messages list.
  9118. // !TBD This should have been done earlier, somewhere
  9119. MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() );
  9120. builder << assertionResult.getMessage();
  9121. builder.m_info.message = builder.m_stream.str();
  9122. infoMessages.push_back( builder.m_info );
  9123. }
  9124. }
  9125. AssertionStats::~AssertionStats() = default;
  9126. SectionStats::SectionStats( SectionInfo const& _sectionInfo,
  9127. Counts const& _assertions,
  9128. double _durationInSeconds,
  9129. bool _missingAssertions )
  9130. : sectionInfo( _sectionInfo ),
  9131. assertions( _assertions ),
  9132. durationInSeconds( _durationInSeconds ),
  9133. missingAssertions( _missingAssertions )
  9134. {}
  9135. SectionStats::~SectionStats() = default;
  9136. TestCaseStats::TestCaseStats( TestCaseInfo const& _testInfo,
  9137. Totals const& _totals,
  9138. std::string const& _stdOut,
  9139. std::string const& _stdErr,
  9140. bool _aborting )
  9141. : testInfo( _testInfo ),
  9142. totals( _totals ),
  9143. stdOut( _stdOut ),
  9144. stdErr( _stdErr ),
  9145. aborting( _aborting )
  9146. {}
  9147. TestCaseStats::~TestCaseStats() = default;
  9148. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo,
  9149. Totals const& _totals,
  9150. bool _aborting )
  9151. : groupInfo( _groupInfo ),
  9152. totals( _totals ),
  9153. aborting( _aborting )
  9154. {}
  9155. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo )
  9156. : groupInfo( _groupInfo ),
  9157. aborting( false )
  9158. {}
  9159. TestGroupStats::~TestGroupStats() = default;
  9160. TestRunStats::TestRunStats( TestRunInfo const& _runInfo,
  9161. Totals const& _totals,
  9162. bool _aborting )
  9163. : runInfo( _runInfo ),
  9164. totals( _totals ),
  9165. aborting( _aborting )
  9166. {}
  9167. TestRunStats::~TestRunStats() = default;
  9168. void IStreamingReporter::fatalErrorEncountered( StringRef ) {}
  9169. bool IStreamingReporter::isMulti() const { return false; }
  9170. IReporterFactory::~IReporterFactory() = default;
  9171. IReporterRegistry::~IReporterRegistry() = default;
  9172. } // end namespace Catch
  9173. // end catch_interfaces_reporter.cpp
  9174. // start catch_interfaces_runner.cpp
  9175. namespace Catch {
  9176. IRunner::~IRunner() = default;
  9177. }
  9178. // end catch_interfaces_runner.cpp
  9179. // start catch_interfaces_testcase.cpp
  9180. namespace Catch {
  9181. ITestInvoker::~ITestInvoker() = default;
  9182. ITestCaseRegistry::~ITestCaseRegistry() = default;
  9183. }
  9184. // end catch_interfaces_testcase.cpp
  9185. // start catch_leak_detector.cpp
  9186. #ifdef CATCH_CONFIG_WINDOWS_CRTDBG
  9187. #include <crtdbg.h>
  9188. namespace Catch {
  9189. LeakDetector::LeakDetector() {
  9190. int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
  9191. flag |= _CRTDBG_LEAK_CHECK_DF;
  9192. flag |= _CRTDBG_ALLOC_MEM_DF;
  9193. _CrtSetDbgFlag(flag);
  9194. _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
  9195. _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
  9196. // Change this to leaking allocation's number to break there
  9197. _CrtSetBreakAlloc(-1);
  9198. }
  9199. }
  9200. #else
  9201. Catch::LeakDetector::LeakDetector() {}
  9202. #endif
  9203. Catch::LeakDetector::~LeakDetector() {
  9204. Catch::cleanUp();
  9205. }
  9206. // end catch_leak_detector.cpp
  9207. // start catch_list.cpp
  9208. // start catch_list.h
  9209. #include <set>
  9210. namespace Catch {
  9211. std::size_t listTests( Config const& config );
  9212. std::size_t listTestsNamesOnly( Config const& config );
  9213. struct TagInfo {
  9214. void add( std::string const& spelling );
  9215. std::string all() const;
  9216. std::set<std::string> spellings;
  9217. std::size_t count = 0;
  9218. };
  9219. std::size_t listTags( Config const& config );
  9220. std::size_t listReporters();
  9221. Option<std::size_t> list( std::shared_ptr<Config> const& config );
  9222. } // end namespace Catch
  9223. // end catch_list.h
  9224. // start catch_text.h
  9225. namespace Catch {
  9226. using namespace clara::TextFlow;
  9227. }
  9228. // end catch_text.h
  9229. #include <limits>
  9230. #include <algorithm>
  9231. #include <iomanip>
  9232. namespace Catch {
  9233. std::size_t listTests( Config const& config ) {
  9234. TestSpec testSpec = config.testSpec();
  9235. if( config.hasTestFilters() )
  9236. Catch::cout() << "Matching test cases:\n";
  9237. else {
  9238. Catch::cout() << "All available test cases:\n";
  9239. }
  9240. auto matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  9241. for( auto const& testCaseInfo : matchedTestCases ) {
  9242. Colour::Code colour = testCaseInfo.isHidden()
  9243. ? Colour::SecondaryText
  9244. : Colour::None;
  9245. Colour colourGuard( colour );
  9246. Catch::cout() << Column( testCaseInfo.name ).initialIndent( 2 ).indent( 4 ) << "\n";
  9247. if( config.verbosity() >= Verbosity::High ) {
  9248. Catch::cout() << Column( Catch::Detail::stringify( testCaseInfo.lineInfo ) ).indent(4) << std::endl;
  9249. std::string description = testCaseInfo.description;
  9250. if( description.empty() )
  9251. description = "(NO DESCRIPTION)";
  9252. Catch::cout() << Column( description ).indent(4) << std::endl;
  9253. }
  9254. if( !testCaseInfo.tags.empty() )
  9255. Catch::cout() << Column( testCaseInfo.tagsAsString() ).indent( 6 ) << "\n";
  9256. }
  9257. if( !config.hasTestFilters() )
  9258. Catch::cout() << pluralise( matchedTestCases.size(), "test case" ) << '\n' << std::endl;
  9259. else
  9260. Catch::cout() << pluralise( matchedTestCases.size(), "matching test case" ) << '\n' << std::endl;
  9261. return matchedTestCases.size();
  9262. }
  9263. std::size_t listTestsNamesOnly( Config const& config ) {
  9264. TestSpec testSpec = config.testSpec();
  9265. std::size_t matchedTests = 0;
  9266. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  9267. for( auto const& testCaseInfo : matchedTestCases ) {
  9268. matchedTests++;
  9269. if( startsWith( testCaseInfo.name, '#' ) )
  9270. Catch::cout() << '"' << testCaseInfo.name << '"';
  9271. else
  9272. Catch::cout() << testCaseInfo.name;
  9273. if ( config.verbosity() >= Verbosity::High )
  9274. Catch::cout() << "\t@" << testCaseInfo.lineInfo;
  9275. Catch::cout() << std::endl;
  9276. }
  9277. return matchedTests;
  9278. }
  9279. void TagInfo::add( std::string const& spelling ) {
  9280. ++count;
  9281. spellings.insert( spelling );
  9282. }
  9283. std::string TagInfo::all() const {
  9284. size_t size = 0;
  9285. for (auto const& spelling : spellings) {
  9286. // Add 2 for the brackes
  9287. size += spelling.size() + 2;
  9288. }
  9289. std::string out; out.reserve(size);
  9290. for (auto const& spelling : spellings) {
  9291. out += '[';
  9292. out += spelling;
  9293. out += ']';
  9294. }
  9295. return out;
  9296. }
  9297. std::size_t listTags( Config const& config ) {
  9298. TestSpec testSpec = config.testSpec();
  9299. if( config.hasTestFilters() )
  9300. Catch::cout() << "Tags for matching test cases:\n";
  9301. else {
  9302. Catch::cout() << "All available tags:\n";
  9303. }
  9304. std::map<std::string, TagInfo> tagCounts;
  9305. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  9306. for( auto const& testCase : matchedTestCases ) {
  9307. for( auto const& tagName : testCase.getTestCaseInfo().tags ) {
  9308. std::string lcaseTagName = toLower( tagName );
  9309. auto countIt = tagCounts.find( lcaseTagName );
  9310. if( countIt == tagCounts.end() )
  9311. countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first;
  9312. countIt->second.add( tagName );
  9313. }
  9314. }
  9315. for( auto const& tagCount : tagCounts ) {
  9316. ReusableStringStream rss;
  9317. rss << " " << std::setw(2) << tagCount.second.count << " ";
  9318. auto str = rss.str();
  9319. auto wrapper = Column( tagCount.second.all() )
  9320. .initialIndent( 0 )
  9321. .indent( str.size() )
  9322. .width( CATCH_CONFIG_CONSOLE_WIDTH-10 );
  9323. Catch::cout() << str << wrapper << '\n';
  9324. }
  9325. Catch::cout() << pluralise( tagCounts.size(), "tag" ) << '\n' << std::endl;
  9326. return tagCounts.size();
  9327. }
  9328. std::size_t listReporters() {
  9329. Catch::cout() << "Available reporters:\n";
  9330. IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
  9331. std::size_t maxNameLen = 0;
  9332. for( auto const& factoryKvp : factories )
  9333. maxNameLen = (std::max)( maxNameLen, factoryKvp.first.size() );
  9334. for( auto const& factoryKvp : factories ) {
  9335. Catch::cout()
  9336. << Column( factoryKvp.first + ":" )
  9337. .indent(2)
  9338. .width( 5+maxNameLen )
  9339. + Column( factoryKvp.second->getDescription() )
  9340. .initialIndent(0)
  9341. .indent(2)
  9342. .width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 )
  9343. << "\n";
  9344. }
  9345. Catch::cout() << std::endl;
  9346. return factories.size();
  9347. }
  9348. Option<std::size_t> list( std::shared_ptr<Config> const& config ) {
  9349. Option<std::size_t> listedCount;
  9350. getCurrentMutableContext().setConfig( config );
  9351. if( config->listTests() )
  9352. listedCount = listedCount.valueOr(0) + listTests( *config );
  9353. if( config->listTestNamesOnly() )
  9354. listedCount = listedCount.valueOr(0) + listTestsNamesOnly( *config );
  9355. if( config->listTags() )
  9356. listedCount = listedCount.valueOr(0) + listTags( *config );
  9357. if( config->listReporters() )
  9358. listedCount = listedCount.valueOr(0) + listReporters();
  9359. return listedCount;
  9360. }
  9361. } // end namespace Catch
  9362. // end catch_list.cpp
  9363. // start catch_matchers.cpp
  9364. namespace Catch {
  9365. namespace Matchers {
  9366. namespace Impl {
  9367. std::string MatcherUntypedBase::toString() const {
  9368. if( m_cachedToString.empty() )
  9369. m_cachedToString = describe();
  9370. return m_cachedToString;
  9371. }
  9372. MatcherUntypedBase::~MatcherUntypedBase() = default;
  9373. } // namespace Impl
  9374. } // namespace Matchers
  9375. using namespace Matchers;
  9376. using Matchers::Impl::MatcherBase;
  9377. } // namespace Catch
  9378. // end catch_matchers.cpp
  9379. // start catch_matchers_floating.cpp
  9380. // start catch_polyfills.hpp
  9381. namespace Catch {
  9382. bool isnan(float f);
  9383. bool isnan(double d);
  9384. }
  9385. // end catch_polyfills.hpp
  9386. // start catch_to_string.hpp
  9387. #include <string>
  9388. namespace Catch {
  9389. template <typename T>
  9390. std::string to_string(T const& t) {
  9391. #if defined(CATCH_CONFIG_CPP11_TO_STRING)
  9392. return std::to_string(t);
  9393. #else
  9394. ReusableStringStream rss;
  9395. rss << t;
  9396. return rss.str();
  9397. #endif
  9398. }
  9399. } // end namespace Catch
  9400. // end catch_to_string.hpp
  9401. #include <cstdlib>
  9402. #include <cstdint>
  9403. #include <cstring>
  9404. #include <sstream>
  9405. #include <iomanip>
  9406. #include <limits>
  9407. namespace Catch {
  9408. namespace Matchers {
  9409. namespace Floating {
  9410. enum class FloatingPointKind : uint8_t {
  9411. Float,
  9412. Double
  9413. };
  9414. }
  9415. }
  9416. }
  9417. namespace {
  9418. template <typename T>
  9419. struct Converter;
  9420. template <>
  9421. struct Converter<float> {
  9422. static_assert(sizeof(float) == sizeof(int32_t), "Important ULP matcher assumption violated");
  9423. Converter(float f) {
  9424. std::memcpy(&i, &f, sizeof(f));
  9425. }
  9426. int32_t i;
  9427. };
  9428. template <>
  9429. struct Converter<double> {
  9430. static_assert(sizeof(double) == sizeof(int64_t), "Important ULP matcher assumption violated");
  9431. Converter(double d) {
  9432. std::memcpy(&i, &d, sizeof(d));
  9433. }
  9434. int64_t i;
  9435. };
  9436. template <typename T>
  9437. auto convert(T t) -> Converter<T> {
  9438. return Converter<T>(t);
  9439. }
  9440. template <typename FP>
  9441. bool almostEqualUlps(FP lhs, FP rhs, int maxUlpDiff) {
  9442. // Comparison with NaN should always be false.
  9443. // This way we can rule it out before getting into the ugly details
  9444. if (Catch::isnan(lhs) || Catch::isnan(rhs)) {
  9445. return false;
  9446. }
  9447. auto lc = convert(lhs);
  9448. auto rc = convert(rhs);
  9449. if ((lc.i < 0) != (rc.i < 0)) {
  9450. // Potentially we can have +0 and -0
  9451. return lhs == rhs;
  9452. }
  9453. auto ulpDiff = std::abs(lc.i - rc.i);
  9454. return ulpDiff <= maxUlpDiff;
  9455. }
  9456. template <typename FP>
  9457. FP step(FP start, FP direction, int steps) {
  9458. for (int i = 0; i < steps; ++i) {
  9459. start = std::nextafter(start, direction);
  9460. }
  9461. return start;
  9462. }
  9463. } // end anonymous namespace
  9464. namespace Catch {
  9465. namespace Matchers {
  9466. namespace Floating {
  9467. WithinAbsMatcher::WithinAbsMatcher(double target, double margin)
  9468. :m_target{ target }, m_margin{ margin } {
  9469. CATCH_ENFORCE(margin >= 0, "Invalid margin: " << margin << '.'
  9470. << " Margin has to be non-negative.");
  9471. }
  9472. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  9473. // But without the subtraction to allow for INFINITY in comparison
  9474. bool WithinAbsMatcher::match(double const& matchee) const {
  9475. return (matchee + m_margin >= m_target) && (m_target + m_margin >= matchee);
  9476. }
  9477. std::string WithinAbsMatcher::describe() const {
  9478. return "is within " + ::Catch::Detail::stringify(m_margin) + " of " + ::Catch::Detail::stringify(m_target);
  9479. }
  9480. WithinUlpsMatcher::WithinUlpsMatcher(double target, int ulps, FloatingPointKind baseType)
  9481. :m_target{ target }, m_ulps{ ulps }, m_type{ baseType } {
  9482. CATCH_ENFORCE(ulps >= 0, "Invalid ULP setting: " << ulps << '.'
  9483. << " ULPs have to be non-negative.");
  9484. }
  9485. #if defined(__clang__)
  9486. #pragma clang diagnostic push
  9487. // Clang <3.5 reports on the default branch in the switch below
  9488. #pragma clang diagnostic ignored "-Wunreachable-code"
  9489. #endif
  9490. bool WithinUlpsMatcher::match(double const& matchee) const {
  9491. switch (m_type) {
  9492. case FloatingPointKind::Float:
  9493. return almostEqualUlps<float>(static_cast<float>(matchee), static_cast<float>(m_target), m_ulps);
  9494. case FloatingPointKind::Double:
  9495. return almostEqualUlps<double>(matchee, m_target, m_ulps);
  9496. default:
  9497. CATCH_INTERNAL_ERROR( "Unknown FloatingPointKind value" );
  9498. }
  9499. }
  9500. #if defined(__clang__)
  9501. #pragma clang diagnostic pop
  9502. #endif
  9503. std::string WithinUlpsMatcher::describe() const {
  9504. std::stringstream ret;
  9505. ret << "is within " << m_ulps << " ULPs of " << ::Catch::Detail::stringify(m_target);
  9506. if (m_type == FloatingPointKind::Float) {
  9507. ret << 'f';
  9508. }
  9509. ret << " ([";
  9510. ret << std::fixed << std::setprecision(std::numeric_limits<double>::max_digits10);
  9511. if (m_type == FloatingPointKind::Double) {
  9512. ret << step(m_target, static_cast<double>(-INFINITY), m_ulps)
  9513. << ", "
  9514. << step(m_target, static_cast<double>(INFINITY), m_ulps);
  9515. } else {
  9516. ret << step<float>(static_cast<float>(m_target), -INFINITY, m_ulps)
  9517. << ", "
  9518. << step<float>(static_cast<float>(m_target), INFINITY, m_ulps);
  9519. }
  9520. ret << "])";
  9521. return ret.str();
  9522. //return "is within " + Catch::to_string(m_ulps) + " ULPs of " + ::Catch::Detail::stringify(m_target) + ((m_type == FloatingPointKind::Float)? "f" : "");
  9523. }
  9524. }// namespace Floating
  9525. Floating::WithinUlpsMatcher WithinULP(double target, int maxUlpDiff) {
  9526. return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Double);
  9527. }
  9528. Floating::WithinUlpsMatcher WithinULP(float target, int maxUlpDiff) {
  9529. return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Float);
  9530. }
  9531. Floating::WithinAbsMatcher WithinAbs(double target, double margin) {
  9532. return Floating::WithinAbsMatcher(target, margin);
  9533. }
  9534. } // namespace Matchers
  9535. } // namespace Catch
  9536. // end catch_matchers_floating.cpp
  9537. // start catch_matchers_generic.cpp
  9538. std::string Catch::Matchers::Generic::Detail::finalizeDescription(const std::string& desc) {
  9539. if (desc.empty()) {
  9540. return "matches undescribed predicate";
  9541. } else {
  9542. return "matches predicate: \"" + desc + '"';
  9543. }
  9544. }
  9545. // end catch_matchers_generic.cpp
  9546. // start catch_matchers_string.cpp
  9547. #include <regex>
  9548. namespace Catch {
  9549. namespace Matchers {
  9550. namespace StdString {
  9551. CasedString::CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity )
  9552. : m_caseSensitivity( caseSensitivity ),
  9553. m_str( adjustString( str ) )
  9554. {}
  9555. std::string CasedString::adjustString( std::string const& str ) const {
  9556. return m_caseSensitivity == CaseSensitive::No
  9557. ? toLower( str )
  9558. : str;
  9559. }
  9560. std::string CasedString::caseSensitivitySuffix() const {
  9561. return m_caseSensitivity == CaseSensitive::No
  9562. ? " (case insensitive)"
  9563. : std::string();
  9564. }
  9565. StringMatcherBase::StringMatcherBase( std::string const& operation, CasedString const& comparator )
  9566. : m_comparator( comparator ),
  9567. m_operation( operation ) {
  9568. }
  9569. std::string StringMatcherBase::describe() const {
  9570. std::string description;
  9571. description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
  9572. m_comparator.caseSensitivitySuffix().size());
  9573. description += m_operation;
  9574. description += ": \"";
  9575. description += m_comparator.m_str;
  9576. description += "\"";
  9577. description += m_comparator.caseSensitivitySuffix();
  9578. return description;
  9579. }
  9580. EqualsMatcher::EqualsMatcher( CasedString const& comparator ) : StringMatcherBase( "equals", comparator ) {}
  9581. bool EqualsMatcher::match( std::string const& source ) const {
  9582. return m_comparator.adjustString( source ) == m_comparator.m_str;
  9583. }
  9584. ContainsMatcher::ContainsMatcher( CasedString const& comparator ) : StringMatcherBase( "contains", comparator ) {}
  9585. bool ContainsMatcher::match( std::string const& source ) const {
  9586. return contains( m_comparator.adjustString( source ), m_comparator.m_str );
  9587. }
  9588. StartsWithMatcher::StartsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "starts with", comparator ) {}
  9589. bool StartsWithMatcher::match( std::string const& source ) const {
  9590. return startsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  9591. }
  9592. EndsWithMatcher::EndsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "ends with", comparator ) {}
  9593. bool EndsWithMatcher::match( std::string const& source ) const {
  9594. return endsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  9595. }
  9596. RegexMatcher::RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity): m_regex(std::move(regex)), m_caseSensitivity(caseSensitivity) {}
  9597. bool RegexMatcher::match(std::string const& matchee) const {
  9598. auto flags = std::regex::ECMAScript; // ECMAScript is the default syntax option anyway
  9599. if (m_caseSensitivity == CaseSensitive::Choice::No) {
  9600. flags |= std::regex::icase;
  9601. }
  9602. auto reg = std::regex(m_regex, flags);
  9603. return std::regex_match(matchee, reg);
  9604. }
  9605. std::string RegexMatcher::describe() const {
  9606. return "matches " + ::Catch::Detail::stringify(m_regex) + ((m_caseSensitivity == CaseSensitive::Choice::Yes)? " case sensitively" : " case insensitively");
  9607. }
  9608. } // namespace StdString
  9609. StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  9610. return StdString::EqualsMatcher( StdString::CasedString( str, caseSensitivity) );
  9611. }
  9612. StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  9613. return StdString::ContainsMatcher( StdString::CasedString( str, caseSensitivity) );
  9614. }
  9615. StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  9616. return StdString::EndsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  9617. }
  9618. StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  9619. return StdString::StartsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  9620. }
  9621. StdString::RegexMatcher Matches(std::string const& regex, CaseSensitive::Choice caseSensitivity) {
  9622. return StdString::RegexMatcher(regex, caseSensitivity);
  9623. }
  9624. } // namespace Matchers
  9625. } // namespace Catch
  9626. // end catch_matchers_string.cpp
  9627. // start catch_message.cpp
  9628. // start catch_uncaught_exceptions.h
  9629. namespace Catch {
  9630. bool uncaught_exceptions();
  9631. } // end namespace Catch
  9632. // end catch_uncaught_exceptions.h
  9633. #include <cassert>
  9634. #include <stack>
  9635. namespace Catch {
  9636. MessageInfo::MessageInfo( StringRef const& _macroName,
  9637. SourceLineInfo const& _lineInfo,
  9638. ResultWas::OfType _type )
  9639. : macroName( _macroName ),
  9640. lineInfo( _lineInfo ),
  9641. type( _type ),
  9642. sequence( ++globalCount )
  9643. {}
  9644. bool MessageInfo::operator==( MessageInfo const& other ) const {
  9645. return sequence == other.sequence;
  9646. }
  9647. bool MessageInfo::operator<( MessageInfo const& other ) const {
  9648. return sequence < other.sequence;
  9649. }
  9650. // This may need protecting if threading support is added
  9651. unsigned int MessageInfo::globalCount = 0;
  9652. ////////////////////////////////////////////////////////////////////////////
  9653. Catch::MessageBuilder::MessageBuilder( StringRef const& macroName,
  9654. SourceLineInfo const& lineInfo,
  9655. ResultWas::OfType type )
  9656. :m_info(macroName, lineInfo, type) {}
  9657. ////////////////////////////////////////////////////////////////////////////
  9658. ScopedMessage::ScopedMessage( MessageBuilder const& builder )
  9659. : m_info( builder.m_info ), m_moved()
  9660. {
  9661. m_info.message = builder.m_stream.str();
  9662. getResultCapture().pushScopedMessage( m_info );
  9663. }
  9664. ScopedMessage::ScopedMessage( ScopedMessage&& old )
  9665. : m_info( old.m_info ), m_moved()
  9666. {
  9667. old.m_moved = true;
  9668. }
  9669. ScopedMessage::~ScopedMessage() {
  9670. if ( !uncaught_exceptions() && !m_moved ){
  9671. getResultCapture().popScopedMessage(m_info);
  9672. }
  9673. }
  9674. Capturer::Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names ) {
  9675. auto trimmed = [&] (size_t start, size_t end) {
  9676. while (names[start] == ',' || isspace(names[start])) {
  9677. ++start;
  9678. }
  9679. while (names[end] == ',' || isspace(names[end])) {
  9680. --end;
  9681. }
  9682. return names.substr(start, end - start + 1);
  9683. };
  9684. auto skipq = [&] (size_t start, char quote) {
  9685. for (auto i = start + 1; i < names.size() ; ++i) {
  9686. if (names[i] == quote)
  9687. return i;
  9688. if (names[i] == '\\')
  9689. ++i;
  9690. }
  9691. CATCH_INTERNAL_ERROR("CAPTURE parsing encountered unmatched quote");
  9692. };
  9693. size_t start = 0;
  9694. std::stack<char> openings;
  9695. for (size_t pos = 0; pos < names.size(); ++pos) {
  9696. char c = names[pos];
  9697. switch (c) {
  9698. case '[':
  9699. case '{':
  9700. case '(':
  9701. // It is basically impossible to disambiguate between
  9702. // comparison and start of template args in this context
  9703. // case '<':
  9704. openings.push(c);
  9705. break;
  9706. case ']':
  9707. case '}':
  9708. case ')':
  9709. // case '>':
  9710. openings.pop();
  9711. break;
  9712. case '"':
  9713. case '\'':
  9714. pos = skipq(pos, c);
  9715. break;
  9716. case ',':
  9717. if (start != pos && openings.size() == 0) {
  9718. m_messages.emplace_back(macroName, lineInfo, resultType);
  9719. m_messages.back().message = trimmed(start, pos);
  9720. m_messages.back().message += " := ";
  9721. start = pos;
  9722. }
  9723. }
  9724. }
  9725. assert(openings.size() == 0 && "Mismatched openings");
  9726. m_messages.emplace_back(macroName, lineInfo, resultType);
  9727. m_messages.back().message = trimmed(start, names.size() - 1);
  9728. m_messages.back().message += " := ";
  9729. }
  9730. Capturer::~Capturer() {
  9731. if ( !uncaught_exceptions() ){
  9732. assert( m_captured == m_messages.size() );
  9733. for( size_t i = 0; i < m_captured; ++i )
  9734. m_resultCapture.popScopedMessage( m_messages[i] );
  9735. }
  9736. }
  9737. void Capturer::captureValue( size_t index, std::string const& value ) {
  9738. assert( index < m_messages.size() );
  9739. m_messages[index].message += value;
  9740. m_resultCapture.pushScopedMessage( m_messages[index] );
  9741. m_captured++;
  9742. }
  9743. } // end namespace Catch
  9744. // end catch_message.cpp
  9745. // start catch_output_redirect.cpp
  9746. // start catch_output_redirect.h
  9747. #ifndef TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  9748. #define TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  9749. #include <cstdio>
  9750. #include <iosfwd>
  9751. #include <string>
  9752. namespace Catch {
  9753. class RedirectedStream {
  9754. std::ostream& m_originalStream;
  9755. std::ostream& m_redirectionStream;
  9756. std::streambuf* m_prevBuf;
  9757. public:
  9758. RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream );
  9759. ~RedirectedStream();
  9760. };
  9761. class RedirectedStdOut {
  9762. ReusableStringStream m_rss;
  9763. RedirectedStream m_cout;
  9764. public:
  9765. RedirectedStdOut();
  9766. auto str() const -> std::string;
  9767. };
  9768. // StdErr has two constituent streams in C++, std::cerr and std::clog
  9769. // This means that we need to redirect 2 streams into 1 to keep proper
  9770. // order of writes
  9771. class RedirectedStdErr {
  9772. ReusableStringStream m_rss;
  9773. RedirectedStream m_cerr;
  9774. RedirectedStream m_clog;
  9775. public:
  9776. RedirectedStdErr();
  9777. auto str() const -> std::string;
  9778. };
  9779. class RedirectedStreams {
  9780. public:
  9781. RedirectedStreams(RedirectedStreams const&) = delete;
  9782. RedirectedStreams& operator=(RedirectedStreams const&) = delete;
  9783. RedirectedStreams(RedirectedStreams&&) = delete;
  9784. RedirectedStreams& operator=(RedirectedStreams&&) = delete;
  9785. RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr);
  9786. ~RedirectedStreams();
  9787. private:
  9788. std::string& m_redirectedCout;
  9789. std::string& m_redirectedCerr;
  9790. RedirectedStdOut m_redirectedStdOut;
  9791. RedirectedStdErr m_redirectedStdErr;
  9792. };
  9793. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  9794. // Windows's implementation of std::tmpfile is terrible (it tries
  9795. // to create a file inside system folder, thus requiring elevated
  9796. // privileges for the binary), so we have to use tmpnam(_s) and
  9797. // create the file ourselves there.
  9798. class TempFile {
  9799. public:
  9800. TempFile(TempFile const&) = delete;
  9801. TempFile& operator=(TempFile const&) = delete;
  9802. TempFile(TempFile&&) = delete;
  9803. TempFile& operator=(TempFile&&) = delete;
  9804. TempFile();
  9805. ~TempFile();
  9806. std::FILE* getFile();
  9807. std::string getContents();
  9808. private:
  9809. std::FILE* m_file = nullptr;
  9810. #if defined(_MSC_VER)
  9811. char m_buffer[L_tmpnam] = { 0 };
  9812. #endif
  9813. };
  9814. class OutputRedirect {
  9815. public:
  9816. OutputRedirect(OutputRedirect const&) = delete;
  9817. OutputRedirect& operator=(OutputRedirect const&) = delete;
  9818. OutputRedirect(OutputRedirect&&) = delete;
  9819. OutputRedirect& operator=(OutputRedirect&&) = delete;
  9820. OutputRedirect(std::string& stdout_dest, std::string& stderr_dest);
  9821. ~OutputRedirect();
  9822. private:
  9823. int m_originalStdout = -1;
  9824. int m_originalStderr = -1;
  9825. TempFile m_stdoutFile;
  9826. TempFile m_stderrFile;
  9827. std::string& m_stdoutDest;
  9828. std::string& m_stderrDest;
  9829. };
  9830. #endif
  9831. } // end namespace Catch
  9832. #endif // TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  9833. // end catch_output_redirect.h
  9834. #include <cstdio>
  9835. #include <cstring>
  9836. #include <fstream>
  9837. #include <sstream>
  9838. #include <stdexcept>
  9839. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  9840. #if defined(_MSC_VER)
  9841. #include <io.h> //_dup and _dup2
  9842. #define dup _dup
  9843. #define dup2 _dup2
  9844. #define fileno _fileno
  9845. #else
  9846. #include <unistd.h> // dup and dup2
  9847. #endif
  9848. #endif
  9849. namespace Catch {
  9850. RedirectedStream::RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream )
  9851. : m_originalStream( originalStream ),
  9852. m_redirectionStream( redirectionStream ),
  9853. m_prevBuf( m_originalStream.rdbuf() )
  9854. {
  9855. m_originalStream.rdbuf( m_redirectionStream.rdbuf() );
  9856. }
  9857. RedirectedStream::~RedirectedStream() {
  9858. m_originalStream.rdbuf( m_prevBuf );
  9859. }
  9860. RedirectedStdOut::RedirectedStdOut() : m_cout( Catch::cout(), m_rss.get() ) {}
  9861. auto RedirectedStdOut::str() const -> std::string { return m_rss.str(); }
  9862. RedirectedStdErr::RedirectedStdErr()
  9863. : m_cerr( Catch::cerr(), m_rss.get() ),
  9864. m_clog( Catch::clog(), m_rss.get() )
  9865. {}
  9866. auto RedirectedStdErr::str() const -> std::string { return m_rss.str(); }
  9867. RedirectedStreams::RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr)
  9868. : m_redirectedCout(redirectedCout),
  9869. m_redirectedCerr(redirectedCerr)
  9870. {}
  9871. RedirectedStreams::~RedirectedStreams() {
  9872. m_redirectedCout += m_redirectedStdOut.str();
  9873. m_redirectedCerr += m_redirectedStdErr.str();
  9874. }
  9875. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  9876. #if defined(_MSC_VER)
  9877. TempFile::TempFile() {
  9878. if (tmpnam_s(m_buffer)) {
  9879. CATCH_RUNTIME_ERROR("Could not get a temp filename");
  9880. }
  9881. if (fopen_s(&m_file, m_buffer, "w")) {
  9882. char buffer[100];
  9883. if (strerror_s(buffer, errno)) {
  9884. CATCH_RUNTIME_ERROR("Could not translate errno to a string");
  9885. }
  9886. CATCH_RUNTIME_ERROR("Could not open the temp file: '" << m_buffer << "' because: " << buffer);
  9887. }
  9888. }
  9889. #else
  9890. TempFile::TempFile() {
  9891. m_file = std::tmpfile();
  9892. if (!m_file) {
  9893. CATCH_RUNTIME_ERROR("Could not create a temp file.");
  9894. }
  9895. }
  9896. #endif
  9897. TempFile::~TempFile() {
  9898. // TBD: What to do about errors here?
  9899. std::fclose(m_file);
  9900. // We manually create the file on Windows only, on Linux
  9901. // it will be autodeleted
  9902. #if defined(_MSC_VER)
  9903. std::remove(m_buffer);
  9904. #endif
  9905. }
  9906. FILE* TempFile::getFile() {
  9907. return m_file;
  9908. }
  9909. std::string TempFile::getContents() {
  9910. std::stringstream sstr;
  9911. char buffer[100] = {};
  9912. std::rewind(m_file);
  9913. while (std::fgets(buffer, sizeof(buffer), m_file)) {
  9914. sstr << buffer;
  9915. }
  9916. return sstr.str();
  9917. }
  9918. OutputRedirect::OutputRedirect(std::string& stdout_dest, std::string& stderr_dest) :
  9919. m_originalStdout(dup(1)),
  9920. m_originalStderr(dup(2)),
  9921. m_stdoutDest(stdout_dest),
  9922. m_stderrDest(stderr_dest) {
  9923. dup2(fileno(m_stdoutFile.getFile()), 1);
  9924. dup2(fileno(m_stderrFile.getFile()), 2);
  9925. }
  9926. OutputRedirect::~OutputRedirect() {
  9927. Catch::cout() << std::flush;
  9928. fflush(stdout);
  9929. // Since we support overriding these streams, we flush cerr
  9930. // even though std::cerr is unbuffered
  9931. Catch::cerr() << std::flush;
  9932. Catch::clog() << std::flush;
  9933. fflush(stderr);
  9934. dup2(m_originalStdout, 1);
  9935. dup2(m_originalStderr, 2);
  9936. m_stdoutDest += m_stdoutFile.getContents();
  9937. m_stderrDest += m_stderrFile.getContents();
  9938. }
  9939. #endif // CATCH_CONFIG_NEW_CAPTURE
  9940. } // namespace Catch
  9941. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  9942. #if defined(_MSC_VER)
  9943. #undef dup
  9944. #undef dup2
  9945. #undef fileno
  9946. #endif
  9947. #endif
  9948. // end catch_output_redirect.cpp
  9949. // start catch_polyfills.cpp
  9950. #include <cmath>
  9951. namespace Catch {
  9952. #if !defined(CATCH_CONFIG_POLYFILL_ISNAN)
  9953. bool isnan(float f) {
  9954. return std::isnan(f);
  9955. }
  9956. bool isnan(double d) {
  9957. return std::isnan(d);
  9958. }
  9959. #else
  9960. // For now we only use this for embarcadero
  9961. bool isnan(float f) {
  9962. return std::_isnan(f);
  9963. }
  9964. bool isnan(double d) {
  9965. return std::_isnan(d);
  9966. }
  9967. #endif
  9968. } // end namespace Catch
  9969. // end catch_polyfills.cpp
  9970. // start catch_random_number_generator.cpp
  9971. namespace Catch {
  9972. std::mt19937& rng() {
  9973. static std::mt19937 s_rng;
  9974. return s_rng;
  9975. }
  9976. void seedRng( IConfig const& config ) {
  9977. if( config.rngSeed() != 0 ) {
  9978. std::srand( config.rngSeed() );
  9979. rng().seed( config.rngSeed() );
  9980. }
  9981. }
  9982. unsigned int rngSeed() {
  9983. return getCurrentContext().getConfig()->rngSeed();
  9984. }
  9985. }
  9986. // end catch_random_number_generator.cpp
  9987. // start catch_registry_hub.cpp
  9988. // start catch_test_case_registry_impl.h
  9989. #include <vector>
  9990. #include <set>
  9991. #include <algorithm>
  9992. #include <ios>
  9993. namespace Catch {
  9994. class TestCase;
  9995. struct IConfig;
  9996. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases );
  9997. bool isThrowSafe( TestCase const& testCase, IConfig const& config );
  9998. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
  9999. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions );
  10000. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
  10001. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
  10002. class TestRegistry : public ITestCaseRegistry {
  10003. public:
  10004. virtual ~TestRegistry() = default;
  10005. virtual void registerTest( TestCase const& testCase );
  10006. std::vector<TestCase> const& getAllTests() const override;
  10007. std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const override;
  10008. private:
  10009. std::vector<TestCase> m_functions;
  10010. mutable RunTests::InWhatOrder m_currentSortOrder = RunTests::InDeclarationOrder;
  10011. mutable std::vector<TestCase> m_sortedFunctions;
  10012. std::size_t m_unnamedCount = 0;
  10013. std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised
  10014. };
  10015. ///////////////////////////////////////////////////////////////////////////
  10016. class TestInvokerAsFunction : public ITestInvoker {
  10017. void(*m_testAsFunction)();
  10018. public:
  10019. TestInvokerAsFunction( void(*testAsFunction)() ) noexcept;
  10020. void invoke() const override;
  10021. };
  10022. std::string extractClassName( StringRef const& classOrQualifiedMethodName );
  10023. ///////////////////////////////////////////////////////////////////////////
  10024. } // end namespace Catch
  10025. // end catch_test_case_registry_impl.h
  10026. // start catch_reporter_registry.h
  10027. #include <map>
  10028. namespace Catch {
  10029. class ReporterRegistry : public IReporterRegistry {
  10030. public:
  10031. ~ReporterRegistry() override;
  10032. IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const override;
  10033. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory );
  10034. void registerListener( IReporterFactoryPtr const& factory );
  10035. FactoryMap const& getFactories() const override;
  10036. Listeners const& getListeners() const override;
  10037. private:
  10038. FactoryMap m_factories;
  10039. Listeners m_listeners;
  10040. };
  10041. }
  10042. // end catch_reporter_registry.h
  10043. // start catch_tag_alias_registry.h
  10044. // start catch_tag_alias.h
  10045. #include <string>
  10046. namespace Catch {
  10047. struct TagAlias {
  10048. TagAlias(std::string const& _tag, SourceLineInfo _lineInfo);
  10049. std::string tag;
  10050. SourceLineInfo lineInfo;
  10051. };
  10052. } // end namespace Catch
  10053. // end catch_tag_alias.h
  10054. #include <map>
  10055. namespace Catch {
  10056. class TagAliasRegistry : public ITagAliasRegistry {
  10057. public:
  10058. ~TagAliasRegistry() override;
  10059. TagAlias const* find( std::string const& alias ) const override;
  10060. std::string expandAliases( std::string const& unexpandedTestSpec ) const override;
  10061. void add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo );
  10062. private:
  10063. std::map<std::string, TagAlias> m_registry;
  10064. };
  10065. } // end namespace Catch
  10066. // end catch_tag_alias_registry.h
  10067. // start catch_startup_exception_registry.h
  10068. #include <vector>
  10069. #include <exception>
  10070. namespace Catch {
  10071. class StartupExceptionRegistry {
  10072. public:
  10073. void add(std::exception_ptr const& exception) noexcept;
  10074. std::vector<std::exception_ptr> const& getExceptions() const noexcept;
  10075. private:
  10076. std::vector<std::exception_ptr> m_exceptions;
  10077. };
  10078. } // end namespace Catch
  10079. // end catch_startup_exception_registry.h
  10080. // start catch_singletons.hpp
  10081. namespace Catch {
  10082. struct ISingleton {
  10083. virtual ~ISingleton();
  10084. };
  10085. void addSingleton( ISingleton* singleton );
  10086. void cleanupSingletons();
  10087. template<typename SingletonImplT, typename InterfaceT = SingletonImplT, typename MutableInterfaceT = InterfaceT>
  10088. class Singleton : SingletonImplT, public ISingleton {
  10089. static auto getInternal() -> Singleton* {
  10090. static Singleton* s_instance = nullptr;
  10091. if( !s_instance ) {
  10092. s_instance = new Singleton;
  10093. addSingleton( s_instance );
  10094. }
  10095. return s_instance;
  10096. }
  10097. public:
  10098. static auto get() -> InterfaceT const& {
  10099. return *getInternal();
  10100. }
  10101. static auto getMutable() -> MutableInterfaceT& {
  10102. return *getInternal();
  10103. }
  10104. };
  10105. } // namespace Catch
  10106. // end catch_singletons.hpp
  10107. namespace Catch {
  10108. namespace {
  10109. class RegistryHub : public IRegistryHub, public IMutableRegistryHub,
  10110. private NonCopyable {
  10111. public: // IRegistryHub
  10112. RegistryHub() = default;
  10113. IReporterRegistry const& getReporterRegistry() const override {
  10114. return m_reporterRegistry;
  10115. }
  10116. ITestCaseRegistry const& getTestCaseRegistry() const override {
  10117. return m_testCaseRegistry;
  10118. }
  10119. IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const override {
  10120. return m_exceptionTranslatorRegistry;
  10121. }
  10122. ITagAliasRegistry const& getTagAliasRegistry() const override {
  10123. return m_tagAliasRegistry;
  10124. }
  10125. StartupExceptionRegistry const& getStartupExceptionRegistry() const override {
  10126. return m_exceptionRegistry;
  10127. }
  10128. public: // IMutableRegistryHub
  10129. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) override {
  10130. m_reporterRegistry.registerReporter( name, factory );
  10131. }
  10132. void registerListener( IReporterFactoryPtr const& factory ) override {
  10133. m_reporterRegistry.registerListener( factory );
  10134. }
  10135. void registerTest( TestCase const& testInfo ) override {
  10136. m_testCaseRegistry.registerTest( testInfo );
  10137. }
  10138. void registerTranslator( const IExceptionTranslator* translator ) override {
  10139. m_exceptionTranslatorRegistry.registerTranslator( translator );
  10140. }
  10141. void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) override {
  10142. m_tagAliasRegistry.add( alias, tag, lineInfo );
  10143. }
  10144. void registerStartupException() noexcept override {
  10145. m_exceptionRegistry.add(std::current_exception());
  10146. }
  10147. IMutableEnumValuesRegistry& getMutableEnumValuesRegistry() override {
  10148. return m_enumValuesRegistry;
  10149. }
  10150. private:
  10151. TestRegistry m_testCaseRegistry;
  10152. ReporterRegistry m_reporterRegistry;
  10153. ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
  10154. TagAliasRegistry m_tagAliasRegistry;
  10155. StartupExceptionRegistry m_exceptionRegistry;
  10156. Detail::EnumValuesRegistry m_enumValuesRegistry;
  10157. };
  10158. }
  10159. using RegistryHubSingleton = Singleton<RegistryHub, IRegistryHub, IMutableRegistryHub>;
  10160. IRegistryHub const& getRegistryHub() {
  10161. return RegistryHubSingleton::get();
  10162. }
  10163. IMutableRegistryHub& getMutableRegistryHub() {
  10164. return RegistryHubSingleton::getMutable();
  10165. }
  10166. void cleanUp() {
  10167. cleanupSingletons();
  10168. cleanUpContext();
  10169. }
  10170. std::string translateActiveException() {
  10171. return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException();
  10172. }
  10173. } // end namespace Catch
  10174. // end catch_registry_hub.cpp
  10175. // start catch_reporter_registry.cpp
  10176. namespace Catch {
  10177. ReporterRegistry::~ReporterRegistry() = default;
  10178. IStreamingReporterPtr ReporterRegistry::create( std::string const& name, IConfigPtr const& config ) const {
  10179. auto it = m_factories.find( name );
  10180. if( it == m_factories.end() )
  10181. return nullptr;
  10182. return it->second->create( ReporterConfig( config ) );
  10183. }
  10184. void ReporterRegistry::registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) {
  10185. m_factories.emplace(name, factory);
  10186. }
  10187. void ReporterRegistry::registerListener( IReporterFactoryPtr const& factory ) {
  10188. m_listeners.push_back( factory );
  10189. }
  10190. IReporterRegistry::FactoryMap const& ReporterRegistry::getFactories() const {
  10191. return m_factories;
  10192. }
  10193. IReporterRegistry::Listeners const& ReporterRegistry::getListeners() const {
  10194. return m_listeners;
  10195. }
  10196. }
  10197. // end catch_reporter_registry.cpp
  10198. // start catch_result_type.cpp
  10199. namespace Catch {
  10200. bool isOk( ResultWas::OfType resultType ) {
  10201. return ( resultType & ResultWas::FailureBit ) == 0;
  10202. }
  10203. bool isJustInfo( int flags ) {
  10204. return flags == ResultWas::Info;
  10205. }
  10206. ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) {
  10207. return static_cast<ResultDisposition::Flags>( static_cast<int>( lhs ) | static_cast<int>( rhs ) );
  10208. }
  10209. bool shouldContinueOnFailure( int flags ) { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; }
  10210. bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; }
  10211. } // end namespace Catch
  10212. // end catch_result_type.cpp
  10213. // start catch_run_context.cpp
  10214. #include <cassert>
  10215. #include <algorithm>
  10216. #include <sstream>
  10217. namespace Catch {
  10218. namespace Generators {
  10219. struct GeneratorTracker : TestCaseTracking::TrackerBase, IGeneratorTracker {
  10220. GeneratorBasePtr m_generator;
  10221. GeneratorTracker( TestCaseTracking::NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  10222. : TrackerBase( nameAndLocation, ctx, parent )
  10223. {}
  10224. ~GeneratorTracker();
  10225. static GeneratorTracker& acquire( TrackerContext& ctx, TestCaseTracking::NameAndLocation const& nameAndLocation ) {
  10226. std::shared_ptr<GeneratorTracker> tracker;
  10227. ITracker& currentTracker = ctx.currentTracker();
  10228. if( TestCaseTracking::ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  10229. assert( childTracker );
  10230. assert( childTracker->isGeneratorTracker() );
  10231. tracker = std::static_pointer_cast<GeneratorTracker>( childTracker );
  10232. }
  10233. else {
  10234. tracker = std::make_shared<GeneratorTracker>( nameAndLocation, ctx, &currentTracker );
  10235. currentTracker.addChild( tracker );
  10236. }
  10237. if( !ctx.completedCycle() && !tracker->isComplete() ) {
  10238. tracker->open();
  10239. }
  10240. return *tracker;
  10241. }
  10242. // TrackerBase interface
  10243. bool isGeneratorTracker() const override { return true; }
  10244. auto hasGenerator() const -> bool override {
  10245. return !!m_generator;
  10246. }
  10247. void close() override {
  10248. TrackerBase::close();
  10249. // Generator interface only finds out if it has another item on atual move
  10250. if (m_runState == CompletedSuccessfully && m_generator->next()) {
  10251. m_children.clear();
  10252. m_runState = Executing;
  10253. }
  10254. }
  10255. // IGeneratorTracker interface
  10256. auto getGenerator() const -> GeneratorBasePtr const& override {
  10257. return m_generator;
  10258. }
  10259. void setGenerator( GeneratorBasePtr&& generator ) override {
  10260. m_generator = std::move( generator );
  10261. }
  10262. };
  10263. GeneratorTracker::~GeneratorTracker() {}
  10264. }
  10265. RunContext::RunContext(IConfigPtr const& _config, IStreamingReporterPtr&& reporter)
  10266. : m_runInfo(_config->name()),
  10267. m_context(getCurrentMutableContext()),
  10268. m_config(_config),
  10269. m_reporter(std::move(reporter)),
  10270. m_lastAssertionInfo{ StringRef(), SourceLineInfo("",0), StringRef(), ResultDisposition::Normal },
  10271. m_includeSuccessfulResults( m_config->includeSuccessfulResults() || m_reporter->getPreferences().shouldReportAllAssertions )
  10272. {
  10273. m_context.setRunner(this);
  10274. m_context.setConfig(m_config);
  10275. m_context.setResultCapture(this);
  10276. m_reporter->testRunStarting(m_runInfo);
  10277. }
  10278. RunContext::~RunContext() {
  10279. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting()));
  10280. }
  10281. void RunContext::testGroupStarting(std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount) {
  10282. m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount));
  10283. }
  10284. void RunContext::testGroupEnded(std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount) {
  10285. m_reporter->testGroupEnded(TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting()));
  10286. }
  10287. Totals RunContext::runTest(TestCase const& testCase) {
  10288. Totals prevTotals = m_totals;
  10289. std::string redirectedCout;
  10290. std::string redirectedCerr;
  10291. auto const& testInfo = testCase.getTestCaseInfo();
  10292. m_reporter->testCaseStarting(testInfo);
  10293. m_activeTestCase = &testCase;
  10294. ITracker& rootTracker = m_trackerContext.startRun();
  10295. assert(rootTracker.isSectionTracker());
  10296. static_cast<SectionTracker&>(rootTracker).addInitialFilters(m_config->getSectionsToRun());
  10297. do {
  10298. m_trackerContext.startCycle();
  10299. m_testCaseTracker = &SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo));
  10300. runCurrentTest(redirectedCout, redirectedCerr);
  10301. } while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting());
  10302. Totals deltaTotals = m_totals.delta(prevTotals);
  10303. if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) {
  10304. deltaTotals.assertions.failed++;
  10305. deltaTotals.testCases.passed--;
  10306. deltaTotals.testCases.failed++;
  10307. }
  10308. m_totals.testCases += deltaTotals.testCases;
  10309. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  10310. deltaTotals,
  10311. redirectedCout,
  10312. redirectedCerr,
  10313. aborting()));
  10314. m_activeTestCase = nullptr;
  10315. m_testCaseTracker = nullptr;
  10316. return deltaTotals;
  10317. }
  10318. IConfigPtr RunContext::config() const {
  10319. return m_config;
  10320. }
  10321. IStreamingReporter& RunContext::reporter() const {
  10322. return *m_reporter;
  10323. }
  10324. void RunContext::assertionEnded(AssertionResult const & result) {
  10325. if (result.getResultType() == ResultWas::Ok) {
  10326. m_totals.assertions.passed++;
  10327. m_lastAssertionPassed = true;
  10328. } else if (!result.isOk()) {
  10329. m_lastAssertionPassed = false;
  10330. if( m_activeTestCase->getTestCaseInfo().okToFail() )
  10331. m_totals.assertions.failedButOk++;
  10332. else
  10333. m_totals.assertions.failed++;
  10334. }
  10335. else {
  10336. m_lastAssertionPassed = true;
  10337. }
  10338. // We have no use for the return value (whether messages should be cleared), because messages were made scoped
  10339. // and should be let to clear themselves out.
  10340. static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals)));
  10341. if (result.getResultType() != ResultWas::Warning)
  10342. m_messageScopes.clear();
  10343. // Reset working state
  10344. resetAssertionInfo();
  10345. m_lastResult = result;
  10346. }
  10347. void RunContext::resetAssertionInfo() {
  10348. m_lastAssertionInfo.macroName = StringRef();
  10349. m_lastAssertionInfo.capturedExpression = "{Unknown expression after the reported line}"_sr;
  10350. }
  10351. bool RunContext::sectionStarted(SectionInfo const & sectionInfo, Counts & assertions) {
  10352. ITracker& sectionTracker = SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(sectionInfo.name, sectionInfo.lineInfo));
  10353. if (!sectionTracker.isOpen())
  10354. return false;
  10355. m_activeSections.push_back(&sectionTracker);
  10356. m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;
  10357. m_reporter->sectionStarting(sectionInfo);
  10358. assertions = m_totals.assertions;
  10359. return true;
  10360. }
  10361. auto RunContext::acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
  10362. using namespace Generators;
  10363. GeneratorTracker& tracker = GeneratorTracker::acquire( m_trackerContext, TestCaseTracking::NameAndLocation( "generator", lineInfo ) );
  10364. assert( tracker.isOpen() );
  10365. m_lastAssertionInfo.lineInfo = lineInfo;
  10366. return tracker;
  10367. }
  10368. bool RunContext::testForMissingAssertions(Counts& assertions) {
  10369. if (assertions.total() != 0)
  10370. return false;
  10371. if (!m_config->warnAboutMissingAssertions())
  10372. return false;
  10373. if (m_trackerContext.currentTracker().hasChildren())
  10374. return false;
  10375. m_totals.assertions.failed++;
  10376. assertions.failed++;
  10377. return true;
  10378. }
  10379. void RunContext::sectionEnded(SectionEndInfo const & endInfo) {
  10380. Counts assertions = m_totals.assertions - endInfo.prevAssertions;
  10381. bool missingAssertions = testForMissingAssertions(assertions);
  10382. if (!m_activeSections.empty()) {
  10383. m_activeSections.back()->close();
  10384. m_activeSections.pop_back();
  10385. }
  10386. m_reporter->sectionEnded(SectionStats(endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions));
  10387. m_messages.clear();
  10388. m_messageScopes.clear();
  10389. }
  10390. void RunContext::sectionEndedEarly(SectionEndInfo const & endInfo) {
  10391. if (m_unfinishedSections.empty())
  10392. m_activeSections.back()->fail();
  10393. else
  10394. m_activeSections.back()->close();
  10395. m_activeSections.pop_back();
  10396. m_unfinishedSections.push_back(endInfo);
  10397. }
  10398. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  10399. void RunContext::benchmarkPreparing(std::string const& name) {
  10400. m_reporter->benchmarkPreparing(name);
  10401. }
  10402. void RunContext::benchmarkStarting( BenchmarkInfo const& info ) {
  10403. m_reporter->benchmarkStarting( info );
  10404. }
  10405. void RunContext::benchmarkEnded( BenchmarkStats<> const& stats ) {
  10406. m_reporter->benchmarkEnded( stats );
  10407. }
  10408. void RunContext::benchmarkFailed(std::string const & error) {
  10409. m_reporter->benchmarkFailed(error);
  10410. }
  10411. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  10412. void RunContext::pushScopedMessage(MessageInfo const & message) {
  10413. m_messages.push_back(message);
  10414. }
  10415. void RunContext::popScopedMessage(MessageInfo const & message) {
  10416. m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end());
  10417. }
  10418. void RunContext::emplaceUnscopedMessage( MessageBuilder const& builder ) {
  10419. m_messageScopes.emplace_back( builder );
  10420. }
  10421. std::string RunContext::getCurrentTestName() const {
  10422. return m_activeTestCase
  10423. ? m_activeTestCase->getTestCaseInfo().name
  10424. : std::string();
  10425. }
  10426. const AssertionResult * RunContext::getLastResult() const {
  10427. return &(*m_lastResult);
  10428. }
  10429. void RunContext::exceptionEarlyReported() {
  10430. m_shouldReportUnexpected = false;
  10431. }
  10432. void RunContext::handleFatalErrorCondition( StringRef message ) {
  10433. // First notify reporter that bad things happened
  10434. m_reporter->fatalErrorEncountered(message);
  10435. // Don't rebuild the result -- the stringification itself can cause more fatal errors
  10436. // Instead, fake a result data.
  10437. AssertionResultData tempResult( ResultWas::FatalErrorCondition, { false } );
  10438. tempResult.message = message;
  10439. AssertionResult result(m_lastAssertionInfo, tempResult);
  10440. assertionEnded(result);
  10441. handleUnfinishedSections();
  10442. // Recreate section for test case (as we will lose the one that was in scope)
  10443. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  10444. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
  10445. Counts assertions;
  10446. assertions.failed = 1;
  10447. SectionStats testCaseSectionStats(testCaseSection, assertions, 0, false);
  10448. m_reporter->sectionEnded(testCaseSectionStats);
  10449. auto const& testInfo = m_activeTestCase->getTestCaseInfo();
  10450. Totals deltaTotals;
  10451. deltaTotals.testCases.failed = 1;
  10452. deltaTotals.assertions.failed = 1;
  10453. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  10454. deltaTotals,
  10455. std::string(),
  10456. std::string(),
  10457. false));
  10458. m_totals.testCases.failed++;
  10459. testGroupEnded(std::string(), m_totals, 1, 1);
  10460. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, false));
  10461. }
  10462. bool RunContext::lastAssertionPassed() {
  10463. return m_lastAssertionPassed;
  10464. }
  10465. void RunContext::assertionPassed() {
  10466. m_lastAssertionPassed = true;
  10467. ++m_totals.assertions.passed;
  10468. resetAssertionInfo();
  10469. m_messageScopes.clear();
  10470. }
  10471. bool RunContext::aborting() const {
  10472. return m_totals.assertions.failed >= static_cast<std::size_t>(m_config->abortAfter());
  10473. }
  10474. void RunContext::runCurrentTest(std::string & redirectedCout, std::string & redirectedCerr) {
  10475. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  10476. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
  10477. m_reporter->sectionStarting(testCaseSection);
  10478. Counts prevAssertions = m_totals.assertions;
  10479. double duration = 0;
  10480. m_shouldReportUnexpected = true;
  10481. m_lastAssertionInfo = { "TEST_CASE"_sr, testCaseInfo.lineInfo, StringRef(), ResultDisposition::Normal };
  10482. seedRng(*m_config);
  10483. Timer timer;
  10484. CATCH_TRY {
  10485. if (m_reporter->getPreferences().shouldRedirectStdOut) {
  10486. #if !defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
  10487. RedirectedStreams redirectedStreams(redirectedCout, redirectedCerr);
  10488. timer.start();
  10489. invokeActiveTestCase();
  10490. #else
  10491. OutputRedirect r(redirectedCout, redirectedCerr);
  10492. timer.start();
  10493. invokeActiveTestCase();
  10494. #endif
  10495. } else {
  10496. timer.start();
  10497. invokeActiveTestCase();
  10498. }
  10499. duration = timer.getElapsedSeconds();
  10500. } CATCH_CATCH_ANON (TestFailureException&) {
  10501. // This just means the test was aborted due to failure
  10502. } CATCH_CATCH_ALL {
  10503. // Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under REQUIRE assertions
  10504. // are reported without translation at the point of origin.
  10505. if( m_shouldReportUnexpected ) {
  10506. AssertionReaction dummyReaction;
  10507. handleUnexpectedInflightException( m_lastAssertionInfo, translateActiveException(), dummyReaction );
  10508. }
  10509. }
  10510. Counts assertions = m_totals.assertions - prevAssertions;
  10511. bool missingAssertions = testForMissingAssertions(assertions);
  10512. m_testCaseTracker->close();
  10513. handleUnfinishedSections();
  10514. m_messages.clear();
  10515. m_messageScopes.clear();
  10516. SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions);
  10517. m_reporter->sectionEnded(testCaseSectionStats);
  10518. }
  10519. void RunContext::invokeActiveTestCase() {
  10520. FatalConditionHandler fatalConditionHandler; // Handle signals
  10521. m_activeTestCase->invoke();
  10522. fatalConditionHandler.reset();
  10523. }
  10524. void RunContext::handleUnfinishedSections() {
  10525. // If sections ended prematurely due to an exception we stored their
  10526. // infos here so we can tear them down outside the unwind process.
  10527. for (auto it = m_unfinishedSections.rbegin(),
  10528. itEnd = m_unfinishedSections.rend();
  10529. it != itEnd;
  10530. ++it)
  10531. sectionEnded(*it);
  10532. m_unfinishedSections.clear();
  10533. }
  10534. void RunContext::handleExpr(
  10535. AssertionInfo const& info,
  10536. ITransientExpression const& expr,
  10537. AssertionReaction& reaction
  10538. ) {
  10539. m_reporter->assertionStarting( info );
  10540. bool negated = isFalseTest( info.resultDisposition );
  10541. bool result = expr.getResult() != negated;
  10542. if( result ) {
  10543. if (!m_includeSuccessfulResults) {
  10544. assertionPassed();
  10545. }
  10546. else {
  10547. reportExpr(info, ResultWas::Ok, &expr, negated);
  10548. }
  10549. }
  10550. else {
  10551. reportExpr(info, ResultWas::ExpressionFailed, &expr, negated );
  10552. populateReaction( reaction );
  10553. }
  10554. }
  10555. void RunContext::reportExpr(
  10556. AssertionInfo const &info,
  10557. ResultWas::OfType resultType,
  10558. ITransientExpression const *expr,
  10559. bool negated ) {
  10560. m_lastAssertionInfo = info;
  10561. AssertionResultData data( resultType, LazyExpression( negated ) );
  10562. AssertionResult assertionResult{ info, data };
  10563. assertionResult.m_resultData.lazyExpression.m_transientExpression = expr;
  10564. assertionEnded( assertionResult );
  10565. }
  10566. void RunContext::handleMessage(
  10567. AssertionInfo const& info,
  10568. ResultWas::OfType resultType,
  10569. StringRef const& message,
  10570. AssertionReaction& reaction
  10571. ) {
  10572. m_reporter->assertionStarting( info );
  10573. m_lastAssertionInfo = info;
  10574. AssertionResultData data( resultType, LazyExpression( false ) );
  10575. data.message = message;
  10576. AssertionResult assertionResult{ m_lastAssertionInfo, data };
  10577. assertionEnded( assertionResult );
  10578. if( !assertionResult.isOk() )
  10579. populateReaction( reaction );
  10580. }
  10581. void RunContext::handleUnexpectedExceptionNotThrown(
  10582. AssertionInfo const& info,
  10583. AssertionReaction& reaction
  10584. ) {
  10585. handleNonExpr(info, Catch::ResultWas::DidntThrowException, reaction);
  10586. }
  10587. void RunContext::handleUnexpectedInflightException(
  10588. AssertionInfo const& info,
  10589. std::string const& message,
  10590. AssertionReaction& reaction
  10591. ) {
  10592. m_lastAssertionInfo = info;
  10593. AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
  10594. data.message = message;
  10595. AssertionResult assertionResult{ info, data };
  10596. assertionEnded( assertionResult );
  10597. populateReaction( reaction );
  10598. }
  10599. void RunContext::populateReaction( AssertionReaction& reaction ) {
  10600. reaction.shouldDebugBreak = m_config->shouldDebugBreak();
  10601. reaction.shouldThrow = aborting() || (m_lastAssertionInfo.resultDisposition & ResultDisposition::Normal);
  10602. }
  10603. void RunContext::handleIncomplete(
  10604. AssertionInfo const& info
  10605. ) {
  10606. m_lastAssertionInfo = info;
  10607. AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
  10608. data.message = "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE";
  10609. AssertionResult assertionResult{ info, data };
  10610. assertionEnded( assertionResult );
  10611. }
  10612. void RunContext::handleNonExpr(
  10613. AssertionInfo const &info,
  10614. ResultWas::OfType resultType,
  10615. AssertionReaction &reaction
  10616. ) {
  10617. m_lastAssertionInfo = info;
  10618. AssertionResultData data( resultType, LazyExpression( false ) );
  10619. AssertionResult assertionResult{ info, data };
  10620. assertionEnded( assertionResult );
  10621. if( !assertionResult.isOk() )
  10622. populateReaction( reaction );
  10623. }
  10624. IResultCapture& getResultCapture() {
  10625. if (auto* capture = getCurrentContext().getResultCapture())
  10626. return *capture;
  10627. else
  10628. CATCH_INTERNAL_ERROR("No result capture instance");
  10629. }
  10630. }
  10631. // end catch_run_context.cpp
  10632. // start catch_section.cpp
  10633. namespace Catch {
  10634. Section::Section( SectionInfo const& info )
  10635. : m_info( info ),
  10636. m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) )
  10637. {
  10638. m_timer.start();
  10639. }
  10640. Section::~Section() {
  10641. if( m_sectionIncluded ) {
  10642. SectionEndInfo endInfo{ m_info, m_assertions, m_timer.getElapsedSeconds() };
  10643. if( uncaught_exceptions() )
  10644. getResultCapture().sectionEndedEarly( endInfo );
  10645. else
  10646. getResultCapture().sectionEnded( endInfo );
  10647. }
  10648. }
  10649. // This indicates whether the section should be executed or not
  10650. Section::operator bool() const {
  10651. return m_sectionIncluded;
  10652. }
  10653. } // end namespace Catch
  10654. // end catch_section.cpp
  10655. // start catch_section_info.cpp
  10656. namespace Catch {
  10657. SectionInfo::SectionInfo
  10658. ( SourceLineInfo const& _lineInfo,
  10659. std::string const& _name )
  10660. : name( _name ),
  10661. lineInfo( _lineInfo )
  10662. {}
  10663. } // end namespace Catch
  10664. // end catch_section_info.cpp
  10665. // start catch_session.cpp
  10666. // start catch_session.h
  10667. #include <memory>
  10668. namespace Catch {
  10669. class Session : NonCopyable {
  10670. public:
  10671. Session();
  10672. ~Session() override;
  10673. void showHelp() const;
  10674. void libIdentify();
  10675. int applyCommandLine( int argc, char const * const * argv );
  10676. #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)
  10677. int applyCommandLine( int argc, wchar_t const * const * argv );
  10678. #endif
  10679. void useConfigData( ConfigData const& configData );
  10680. template<typename CharT>
  10681. int run(int argc, CharT const * const argv[]) {
  10682. if (m_startupExceptions)
  10683. return 1;
  10684. int returnCode = applyCommandLine(argc, argv);
  10685. if (returnCode == 0)
  10686. returnCode = run();
  10687. return returnCode;
  10688. }
  10689. int run();
  10690. clara::Parser const& cli() const;
  10691. void cli( clara::Parser const& newParser );
  10692. ConfigData& configData();
  10693. Config& config();
  10694. private:
  10695. int runInternal();
  10696. clara::Parser m_cli;
  10697. ConfigData m_configData;
  10698. std::shared_ptr<Config> m_config;
  10699. bool m_startupExceptions = false;
  10700. };
  10701. } // end namespace Catch
  10702. // end catch_session.h
  10703. // start catch_version.h
  10704. #include <iosfwd>
  10705. namespace Catch {
  10706. // Versioning information
  10707. struct Version {
  10708. Version( Version const& ) = delete;
  10709. Version& operator=( Version const& ) = delete;
  10710. Version( unsigned int _majorVersion,
  10711. unsigned int _minorVersion,
  10712. unsigned int _patchNumber,
  10713. char const * const _branchName,
  10714. unsigned int _buildNumber );
  10715. unsigned int const majorVersion;
  10716. unsigned int const minorVersion;
  10717. unsigned int const patchNumber;
  10718. // buildNumber is only used if branchName is not null
  10719. char const * const branchName;
  10720. unsigned int const buildNumber;
  10721. friend std::ostream& operator << ( std::ostream& os, Version const& version );
  10722. };
  10723. Version const& libraryVersion();
  10724. }
  10725. // end catch_version.h
  10726. #include <cstdlib>
  10727. #include <iomanip>
  10728. #include <set>
  10729. #include <iterator>
  10730. namespace Catch {
  10731. namespace {
  10732. const int MaxExitCode = 255;
  10733. IStreamingReporterPtr createReporter(std::string const& reporterName, IConfigPtr const& config) {
  10734. auto reporter = Catch::getRegistryHub().getReporterRegistry().create(reporterName, config);
  10735. CATCH_ENFORCE(reporter, "No reporter registered with name: '" << reporterName << "'");
  10736. return reporter;
  10737. }
  10738. IStreamingReporterPtr makeReporter(std::shared_ptr<Config> const& config) {
  10739. if (Catch::getRegistryHub().getReporterRegistry().getListeners().empty()) {
  10740. return createReporter(config->getReporterName(), config);
  10741. }
  10742. // On older platforms, returning std::unique_ptr<ListeningReporter>
  10743. // when the return type is std::unique_ptr<IStreamingReporter>
  10744. // doesn't compile without a std::move call. However, this causes
  10745. // a warning on newer platforms. Thus, we have to work around
  10746. // it a bit and downcast the pointer manually.
  10747. auto ret = std::unique_ptr<IStreamingReporter>(new ListeningReporter);
  10748. auto& multi = static_cast<ListeningReporter&>(*ret);
  10749. auto const& listeners = Catch::getRegistryHub().getReporterRegistry().getListeners();
  10750. for (auto const& listener : listeners) {
  10751. multi.addListener(listener->create(Catch::ReporterConfig(config)));
  10752. }
  10753. multi.addReporter(createReporter(config->getReporterName(), config));
  10754. return ret;
  10755. }
  10756. class TestGroup {
  10757. public:
  10758. explicit TestGroup(std::shared_ptr<Config> const& config)
  10759. : m_config{config}
  10760. , m_context{config, makeReporter(config)}
  10761. {
  10762. auto const& allTestCases = getAllTestCasesSorted(*m_config);
  10763. m_matches = m_config->testSpec().matchesByFilter(allTestCases, *m_config);
  10764. if (m_matches.empty()) {
  10765. for (auto const& test : allTestCases)
  10766. if (!test.isHidden())
  10767. m_tests.emplace(&test);
  10768. } else {
  10769. for (auto const& match : m_matches)
  10770. m_tests.insert(match.tests.begin(), match.tests.end());
  10771. }
  10772. }
  10773. Totals execute() {
  10774. Totals totals;
  10775. m_context.testGroupStarting(m_config->name(), 1, 1);
  10776. for (auto const& testCase : m_tests) {
  10777. if (!m_context.aborting())
  10778. totals += m_context.runTest(*testCase);
  10779. else
  10780. m_context.reporter().skipTest(*testCase);
  10781. }
  10782. for (auto const& match : m_matches) {
  10783. if (match.tests.empty()) {
  10784. m_context.reporter().noMatchingTestCases(match.name);
  10785. totals.error = -1;
  10786. }
  10787. }
  10788. m_context.testGroupEnded(m_config->name(), totals, 1, 1);
  10789. return totals;
  10790. }
  10791. private:
  10792. using Tests = std::set<TestCase const*>;
  10793. std::shared_ptr<Config> m_config;
  10794. RunContext m_context;
  10795. Tests m_tests;
  10796. TestSpec::Matches m_matches;
  10797. };
  10798. void applyFilenamesAsTags(Catch::IConfig const& config) {
  10799. auto& tests = const_cast<std::vector<TestCase>&>(getAllTestCasesSorted(config));
  10800. for (auto& testCase : tests) {
  10801. auto tags = testCase.tags;
  10802. std::string filename = testCase.lineInfo.file;
  10803. auto lastSlash = filename.find_last_of("\\/");
  10804. if (lastSlash != std::string::npos) {
  10805. filename.erase(0, lastSlash);
  10806. filename[0] = '#';
  10807. }
  10808. auto lastDot = filename.find_last_of('.');
  10809. if (lastDot != std::string::npos) {
  10810. filename.erase(lastDot);
  10811. }
  10812. tags.push_back(std::move(filename));
  10813. setTags(testCase, tags);
  10814. }
  10815. }
  10816. } // anon namespace
  10817. Session::Session() {
  10818. static bool alreadyInstantiated = false;
  10819. if( alreadyInstantiated ) {
  10820. CATCH_TRY { CATCH_INTERNAL_ERROR( "Only one instance of Catch::Session can ever be used" ); }
  10821. CATCH_CATCH_ALL { getMutableRegistryHub().registerStartupException(); }
  10822. }
  10823. // There cannot be exceptions at startup in no-exception mode.
  10824. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  10825. const auto& exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions();
  10826. if ( !exceptions.empty() ) {
  10827. config();
  10828. getCurrentMutableContext().setConfig(m_config);
  10829. m_startupExceptions = true;
  10830. Colour colourGuard( Colour::Red );
  10831. Catch::cerr() << "Errors occurred during startup!" << '\n';
  10832. // iterate over all exceptions and notify user
  10833. for ( const auto& ex_ptr : exceptions ) {
  10834. try {
  10835. std::rethrow_exception(ex_ptr);
  10836. } catch ( std::exception const& ex ) {
  10837. Catch::cerr() << Column( ex.what() ).indent(2) << '\n';
  10838. }
  10839. }
  10840. }
  10841. #endif
  10842. alreadyInstantiated = true;
  10843. m_cli = makeCommandLineParser( m_configData );
  10844. }
  10845. Session::~Session() {
  10846. Catch::cleanUp();
  10847. }
  10848. void Session::showHelp() const {
  10849. Catch::cout()
  10850. << "\nCatch v" << libraryVersion() << "\n"
  10851. << m_cli << std::endl
  10852. << "For more detailed usage please see the project docs\n" << std::endl;
  10853. }
  10854. void Session::libIdentify() {
  10855. Catch::cout()
  10856. << std::left << std::setw(16) << "description: " << "A Catch test executable\n"
  10857. << std::left << std::setw(16) << "category: " << "testframework\n"
  10858. << std::left << std::setw(16) << "framework: " << "Catch Test\n"
  10859. << std::left << std::setw(16) << "version: " << libraryVersion() << std::endl;
  10860. }
  10861. int Session::applyCommandLine( int argc, char const * const * argv ) {
  10862. if( m_startupExceptions )
  10863. return 1;
  10864. auto result = m_cli.parse( clara::Args( argc, argv ) );
  10865. if( !result ) {
  10866. config();
  10867. getCurrentMutableContext().setConfig(m_config);
  10868. Catch::cerr()
  10869. << Colour( Colour::Red )
  10870. << "\nError(s) in input:\n"
  10871. << Column( result.errorMessage() ).indent( 2 )
  10872. << "\n\n";
  10873. Catch::cerr() << "Run with -? for usage\n" << std::endl;
  10874. return MaxExitCode;
  10875. }
  10876. if( m_configData.showHelp )
  10877. showHelp();
  10878. if( m_configData.libIdentify )
  10879. libIdentify();
  10880. m_config.reset();
  10881. return 0;
  10882. }
  10883. #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)
  10884. int Session::applyCommandLine( int argc, wchar_t const * const * argv ) {
  10885. char **utf8Argv = new char *[ argc ];
  10886. for ( int i = 0; i < argc; ++i ) {
  10887. int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, NULL, 0, NULL, NULL );
  10888. utf8Argv[ i ] = new char[ bufSize ];
  10889. WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, NULL, NULL );
  10890. }
  10891. int returnCode = applyCommandLine( argc, utf8Argv );
  10892. for ( int i = 0; i < argc; ++i )
  10893. delete [] utf8Argv[ i ];
  10894. delete [] utf8Argv;
  10895. return returnCode;
  10896. }
  10897. #endif
  10898. void Session::useConfigData( ConfigData const& configData ) {
  10899. m_configData = configData;
  10900. m_config.reset();
  10901. }
  10902. int Session::run() {
  10903. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeStart ) != 0 ) {
  10904. Catch::cout() << "...waiting for enter/ return before starting" << std::endl;
  10905. static_cast<void>(std::getchar());
  10906. }
  10907. int exitCode = runInternal();
  10908. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeExit ) != 0 ) {
  10909. Catch::cout() << "...waiting for enter/ return before exiting, with code: " << exitCode << std::endl;
  10910. static_cast<void>(std::getchar());
  10911. }
  10912. return exitCode;
  10913. }
  10914. clara::Parser const& Session::cli() const {
  10915. return m_cli;
  10916. }
  10917. void Session::cli( clara::Parser const& newParser ) {
  10918. m_cli = newParser;
  10919. }
  10920. ConfigData& Session::configData() {
  10921. return m_configData;
  10922. }
  10923. Config& Session::config() {
  10924. if( !m_config )
  10925. m_config = std::make_shared<Config>( m_configData );
  10926. return *m_config;
  10927. }
  10928. int Session::runInternal() {
  10929. if( m_startupExceptions )
  10930. return 1;
  10931. if (m_configData.showHelp || m_configData.libIdentify) {
  10932. return 0;
  10933. }
  10934. CATCH_TRY {
  10935. config(); // Force config to be constructed
  10936. seedRng( *m_config );
  10937. if( m_configData.filenamesAsTags )
  10938. applyFilenamesAsTags( *m_config );
  10939. // Handle list request
  10940. if( Option<std::size_t> listed = list( m_config ) )
  10941. return static_cast<int>( *listed );
  10942. TestGroup tests { m_config };
  10943. auto const totals = tests.execute();
  10944. if( m_config->warnAboutNoTests() && totals.error == -1 )
  10945. return 2;
  10946. // Note that on unices only the lower 8 bits are usually used, clamping
  10947. // the return value to 255 prevents false negative when some multiple
  10948. // of 256 tests has failed
  10949. return (std::min) (MaxExitCode, (std::max) (totals.error, static_cast<int>(totals.assertions.failed)));
  10950. }
  10951. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  10952. catch( std::exception& ex ) {
  10953. Catch::cerr() << ex.what() << std::endl;
  10954. return MaxExitCode;
  10955. }
  10956. #endif
  10957. }
  10958. } // end namespace Catch
  10959. // end catch_session.cpp
  10960. // start catch_singletons.cpp
  10961. #include <vector>
  10962. namespace Catch {
  10963. namespace {
  10964. static auto getSingletons() -> std::vector<ISingleton*>*& {
  10965. static std::vector<ISingleton*>* g_singletons = nullptr;
  10966. if( !g_singletons )
  10967. g_singletons = new std::vector<ISingleton*>();
  10968. return g_singletons;
  10969. }
  10970. }
  10971. ISingleton::~ISingleton() {}
  10972. void addSingleton(ISingleton* singleton ) {
  10973. getSingletons()->push_back( singleton );
  10974. }
  10975. void cleanupSingletons() {
  10976. auto& singletons = getSingletons();
  10977. for( auto singleton : *singletons )
  10978. delete singleton;
  10979. delete singletons;
  10980. singletons = nullptr;
  10981. }
  10982. } // namespace Catch
  10983. // end catch_singletons.cpp
  10984. // start catch_startup_exception_registry.cpp
  10985. namespace Catch {
  10986. void StartupExceptionRegistry::add( std::exception_ptr const& exception ) noexcept {
  10987. CATCH_TRY {
  10988. m_exceptions.push_back(exception);
  10989. } CATCH_CATCH_ALL {
  10990. // If we run out of memory during start-up there's really not a lot more we can do about it
  10991. std::terminate();
  10992. }
  10993. }
  10994. std::vector<std::exception_ptr> const& StartupExceptionRegistry::getExceptions() const noexcept {
  10995. return m_exceptions;
  10996. }
  10997. } // end namespace Catch
  10998. // end catch_startup_exception_registry.cpp
  10999. // start catch_stream.cpp
  11000. #include <cstdio>
  11001. #include <iostream>
  11002. #include <fstream>
  11003. #include <sstream>
  11004. #include <vector>
  11005. #include <memory>
  11006. namespace Catch {
  11007. Catch::IStream::~IStream() = default;
  11008. namespace Detail { namespace {
  11009. template<typename WriterF, std::size_t bufferSize=256>
  11010. class StreamBufImpl : public std::streambuf {
  11011. char data[bufferSize];
  11012. WriterF m_writer;
  11013. public:
  11014. StreamBufImpl() {
  11015. setp( data, data + sizeof(data) );
  11016. }
  11017. ~StreamBufImpl() noexcept {
  11018. StreamBufImpl::sync();
  11019. }
  11020. private:
  11021. int overflow( int c ) override {
  11022. sync();
  11023. if( c != EOF ) {
  11024. if( pbase() == epptr() )
  11025. m_writer( std::string( 1, static_cast<char>( c ) ) );
  11026. else
  11027. sputc( static_cast<char>( c ) );
  11028. }
  11029. return 0;
  11030. }
  11031. int sync() override {
  11032. if( pbase() != pptr() ) {
  11033. m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) );
  11034. setp( pbase(), epptr() );
  11035. }
  11036. return 0;
  11037. }
  11038. };
  11039. ///////////////////////////////////////////////////////////////////////////
  11040. struct OutputDebugWriter {
  11041. void operator()( std::string const&str ) {
  11042. writeToDebugConsole( str );
  11043. }
  11044. };
  11045. ///////////////////////////////////////////////////////////////////////////
  11046. class FileStream : public IStream {
  11047. mutable std::ofstream m_ofs;
  11048. public:
  11049. FileStream( StringRef filename ) {
  11050. m_ofs.open( filename.c_str() );
  11051. CATCH_ENFORCE( !m_ofs.fail(), "Unable to open file: '" << filename << "'" );
  11052. }
  11053. ~FileStream() override = default;
  11054. public: // IStream
  11055. std::ostream& stream() const override {
  11056. return m_ofs;
  11057. }
  11058. };
  11059. ///////////////////////////////////////////////////////////////////////////
  11060. class CoutStream : public IStream {
  11061. mutable std::ostream m_os;
  11062. public:
  11063. // Store the streambuf from cout up-front because
  11064. // cout may get redirected when running tests
  11065. CoutStream() : m_os( Catch::cout().rdbuf() ) {}
  11066. ~CoutStream() override = default;
  11067. public: // IStream
  11068. std::ostream& stream() const override { return m_os; }
  11069. };
  11070. ///////////////////////////////////////////////////////////////////////////
  11071. class DebugOutStream : public IStream {
  11072. std::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf;
  11073. mutable std::ostream m_os;
  11074. public:
  11075. DebugOutStream()
  11076. : m_streamBuf( new StreamBufImpl<OutputDebugWriter>() ),
  11077. m_os( m_streamBuf.get() )
  11078. {}
  11079. ~DebugOutStream() override = default;
  11080. public: // IStream
  11081. std::ostream& stream() const override { return m_os; }
  11082. };
  11083. }} // namespace anon::detail
  11084. ///////////////////////////////////////////////////////////////////////////
  11085. auto makeStream( StringRef const &filename ) -> IStream const* {
  11086. if( filename.empty() )
  11087. return new Detail::CoutStream();
  11088. else if( filename[0] == '%' ) {
  11089. if( filename == "%debug" )
  11090. return new Detail::DebugOutStream();
  11091. else
  11092. CATCH_ERROR( "Unrecognised stream: '" << filename << "'" );
  11093. }
  11094. else
  11095. return new Detail::FileStream( filename );
  11096. }
  11097. // This class encapsulates the idea of a pool of ostringstreams that can be reused.
  11098. struct StringStreams {
  11099. std::vector<std::unique_ptr<std::ostringstream>> m_streams;
  11100. std::vector<std::size_t> m_unused;
  11101. std::ostringstream m_referenceStream; // Used for copy state/ flags from
  11102. auto add() -> std::size_t {
  11103. if( m_unused.empty() ) {
  11104. m_streams.push_back( std::unique_ptr<std::ostringstream>( new std::ostringstream ) );
  11105. return m_streams.size()-1;
  11106. }
  11107. else {
  11108. auto index = m_unused.back();
  11109. m_unused.pop_back();
  11110. return index;
  11111. }
  11112. }
  11113. void release( std::size_t index ) {
  11114. m_streams[index]->copyfmt( m_referenceStream ); // Restore initial flags and other state
  11115. m_unused.push_back(index);
  11116. }
  11117. };
  11118. ReusableStringStream::ReusableStringStream()
  11119. : m_index( Singleton<StringStreams>::getMutable().add() ),
  11120. m_oss( Singleton<StringStreams>::getMutable().m_streams[m_index].get() )
  11121. {}
  11122. ReusableStringStream::~ReusableStringStream() {
  11123. static_cast<std::ostringstream*>( m_oss )->str("");
  11124. m_oss->clear();
  11125. Singleton<StringStreams>::getMutable().release( m_index );
  11126. }
  11127. auto ReusableStringStream::str() const -> std::string {
  11128. return static_cast<std::ostringstream*>( m_oss )->str();
  11129. }
  11130. ///////////////////////////////////////////////////////////////////////////
  11131. #ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions
  11132. std::ostream& cout() { return std::cout; }
  11133. std::ostream& cerr() { return std::cerr; }
  11134. std::ostream& clog() { return std::clog; }
  11135. #endif
  11136. }
  11137. // end catch_stream.cpp
  11138. // start catch_string_manip.cpp
  11139. #include <algorithm>
  11140. #include <ostream>
  11141. #include <cstring>
  11142. #include <cctype>
  11143. #include <vector>
  11144. namespace Catch {
  11145. namespace {
  11146. char toLowerCh(char c) {
  11147. return static_cast<char>( std::tolower( c ) );
  11148. }
  11149. }
  11150. bool startsWith( std::string const& s, std::string const& prefix ) {
  11151. return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
  11152. }
  11153. bool startsWith( std::string const& s, char prefix ) {
  11154. return !s.empty() && s[0] == prefix;
  11155. }
  11156. bool endsWith( std::string const& s, std::string const& suffix ) {
  11157. return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
  11158. }
  11159. bool endsWith( std::string const& s, char suffix ) {
  11160. return !s.empty() && s[s.size()-1] == suffix;
  11161. }
  11162. bool contains( std::string const& s, std::string const& infix ) {
  11163. return s.find( infix ) != std::string::npos;
  11164. }
  11165. void toLowerInPlace( std::string& s ) {
  11166. std::transform( s.begin(), s.end(), s.begin(), toLowerCh );
  11167. }
  11168. std::string toLower( std::string const& s ) {
  11169. std::string lc = s;
  11170. toLowerInPlace( lc );
  11171. return lc;
  11172. }
  11173. std::string trim( std::string const& str ) {
  11174. static char const* whitespaceChars = "\n\r\t ";
  11175. std::string::size_type start = str.find_first_not_of( whitespaceChars );
  11176. std::string::size_type end = str.find_last_not_of( whitespaceChars );
  11177. return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string();
  11178. }
  11179. bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) {
  11180. bool replaced = false;
  11181. std::size_t i = str.find( replaceThis );
  11182. while( i != std::string::npos ) {
  11183. replaced = true;
  11184. str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() );
  11185. if( i < str.size()-withThis.size() )
  11186. i = str.find( replaceThis, i+withThis.size() );
  11187. else
  11188. i = std::string::npos;
  11189. }
  11190. return replaced;
  11191. }
  11192. std::vector<StringRef> splitStringRef( StringRef str, char delimiter ) {
  11193. std::vector<StringRef> subStrings;
  11194. std::size_t start = 0;
  11195. for(std::size_t pos = 0; pos < str.size(); ++pos ) {
  11196. if( str[pos] == delimiter ) {
  11197. if( pos - start > 1 )
  11198. subStrings.push_back( str.substr( start, pos-start ) );
  11199. start = pos+1;
  11200. }
  11201. }
  11202. if( start < str.size() )
  11203. subStrings.push_back( str.substr( start, str.size()-start ) );
  11204. return subStrings;
  11205. }
  11206. pluralise::pluralise( std::size_t count, std::string const& label )
  11207. : m_count( count ),
  11208. m_label( label )
  11209. {}
  11210. std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) {
  11211. os << pluraliser.m_count << ' ' << pluraliser.m_label;
  11212. if( pluraliser.m_count != 1 )
  11213. os << 's';
  11214. return os;
  11215. }
  11216. }
  11217. // end catch_string_manip.cpp
  11218. // start catch_stringref.cpp
  11219. #if defined(__clang__)
  11220. # pragma clang diagnostic push
  11221. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  11222. #endif
  11223. #include <ostream>
  11224. #include <cstring>
  11225. #include <cstdint>
  11226. namespace {
  11227. const uint32_t byte_2_lead = 0xC0;
  11228. const uint32_t byte_3_lead = 0xE0;
  11229. const uint32_t byte_4_lead = 0xF0;
  11230. }
  11231. namespace Catch {
  11232. StringRef::StringRef( char const* rawChars ) noexcept
  11233. : StringRef( rawChars, static_cast<StringRef::size_type>(std::strlen(rawChars) ) )
  11234. {}
  11235. StringRef::operator std::string() const {
  11236. return std::string( m_start, m_size );
  11237. }
  11238. void StringRef::swap( StringRef& other ) noexcept {
  11239. std::swap( m_start, other.m_start );
  11240. std::swap( m_size, other.m_size );
  11241. std::swap( m_data, other.m_data );
  11242. }
  11243. auto StringRef::c_str() const -> char const* {
  11244. if( !isSubstring() )
  11245. return m_start;
  11246. const_cast<StringRef *>( this )->takeOwnership();
  11247. return m_data;
  11248. }
  11249. auto StringRef::currentData() const noexcept -> char const* {
  11250. return m_start;
  11251. }
  11252. auto StringRef::isOwned() const noexcept -> bool {
  11253. return m_data != nullptr;
  11254. }
  11255. auto StringRef::isSubstring() const noexcept -> bool {
  11256. return m_start[m_size] != '\0';
  11257. }
  11258. void StringRef::takeOwnership() {
  11259. if( !isOwned() ) {
  11260. m_data = new char[m_size+1];
  11261. memcpy( m_data, m_start, m_size );
  11262. m_data[m_size] = '\0';
  11263. }
  11264. }
  11265. auto StringRef::substr( size_type start, size_type size ) const noexcept -> StringRef {
  11266. if( start < m_size )
  11267. return StringRef( m_start+start, size );
  11268. else
  11269. return StringRef();
  11270. }
  11271. auto StringRef::operator == ( StringRef const& other ) const noexcept -> bool {
  11272. return
  11273. size() == other.size() &&
  11274. (std::strncmp( m_start, other.m_start, size() ) == 0);
  11275. }
  11276. auto StringRef::operator != ( StringRef const& other ) const noexcept -> bool {
  11277. return !operator==( other );
  11278. }
  11279. auto StringRef::operator[](size_type index) const noexcept -> char {
  11280. return m_start[index];
  11281. }
  11282. auto StringRef::numberOfCharacters() const noexcept -> size_type {
  11283. size_type noChars = m_size;
  11284. // Make adjustments for uft encodings
  11285. for( size_type i=0; i < m_size; ++i ) {
  11286. char c = m_start[i];
  11287. if( ( c & byte_2_lead ) == byte_2_lead ) {
  11288. noChars--;
  11289. if (( c & byte_3_lead ) == byte_3_lead )
  11290. noChars--;
  11291. if( ( c & byte_4_lead ) == byte_4_lead )
  11292. noChars--;
  11293. }
  11294. }
  11295. return noChars;
  11296. }
  11297. auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string {
  11298. std::string str;
  11299. str.reserve( lhs.size() + rhs.size() );
  11300. str += lhs;
  11301. str += rhs;
  11302. return str;
  11303. }
  11304. auto operator + ( StringRef const& lhs, const char* rhs ) -> std::string {
  11305. return std::string( lhs ) + std::string( rhs );
  11306. }
  11307. auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string {
  11308. return std::string( lhs ) + std::string( rhs );
  11309. }
  11310. auto operator << ( std::ostream& os, StringRef const& str ) -> std::ostream& {
  11311. return os.write(str.currentData(), str.size());
  11312. }
  11313. auto operator+=( std::string& lhs, StringRef const& rhs ) -> std::string& {
  11314. lhs.append(rhs.currentData(), rhs.size());
  11315. return lhs;
  11316. }
  11317. } // namespace Catch
  11318. #if defined(__clang__)
  11319. # pragma clang diagnostic pop
  11320. #endif
  11321. // end catch_stringref.cpp
  11322. // start catch_tag_alias.cpp
  11323. namespace Catch {
  11324. TagAlias::TagAlias(std::string const & _tag, SourceLineInfo _lineInfo): tag(_tag), lineInfo(_lineInfo) {}
  11325. }
  11326. // end catch_tag_alias.cpp
  11327. // start catch_tag_alias_autoregistrar.cpp
  11328. namespace Catch {
  11329. RegistrarForTagAliases::RegistrarForTagAliases(char const* alias, char const* tag, SourceLineInfo const& lineInfo) {
  11330. CATCH_TRY {
  11331. getMutableRegistryHub().registerTagAlias(alias, tag, lineInfo);
  11332. } CATCH_CATCH_ALL {
  11333. // Do not throw when constructing global objects, instead register the exception to be processed later
  11334. getMutableRegistryHub().registerStartupException();
  11335. }
  11336. }
  11337. }
  11338. // end catch_tag_alias_autoregistrar.cpp
  11339. // start catch_tag_alias_registry.cpp
  11340. #include <sstream>
  11341. namespace Catch {
  11342. TagAliasRegistry::~TagAliasRegistry() {}
  11343. TagAlias const* TagAliasRegistry::find( std::string const& alias ) const {
  11344. auto it = m_registry.find( alias );
  11345. if( it != m_registry.end() )
  11346. return &(it->second);
  11347. else
  11348. return nullptr;
  11349. }
  11350. std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const {
  11351. std::string expandedTestSpec = unexpandedTestSpec;
  11352. for( auto const& registryKvp : m_registry ) {
  11353. std::size_t pos = expandedTestSpec.find( registryKvp.first );
  11354. if( pos != std::string::npos ) {
  11355. expandedTestSpec = expandedTestSpec.substr( 0, pos ) +
  11356. registryKvp.second.tag +
  11357. expandedTestSpec.substr( pos + registryKvp.first.size() );
  11358. }
  11359. }
  11360. return expandedTestSpec;
  11361. }
  11362. void TagAliasRegistry::add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) {
  11363. CATCH_ENFORCE( startsWith(alias, "[@") && endsWith(alias, ']'),
  11364. "error: tag alias, '" << alias << "' is not of the form [@alias name].\n" << lineInfo );
  11365. CATCH_ENFORCE( m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second,
  11366. "error: tag alias, '" << alias << "' already registered.\n"
  11367. << "\tFirst seen at: " << find(alias)->lineInfo << "\n"
  11368. << "\tRedefined at: " << lineInfo );
  11369. }
  11370. ITagAliasRegistry::~ITagAliasRegistry() {}
  11371. ITagAliasRegistry const& ITagAliasRegistry::get() {
  11372. return getRegistryHub().getTagAliasRegistry();
  11373. }
  11374. } // end namespace Catch
  11375. // end catch_tag_alias_registry.cpp
  11376. // start catch_test_case_info.cpp
  11377. #include <cctype>
  11378. #include <exception>
  11379. #include <algorithm>
  11380. #include <sstream>
  11381. namespace Catch {
  11382. namespace {
  11383. TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) {
  11384. if( startsWith( tag, '.' ) ||
  11385. tag == "!hide" )
  11386. return TestCaseInfo::IsHidden;
  11387. else if( tag == "!throws" )
  11388. return TestCaseInfo::Throws;
  11389. else if( tag == "!shouldfail" )
  11390. return TestCaseInfo::ShouldFail;
  11391. else if( tag == "!mayfail" )
  11392. return TestCaseInfo::MayFail;
  11393. else if( tag == "!nonportable" )
  11394. return TestCaseInfo::NonPortable;
  11395. else if( tag == "!benchmark" )
  11396. return static_cast<TestCaseInfo::SpecialProperties>( TestCaseInfo::Benchmark | TestCaseInfo::IsHidden );
  11397. else
  11398. return TestCaseInfo::None;
  11399. }
  11400. bool isReservedTag( std::string const& tag ) {
  11401. return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !std::isalnum( static_cast<unsigned char>(tag[0]) );
  11402. }
  11403. void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) {
  11404. CATCH_ENFORCE( !isReservedTag(tag),
  11405. "Tag name: [" << tag << "] is not allowed.\n"
  11406. << "Tag names starting with non alphanumeric characters are reserved\n"
  11407. << _lineInfo );
  11408. }
  11409. }
  11410. TestCase makeTestCase( ITestInvoker* _testCase,
  11411. std::string const& _className,
  11412. NameAndTags const& nameAndTags,
  11413. SourceLineInfo const& _lineInfo )
  11414. {
  11415. bool isHidden = false;
  11416. // Parse out tags
  11417. std::vector<std::string> tags;
  11418. std::string desc, tag;
  11419. bool inTag = false;
  11420. std::string _descOrTags = nameAndTags.tags;
  11421. for (char c : _descOrTags) {
  11422. if( !inTag ) {
  11423. if( c == '[' )
  11424. inTag = true;
  11425. else
  11426. desc += c;
  11427. }
  11428. else {
  11429. if( c == ']' ) {
  11430. TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag );
  11431. if( ( prop & TestCaseInfo::IsHidden ) != 0 )
  11432. isHidden = true;
  11433. else if( prop == TestCaseInfo::None )
  11434. enforceNotReservedTag( tag, _lineInfo );
  11435. // Merged hide tags like `[.approvals]` should be added as
  11436. // `[.][approvals]`. The `[.]` is added at later point, so
  11437. // we only strip the prefix
  11438. if (startsWith(tag, '.') && tag.size() > 1) {
  11439. tag.erase(0, 1);
  11440. }
  11441. tags.push_back( tag );
  11442. tag.clear();
  11443. inTag = false;
  11444. }
  11445. else
  11446. tag += c;
  11447. }
  11448. }
  11449. if( isHidden ) {
  11450. tags.push_back( "." );
  11451. }
  11452. TestCaseInfo info( nameAndTags.name, _className, desc, tags, _lineInfo );
  11453. return TestCase( _testCase, std::move(info) );
  11454. }
  11455. void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags ) {
  11456. std::sort(begin(tags), end(tags));
  11457. tags.erase(std::unique(begin(tags), end(tags)), end(tags));
  11458. testCaseInfo.lcaseTags.clear();
  11459. for( auto const& tag : tags ) {
  11460. std::string lcaseTag = toLower( tag );
  11461. testCaseInfo.properties = static_cast<TestCaseInfo::SpecialProperties>( testCaseInfo.properties | parseSpecialTag( lcaseTag ) );
  11462. testCaseInfo.lcaseTags.push_back( lcaseTag );
  11463. }
  11464. testCaseInfo.tags = std::move(tags);
  11465. }
  11466. TestCaseInfo::TestCaseInfo( std::string const& _name,
  11467. std::string const& _className,
  11468. std::string const& _description,
  11469. std::vector<std::string> const& _tags,
  11470. SourceLineInfo const& _lineInfo )
  11471. : name( _name ),
  11472. className( _className ),
  11473. description( _description ),
  11474. lineInfo( _lineInfo ),
  11475. properties( None )
  11476. {
  11477. setTags( *this, _tags );
  11478. }
  11479. bool TestCaseInfo::isHidden() const {
  11480. return ( properties & IsHidden ) != 0;
  11481. }
  11482. bool TestCaseInfo::throws() const {
  11483. return ( properties & Throws ) != 0;
  11484. }
  11485. bool TestCaseInfo::okToFail() const {
  11486. return ( properties & (ShouldFail | MayFail ) ) != 0;
  11487. }
  11488. bool TestCaseInfo::expectedToFail() const {
  11489. return ( properties & (ShouldFail ) ) != 0;
  11490. }
  11491. std::string TestCaseInfo::tagsAsString() const {
  11492. std::string ret;
  11493. // '[' and ']' per tag
  11494. std::size_t full_size = 2 * tags.size();
  11495. for (const auto& tag : tags) {
  11496. full_size += tag.size();
  11497. }
  11498. ret.reserve(full_size);
  11499. for (const auto& tag : tags) {
  11500. ret.push_back('[');
  11501. ret.append(tag);
  11502. ret.push_back(']');
  11503. }
  11504. return ret;
  11505. }
  11506. TestCase::TestCase( ITestInvoker* testCase, TestCaseInfo&& info ) : TestCaseInfo( std::move(info) ), test( testCase ) {}
  11507. TestCase TestCase::withName( std::string const& _newName ) const {
  11508. TestCase other( *this );
  11509. other.name = _newName;
  11510. return other;
  11511. }
  11512. void TestCase::invoke() const {
  11513. test->invoke();
  11514. }
  11515. bool TestCase::operator == ( TestCase const& other ) const {
  11516. return test.get() == other.test.get() &&
  11517. name == other.name &&
  11518. className == other.className;
  11519. }
  11520. bool TestCase::operator < ( TestCase const& other ) const {
  11521. return name < other.name;
  11522. }
  11523. TestCaseInfo const& TestCase::getTestCaseInfo() const
  11524. {
  11525. return *this;
  11526. }
  11527. } // end namespace Catch
  11528. // end catch_test_case_info.cpp
  11529. // start catch_test_case_registry_impl.cpp
  11530. #include <sstream>
  11531. namespace Catch {
  11532. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases ) {
  11533. std::vector<TestCase> sorted = unsortedTestCases;
  11534. switch( config.runOrder() ) {
  11535. case RunTests::InLexicographicalOrder:
  11536. std::sort( sorted.begin(), sorted.end() );
  11537. break;
  11538. case RunTests::InRandomOrder:
  11539. seedRng( config );
  11540. std::shuffle( sorted.begin(), sorted.end(), rng() );
  11541. break;
  11542. case RunTests::InDeclarationOrder:
  11543. // already in declaration order
  11544. break;
  11545. }
  11546. return sorted;
  11547. }
  11548. bool isThrowSafe( TestCase const& testCase, IConfig const& config ) {
  11549. return !testCase.throws() || config.allowThrows();
  11550. }
  11551. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ) {
  11552. return testSpec.matches( testCase ) && isThrowSafe( testCase, config );
  11553. }
  11554. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions ) {
  11555. std::set<TestCase> seenFunctions;
  11556. for( auto const& function : functions ) {
  11557. auto prev = seenFunctions.insert( function );
  11558. CATCH_ENFORCE( prev.second,
  11559. "error: TEST_CASE( \"" << function.name << "\" ) already defined.\n"
  11560. << "\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo << "\n"
  11561. << "\tRedefined at " << function.getTestCaseInfo().lineInfo );
  11562. }
  11563. }
  11564. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config ) {
  11565. std::vector<TestCase> filtered;
  11566. filtered.reserve( testCases.size() );
  11567. for (auto const& testCase : testCases) {
  11568. if ((!testSpec.hasFilters() && !testCase.isHidden()) ||
  11569. (testSpec.hasFilters() && matchTest(testCase, testSpec, config))) {
  11570. filtered.push_back(testCase);
  11571. }
  11572. }
  11573. return filtered;
  11574. }
  11575. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config ) {
  11576. return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config );
  11577. }
  11578. void TestRegistry::registerTest( TestCase const& testCase ) {
  11579. std::string name = testCase.getTestCaseInfo().name;
  11580. if( name.empty() ) {
  11581. ReusableStringStream rss;
  11582. rss << "Anonymous test case " << ++m_unnamedCount;
  11583. return registerTest( testCase.withName( rss.str() ) );
  11584. }
  11585. m_functions.push_back( testCase );
  11586. }
  11587. std::vector<TestCase> const& TestRegistry::getAllTests() const {
  11588. return m_functions;
  11589. }
  11590. std::vector<TestCase> const& TestRegistry::getAllTestsSorted( IConfig const& config ) const {
  11591. if( m_sortedFunctions.empty() )
  11592. enforceNoDuplicateTestCases( m_functions );
  11593. if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) {
  11594. m_sortedFunctions = sortTests( config, m_functions );
  11595. m_currentSortOrder = config.runOrder();
  11596. }
  11597. return m_sortedFunctions;
  11598. }
  11599. ///////////////////////////////////////////////////////////////////////////
  11600. TestInvokerAsFunction::TestInvokerAsFunction( void(*testAsFunction)() ) noexcept : m_testAsFunction( testAsFunction ) {}
  11601. void TestInvokerAsFunction::invoke() const {
  11602. m_testAsFunction();
  11603. }
  11604. std::string extractClassName( StringRef const& classOrQualifiedMethodName ) {
  11605. std::string className = classOrQualifiedMethodName;
  11606. if( startsWith( className, '&' ) )
  11607. {
  11608. std::size_t lastColons = className.rfind( "::" );
  11609. std::size_t penultimateColons = className.rfind( "::", lastColons-1 );
  11610. if( penultimateColons == std::string::npos )
  11611. penultimateColons = 1;
  11612. className = className.substr( penultimateColons, lastColons-penultimateColons );
  11613. }
  11614. return className;
  11615. }
  11616. } // end namespace Catch
  11617. // end catch_test_case_registry_impl.cpp
  11618. // start catch_test_case_tracker.cpp
  11619. #include <algorithm>
  11620. #include <cassert>
  11621. #include <stdexcept>
  11622. #include <memory>
  11623. #include <sstream>
  11624. #if defined(__clang__)
  11625. # pragma clang diagnostic push
  11626. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  11627. #endif
  11628. namespace Catch {
  11629. namespace TestCaseTracking {
  11630. NameAndLocation::NameAndLocation( std::string const& _name, SourceLineInfo const& _location )
  11631. : name( _name ),
  11632. location( _location )
  11633. {}
  11634. ITracker::~ITracker() = default;
  11635. ITracker& TrackerContext::startRun() {
  11636. m_rootTracker = std::make_shared<SectionTracker>( NameAndLocation( "{root}", CATCH_INTERNAL_LINEINFO ), *this, nullptr );
  11637. m_currentTracker = nullptr;
  11638. m_runState = Executing;
  11639. return *m_rootTracker;
  11640. }
  11641. void TrackerContext::endRun() {
  11642. m_rootTracker.reset();
  11643. m_currentTracker = nullptr;
  11644. m_runState = NotStarted;
  11645. }
  11646. void TrackerContext::startCycle() {
  11647. m_currentTracker = m_rootTracker.get();
  11648. m_runState = Executing;
  11649. }
  11650. void TrackerContext::completeCycle() {
  11651. m_runState = CompletedCycle;
  11652. }
  11653. bool TrackerContext::completedCycle() const {
  11654. return m_runState == CompletedCycle;
  11655. }
  11656. ITracker& TrackerContext::currentTracker() {
  11657. return *m_currentTracker;
  11658. }
  11659. void TrackerContext::setCurrentTracker( ITracker* tracker ) {
  11660. m_currentTracker = tracker;
  11661. }
  11662. TrackerBase::TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  11663. : m_nameAndLocation( nameAndLocation ),
  11664. m_ctx( ctx ),
  11665. m_parent( parent )
  11666. {}
  11667. NameAndLocation const& TrackerBase::nameAndLocation() const {
  11668. return m_nameAndLocation;
  11669. }
  11670. bool TrackerBase::isComplete() const {
  11671. return m_runState == CompletedSuccessfully || m_runState == Failed;
  11672. }
  11673. bool TrackerBase::isSuccessfullyCompleted() const {
  11674. return m_runState == CompletedSuccessfully;
  11675. }
  11676. bool TrackerBase::isOpen() const {
  11677. return m_runState != NotStarted && !isComplete();
  11678. }
  11679. bool TrackerBase::hasChildren() const {
  11680. return !m_children.empty();
  11681. }
  11682. void TrackerBase::addChild( ITrackerPtr const& child ) {
  11683. m_children.push_back( child );
  11684. }
  11685. ITrackerPtr TrackerBase::findChild( NameAndLocation const& nameAndLocation ) {
  11686. auto it = std::find_if( m_children.begin(), m_children.end(),
  11687. [&nameAndLocation]( ITrackerPtr const& tracker ){
  11688. return
  11689. tracker->nameAndLocation().location == nameAndLocation.location &&
  11690. tracker->nameAndLocation().name == nameAndLocation.name;
  11691. } );
  11692. return( it != m_children.end() )
  11693. ? *it
  11694. : nullptr;
  11695. }
  11696. ITracker& TrackerBase::parent() {
  11697. assert( m_parent ); // Should always be non-null except for root
  11698. return *m_parent;
  11699. }
  11700. void TrackerBase::openChild() {
  11701. if( m_runState != ExecutingChildren ) {
  11702. m_runState = ExecutingChildren;
  11703. if( m_parent )
  11704. m_parent->openChild();
  11705. }
  11706. }
  11707. bool TrackerBase::isSectionTracker() const { return false; }
  11708. bool TrackerBase::isGeneratorTracker() const { return false; }
  11709. void TrackerBase::open() {
  11710. m_runState = Executing;
  11711. moveToThis();
  11712. if( m_parent )
  11713. m_parent->openChild();
  11714. }
  11715. void TrackerBase::close() {
  11716. // Close any still open children (e.g. generators)
  11717. while( &m_ctx.currentTracker() != this )
  11718. m_ctx.currentTracker().close();
  11719. switch( m_runState ) {
  11720. case NeedsAnotherRun:
  11721. break;
  11722. case Executing:
  11723. m_runState = CompletedSuccessfully;
  11724. break;
  11725. case ExecutingChildren:
  11726. if( std::all_of(m_children.begin(), m_children.end(), [](ITrackerPtr const& t){ return t->isComplete(); }) )
  11727. m_runState = CompletedSuccessfully;
  11728. break;
  11729. case NotStarted:
  11730. case CompletedSuccessfully:
  11731. case Failed:
  11732. CATCH_INTERNAL_ERROR( "Illogical state: " << m_runState );
  11733. default:
  11734. CATCH_INTERNAL_ERROR( "Unknown state: " << m_runState );
  11735. }
  11736. moveToParent();
  11737. m_ctx.completeCycle();
  11738. }
  11739. void TrackerBase::fail() {
  11740. m_runState = Failed;
  11741. if( m_parent )
  11742. m_parent->markAsNeedingAnotherRun();
  11743. moveToParent();
  11744. m_ctx.completeCycle();
  11745. }
  11746. void TrackerBase::markAsNeedingAnotherRun() {
  11747. m_runState = NeedsAnotherRun;
  11748. }
  11749. void TrackerBase::moveToParent() {
  11750. assert( m_parent );
  11751. m_ctx.setCurrentTracker( m_parent );
  11752. }
  11753. void TrackerBase::moveToThis() {
  11754. m_ctx.setCurrentTracker( this );
  11755. }
  11756. SectionTracker::SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  11757. : TrackerBase( nameAndLocation, ctx, parent )
  11758. {
  11759. if( parent ) {
  11760. while( !parent->isSectionTracker() )
  11761. parent = &parent->parent();
  11762. SectionTracker& parentSection = static_cast<SectionTracker&>( *parent );
  11763. addNextFilters( parentSection.m_filters );
  11764. }
  11765. }
  11766. bool SectionTracker::isComplete() const {
  11767. bool complete = true;
  11768. if ((m_filters.empty() || m_filters[0] == "") ||
  11769. std::find(m_filters.begin(), m_filters.end(),
  11770. m_nameAndLocation.name) != m_filters.end())
  11771. complete = TrackerBase::isComplete();
  11772. return complete;
  11773. }
  11774. bool SectionTracker::isSectionTracker() const { return true; }
  11775. SectionTracker& SectionTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ) {
  11776. std::shared_ptr<SectionTracker> section;
  11777. ITracker& currentTracker = ctx.currentTracker();
  11778. if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  11779. assert( childTracker );
  11780. assert( childTracker->isSectionTracker() );
  11781. section = std::static_pointer_cast<SectionTracker>( childTracker );
  11782. }
  11783. else {
  11784. section = std::make_shared<SectionTracker>( nameAndLocation, ctx, &currentTracker );
  11785. currentTracker.addChild( section );
  11786. }
  11787. if( !ctx.completedCycle() )
  11788. section->tryOpen();
  11789. return *section;
  11790. }
  11791. void SectionTracker::tryOpen() {
  11792. if( !isComplete() && (m_filters.empty() || m_filters[0].empty() || m_filters[0] == m_nameAndLocation.name ) )
  11793. open();
  11794. }
  11795. void SectionTracker::addInitialFilters( std::vector<std::string> const& filters ) {
  11796. if( !filters.empty() ) {
  11797. m_filters.push_back(""); // Root - should never be consulted
  11798. m_filters.push_back(""); // Test Case - not a section filter
  11799. m_filters.insert( m_filters.end(), filters.begin(), filters.end() );
  11800. }
  11801. }
  11802. void SectionTracker::addNextFilters( std::vector<std::string> const& filters ) {
  11803. if( filters.size() > 1 )
  11804. m_filters.insert( m_filters.end(), ++filters.begin(), filters.end() );
  11805. }
  11806. } // namespace TestCaseTracking
  11807. using TestCaseTracking::ITracker;
  11808. using TestCaseTracking::TrackerContext;
  11809. using TestCaseTracking::SectionTracker;
  11810. } // namespace Catch
  11811. #if defined(__clang__)
  11812. # pragma clang diagnostic pop
  11813. #endif
  11814. // end catch_test_case_tracker.cpp
  11815. // start catch_test_registry.cpp
  11816. namespace Catch {
  11817. auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker* {
  11818. return new(std::nothrow) TestInvokerAsFunction( testAsFunction );
  11819. }
  11820. NameAndTags::NameAndTags( StringRef const& name_ , StringRef const& tags_ ) noexcept : name( name_ ), tags( tags_ ) {}
  11821. AutoReg::AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept {
  11822. CATCH_TRY {
  11823. getMutableRegistryHub()
  11824. .registerTest(
  11825. makeTestCase(
  11826. invoker,
  11827. extractClassName( classOrMethod ),
  11828. nameAndTags,
  11829. lineInfo));
  11830. } CATCH_CATCH_ALL {
  11831. // Do not throw when constructing global objects, instead register the exception to be processed later
  11832. getMutableRegistryHub().registerStartupException();
  11833. }
  11834. }
  11835. AutoReg::~AutoReg() = default;
  11836. }
  11837. // end catch_test_registry.cpp
  11838. // start catch_test_spec.cpp
  11839. #include <algorithm>
  11840. #include <string>
  11841. #include <vector>
  11842. #include <memory>
  11843. namespace Catch {
  11844. TestSpec::Pattern::Pattern( std::string const& name )
  11845. : m_name( name )
  11846. {}
  11847. TestSpec::Pattern::~Pattern() = default;
  11848. std::string const& TestSpec::Pattern::name() const {
  11849. return m_name;
  11850. }
  11851. TestSpec::NamePattern::NamePattern( std::string const& name, std::string const& filterString )
  11852. : Pattern( filterString )
  11853. , m_wildcardPattern( toLower( name ), CaseSensitive::No )
  11854. {}
  11855. bool TestSpec::NamePattern::matches( TestCaseInfo const& testCase ) const {
  11856. return m_wildcardPattern.matches( toLower( testCase.name ) );
  11857. }
  11858. TestSpec::TagPattern::TagPattern( std::string const& tag, std::string const& filterString )
  11859. : Pattern( filterString )
  11860. , m_tag( toLower( tag ) )
  11861. {}
  11862. bool TestSpec::TagPattern::matches( TestCaseInfo const& testCase ) const {
  11863. return std::find(begin(testCase.lcaseTags),
  11864. end(testCase.lcaseTags),
  11865. m_tag) != end(testCase.lcaseTags);
  11866. }
  11867. TestSpec::ExcludedPattern::ExcludedPattern( PatternPtr const& underlyingPattern )
  11868. : Pattern( underlyingPattern->name() )
  11869. , m_underlyingPattern( underlyingPattern )
  11870. {}
  11871. bool TestSpec::ExcludedPattern::matches( TestCaseInfo const& testCase ) const {
  11872. return !m_underlyingPattern->matches( testCase );
  11873. }
  11874. bool TestSpec::Filter::matches( TestCaseInfo const& testCase ) const {
  11875. return std::all_of( m_patterns.begin(), m_patterns.end(), [&]( PatternPtr const& p ){ return p->matches( testCase ); } );
  11876. }
  11877. std::string TestSpec::Filter::name() const {
  11878. std::string name;
  11879. for( auto const& p : m_patterns )
  11880. name += p->name();
  11881. return name;
  11882. }
  11883. bool TestSpec::hasFilters() const {
  11884. return !m_filters.empty();
  11885. }
  11886. bool TestSpec::matches( TestCaseInfo const& testCase ) const {
  11887. return std::any_of( m_filters.begin(), m_filters.end(), [&]( Filter const& f ){ return f.matches( testCase ); } );
  11888. }
  11889. TestSpec::Matches TestSpec::matchesByFilter( std::vector<TestCase> const& testCases, IConfig const& config ) const
  11890. {
  11891. Matches matches( m_filters.size() );
  11892. std::transform( m_filters.begin(), m_filters.end(), matches.begin(), [&]( Filter const& filter ){
  11893. std::vector<TestCase const*> currentMatches;
  11894. for( auto const& test : testCases )
  11895. if( isThrowSafe( test, config ) && filter.matches( test ) )
  11896. currentMatches.emplace_back( &test );
  11897. return FilterMatch{ filter.name(), currentMatches };
  11898. } );
  11899. return matches;
  11900. }
  11901. }
  11902. // end catch_test_spec.cpp
  11903. // start catch_test_spec_parser.cpp
  11904. namespace Catch {
  11905. TestSpecParser::TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {}
  11906. TestSpecParser& TestSpecParser::parse( std::string const& arg ) {
  11907. m_mode = None;
  11908. m_exclusion = false;
  11909. m_arg = m_tagAliases->expandAliases( arg );
  11910. m_escapeChars.clear();
  11911. m_substring.reserve(m_arg.size());
  11912. m_patternName.reserve(m_arg.size());
  11913. for( m_pos = 0; m_pos < m_arg.size(); ++m_pos )
  11914. visitChar( m_arg[m_pos] );
  11915. endMode();
  11916. return *this;
  11917. }
  11918. TestSpec TestSpecParser::testSpec() {
  11919. addFilter();
  11920. return m_testSpec;
  11921. }
  11922. void TestSpecParser::visitChar( char c ) {
  11923. if( c == ',' ) {
  11924. endMode();
  11925. addFilter();
  11926. return;
  11927. }
  11928. switch( m_mode ) {
  11929. case None:
  11930. if( processNoneChar( c ) )
  11931. return;
  11932. break;
  11933. case Name:
  11934. processNameChar( c );
  11935. break;
  11936. case EscapedName:
  11937. endMode();
  11938. break;
  11939. default:
  11940. case Tag:
  11941. case QuotedName:
  11942. if( processOtherChar( c ) )
  11943. return;
  11944. break;
  11945. }
  11946. m_substring += c;
  11947. if( !isControlChar( c ) )
  11948. m_patternName += c;
  11949. }
  11950. // Two of the processing methods return true to signal the caller to return
  11951. // without adding the given character to the current pattern strings
  11952. bool TestSpecParser::processNoneChar( char c ) {
  11953. switch( c ) {
  11954. case ' ':
  11955. return true;
  11956. case '~':
  11957. m_exclusion = true;
  11958. return false;
  11959. case '[':
  11960. startNewMode( Tag );
  11961. return false;
  11962. case '"':
  11963. startNewMode( QuotedName );
  11964. return false;
  11965. case '\\':
  11966. escape();
  11967. return true;
  11968. default:
  11969. startNewMode( Name );
  11970. return false;
  11971. }
  11972. }
  11973. void TestSpecParser::processNameChar( char c ) {
  11974. if( c == '[' ) {
  11975. if( m_substring == "exclude:" )
  11976. m_exclusion = true;
  11977. else
  11978. endMode();
  11979. startNewMode( Tag );
  11980. }
  11981. }
  11982. bool TestSpecParser::processOtherChar( char c ) {
  11983. if( !isControlChar( c ) )
  11984. return false;
  11985. m_substring += c;
  11986. endMode();
  11987. return true;
  11988. }
  11989. void TestSpecParser::startNewMode( Mode mode ) {
  11990. m_mode = mode;
  11991. }
  11992. void TestSpecParser::endMode() {
  11993. switch( m_mode ) {
  11994. case Name:
  11995. case QuotedName:
  11996. return addPattern<TestSpec::NamePattern>();
  11997. case Tag:
  11998. return addPattern<TestSpec::TagPattern>();
  11999. case EscapedName:
  12000. return startNewMode( Name );
  12001. case None:
  12002. default:
  12003. return startNewMode( None );
  12004. }
  12005. }
  12006. void TestSpecParser::escape() {
  12007. m_mode = EscapedName;
  12008. m_escapeChars.push_back( m_pos );
  12009. }
  12010. bool TestSpecParser::isControlChar( char c ) const {
  12011. switch( m_mode ) {
  12012. default:
  12013. return false;
  12014. case None:
  12015. return c == '~';
  12016. case Name:
  12017. return c == '[';
  12018. case EscapedName:
  12019. return true;
  12020. case QuotedName:
  12021. return c == '"';
  12022. case Tag:
  12023. return c == '[' || c == ']';
  12024. }
  12025. }
  12026. void TestSpecParser::addFilter() {
  12027. if( !m_currentFilter.m_patterns.empty() ) {
  12028. m_testSpec.m_filters.push_back( m_currentFilter );
  12029. m_currentFilter = TestSpec::Filter();
  12030. }
  12031. }
  12032. TestSpec parseTestSpec( std::string const& arg ) {
  12033. return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec();
  12034. }
  12035. } // namespace Catch
  12036. // end catch_test_spec_parser.cpp
  12037. // start catch_timer.cpp
  12038. #include <chrono>
  12039. static const uint64_t nanosecondsInSecond = 1000000000;
  12040. namespace Catch {
  12041. auto getCurrentNanosecondsSinceEpoch() -> uint64_t {
  12042. return std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::high_resolution_clock::now().time_since_epoch() ).count();
  12043. }
  12044. namespace {
  12045. auto estimateClockResolution() -> uint64_t {
  12046. uint64_t sum = 0;
  12047. static const uint64_t iterations = 1000000;
  12048. auto startTime = getCurrentNanosecondsSinceEpoch();
  12049. for( std::size_t i = 0; i < iterations; ++i ) {
  12050. uint64_t ticks;
  12051. uint64_t baseTicks = getCurrentNanosecondsSinceEpoch();
  12052. do {
  12053. ticks = getCurrentNanosecondsSinceEpoch();
  12054. } while( ticks == baseTicks );
  12055. auto delta = ticks - baseTicks;
  12056. sum += delta;
  12057. // If we have been calibrating for over 3 seconds -- the clock
  12058. // is terrible and we should move on.
  12059. // TBD: How to signal that the measured resolution is probably wrong?
  12060. if (ticks > startTime + 3 * nanosecondsInSecond) {
  12061. return sum / ( i + 1u );
  12062. }
  12063. }
  12064. // We're just taking the mean, here. To do better we could take the std. dev and exclude outliers
  12065. // - and potentially do more iterations if there's a high variance.
  12066. return sum/iterations;
  12067. }
  12068. }
  12069. auto getEstimatedClockResolution() -> uint64_t {
  12070. static auto s_resolution = estimateClockResolution();
  12071. return s_resolution;
  12072. }
  12073. void Timer::start() {
  12074. m_nanoseconds = getCurrentNanosecondsSinceEpoch();
  12075. }
  12076. auto Timer::getElapsedNanoseconds() const -> uint64_t {
  12077. return getCurrentNanosecondsSinceEpoch() - m_nanoseconds;
  12078. }
  12079. auto Timer::getElapsedMicroseconds() const -> uint64_t {
  12080. return getElapsedNanoseconds()/1000;
  12081. }
  12082. auto Timer::getElapsedMilliseconds() const -> unsigned int {
  12083. return static_cast<unsigned int>(getElapsedMicroseconds()/1000);
  12084. }
  12085. auto Timer::getElapsedSeconds() const -> double {
  12086. return getElapsedMicroseconds()/1000000.0;
  12087. }
  12088. } // namespace Catch
  12089. // end catch_timer.cpp
  12090. // start catch_tostring.cpp
  12091. #if defined(__clang__)
  12092. # pragma clang diagnostic push
  12093. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  12094. # pragma clang diagnostic ignored "-Wglobal-constructors"
  12095. #endif
  12096. // Enable specific decls locally
  12097. #if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  12098. #define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  12099. #endif
  12100. #include <cmath>
  12101. #include <iomanip>
  12102. namespace Catch {
  12103. namespace Detail {
  12104. const std::string unprintableString = "{?}";
  12105. namespace {
  12106. const int hexThreshold = 255;
  12107. struct Endianness {
  12108. enum Arch { Big, Little };
  12109. static Arch which() {
  12110. union _{
  12111. int asInt;
  12112. char asChar[sizeof (int)];
  12113. } u;
  12114. u.asInt = 1;
  12115. return ( u.asChar[sizeof(int)-1] == 1 ) ? Big : Little;
  12116. }
  12117. };
  12118. }
  12119. std::string rawMemoryToString( const void *object, std::size_t size ) {
  12120. // Reverse order for little endian architectures
  12121. int i = 0, end = static_cast<int>( size ), inc = 1;
  12122. if( Endianness::which() == Endianness::Little ) {
  12123. i = end-1;
  12124. end = inc = -1;
  12125. }
  12126. unsigned char const *bytes = static_cast<unsigned char const *>(object);
  12127. ReusableStringStream rss;
  12128. rss << "0x" << std::setfill('0') << std::hex;
  12129. for( ; i != end; i += inc )
  12130. rss << std::setw(2) << static_cast<unsigned>(bytes[i]);
  12131. return rss.str();
  12132. }
  12133. }
  12134. template<typename T>
  12135. std::string fpToString( T value, int precision ) {
  12136. if (Catch::isnan(value)) {
  12137. return "nan";
  12138. }
  12139. ReusableStringStream rss;
  12140. rss << std::setprecision( precision )
  12141. << std::fixed
  12142. << value;
  12143. std::string d = rss.str();
  12144. std::size_t i = d.find_last_not_of( '0' );
  12145. if( i != std::string::npos && i != d.size()-1 ) {
  12146. if( d[i] == '.' )
  12147. i++;
  12148. d = d.substr( 0, i+1 );
  12149. }
  12150. return d;
  12151. }
  12152. //// ======================================================= ////
  12153. //
  12154. // Out-of-line defs for full specialization of StringMaker
  12155. //
  12156. //// ======================================================= ////
  12157. std::string StringMaker<std::string>::convert(const std::string& str) {
  12158. if (!getCurrentContext().getConfig()->showInvisibles()) {
  12159. return '"' + str + '"';
  12160. }
  12161. std::string s("\"");
  12162. for (char c : str) {
  12163. switch (c) {
  12164. case '\n':
  12165. s.append("\\n");
  12166. break;
  12167. case '\t':
  12168. s.append("\\t");
  12169. break;
  12170. default:
  12171. s.push_back(c);
  12172. break;
  12173. }
  12174. }
  12175. s.append("\"");
  12176. return s;
  12177. }
  12178. #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  12179. std::string StringMaker<std::string_view>::convert(std::string_view str) {
  12180. return ::Catch::Detail::stringify(std::string{ str });
  12181. }
  12182. #endif
  12183. std::string StringMaker<char const*>::convert(char const* str) {
  12184. if (str) {
  12185. return ::Catch::Detail::stringify(std::string{ str });
  12186. } else {
  12187. return{ "{null string}" };
  12188. }
  12189. }
  12190. std::string StringMaker<char*>::convert(char* str) {
  12191. if (str) {
  12192. return ::Catch::Detail::stringify(std::string{ str });
  12193. } else {
  12194. return{ "{null string}" };
  12195. }
  12196. }
  12197. #ifdef CATCH_CONFIG_WCHAR
  12198. std::string StringMaker<std::wstring>::convert(const std::wstring& wstr) {
  12199. std::string s;
  12200. s.reserve(wstr.size());
  12201. for (auto c : wstr) {
  12202. s += (c <= 0xff) ? static_cast<char>(c) : '?';
  12203. }
  12204. return ::Catch::Detail::stringify(s);
  12205. }
  12206. # ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  12207. std::string StringMaker<std::wstring_view>::convert(std::wstring_view str) {
  12208. return StringMaker<std::wstring>::convert(std::wstring(str));
  12209. }
  12210. # endif
  12211. std::string StringMaker<wchar_t const*>::convert(wchar_t const * str) {
  12212. if (str) {
  12213. return ::Catch::Detail::stringify(std::wstring{ str });
  12214. } else {
  12215. return{ "{null string}" };
  12216. }
  12217. }
  12218. std::string StringMaker<wchar_t *>::convert(wchar_t * str) {
  12219. if (str) {
  12220. return ::Catch::Detail::stringify(std::wstring{ str });
  12221. } else {
  12222. return{ "{null string}" };
  12223. }
  12224. }
  12225. #endif
  12226. #if defined(CATCH_CONFIG_CPP17_BYTE)
  12227. #include <cstddef>
  12228. std::string StringMaker<std::byte>::convert(std::byte value) {
  12229. return ::Catch::Detail::stringify(std::to_integer<unsigned long long>(value));
  12230. }
  12231. #endif // defined(CATCH_CONFIG_CPP17_BYTE)
  12232. std::string StringMaker<int>::convert(int value) {
  12233. return ::Catch::Detail::stringify(static_cast<long long>(value));
  12234. }
  12235. std::string StringMaker<long>::convert(long value) {
  12236. return ::Catch::Detail::stringify(static_cast<long long>(value));
  12237. }
  12238. std::string StringMaker<long long>::convert(long long value) {
  12239. ReusableStringStream rss;
  12240. rss << value;
  12241. if (value > Detail::hexThreshold) {
  12242. rss << " (0x" << std::hex << value << ')';
  12243. }
  12244. return rss.str();
  12245. }
  12246. std::string StringMaker<unsigned int>::convert(unsigned int value) {
  12247. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  12248. }
  12249. std::string StringMaker<unsigned long>::convert(unsigned long value) {
  12250. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  12251. }
  12252. std::string StringMaker<unsigned long long>::convert(unsigned long long value) {
  12253. ReusableStringStream rss;
  12254. rss << value;
  12255. if (value > Detail::hexThreshold) {
  12256. rss << " (0x" << std::hex << value << ')';
  12257. }
  12258. return rss.str();
  12259. }
  12260. std::string StringMaker<bool>::convert(bool b) {
  12261. return b ? "true" : "false";
  12262. }
  12263. std::string StringMaker<signed char>::convert(signed char value) {
  12264. if (value == '\r') {
  12265. return "'\\r'";
  12266. } else if (value == '\f') {
  12267. return "'\\f'";
  12268. } else if (value == '\n') {
  12269. return "'\\n'";
  12270. } else if (value == '\t') {
  12271. return "'\\t'";
  12272. } else if ('\0' <= value && value < ' ') {
  12273. return ::Catch::Detail::stringify(static_cast<unsigned int>(value));
  12274. } else {
  12275. char chstr[] = "' '";
  12276. chstr[1] = value;
  12277. return chstr;
  12278. }
  12279. }
  12280. std::string StringMaker<char>::convert(char c) {
  12281. return ::Catch::Detail::stringify(static_cast<signed char>(c));
  12282. }
  12283. std::string StringMaker<unsigned char>::convert(unsigned char c) {
  12284. return ::Catch::Detail::stringify(static_cast<char>(c));
  12285. }
  12286. std::string StringMaker<std::nullptr_t>::convert(std::nullptr_t) {
  12287. return "nullptr";
  12288. }
  12289. int StringMaker<float>::precision = 5;
  12290. std::string StringMaker<float>::convert(float value) {
  12291. return fpToString(value, precision) + 'f';
  12292. }
  12293. int StringMaker<double>::precision = 10;
  12294. std::string StringMaker<double>::convert(double value) {
  12295. return fpToString(value, precision);
  12296. }
  12297. std::string ratio_string<std::atto>::symbol() { return "a"; }
  12298. std::string ratio_string<std::femto>::symbol() { return "f"; }
  12299. std::string ratio_string<std::pico>::symbol() { return "p"; }
  12300. std::string ratio_string<std::nano>::symbol() { return "n"; }
  12301. std::string ratio_string<std::micro>::symbol() { return "u"; }
  12302. std::string ratio_string<std::milli>::symbol() { return "m"; }
  12303. } // end namespace Catch
  12304. #if defined(__clang__)
  12305. # pragma clang diagnostic pop
  12306. #endif
  12307. // end catch_tostring.cpp
  12308. // start catch_totals.cpp
  12309. namespace Catch {
  12310. Counts Counts::operator - ( Counts const& other ) const {
  12311. Counts diff;
  12312. diff.passed = passed - other.passed;
  12313. diff.failed = failed - other.failed;
  12314. diff.failedButOk = failedButOk - other.failedButOk;
  12315. return diff;
  12316. }
  12317. Counts& Counts::operator += ( Counts const& other ) {
  12318. passed += other.passed;
  12319. failed += other.failed;
  12320. failedButOk += other.failedButOk;
  12321. return *this;
  12322. }
  12323. std::size_t Counts::total() const {
  12324. return passed + failed + failedButOk;
  12325. }
  12326. bool Counts::allPassed() const {
  12327. return failed == 0 && failedButOk == 0;
  12328. }
  12329. bool Counts::allOk() const {
  12330. return failed == 0;
  12331. }
  12332. Totals Totals::operator - ( Totals const& other ) const {
  12333. Totals diff;
  12334. diff.assertions = assertions - other.assertions;
  12335. diff.testCases = testCases - other.testCases;
  12336. return diff;
  12337. }
  12338. Totals& Totals::operator += ( Totals const& other ) {
  12339. assertions += other.assertions;
  12340. testCases += other.testCases;
  12341. return *this;
  12342. }
  12343. Totals Totals::delta( Totals const& prevTotals ) const {
  12344. Totals diff = *this - prevTotals;
  12345. if( diff.assertions.failed > 0 )
  12346. ++diff.testCases.failed;
  12347. else if( diff.assertions.failedButOk > 0 )
  12348. ++diff.testCases.failedButOk;
  12349. else
  12350. ++diff.testCases.passed;
  12351. return diff;
  12352. }
  12353. }
  12354. // end catch_totals.cpp
  12355. // start catch_uncaught_exceptions.cpp
  12356. #include <exception>
  12357. namespace Catch {
  12358. bool uncaught_exceptions() {
  12359. #if defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
  12360. return std::uncaught_exceptions() > 0;
  12361. #else
  12362. return std::uncaught_exception();
  12363. #endif
  12364. }
  12365. } // end namespace Catch
  12366. // end catch_uncaught_exceptions.cpp
  12367. // start catch_version.cpp
  12368. #include <ostream>
  12369. namespace Catch {
  12370. Version::Version
  12371. ( unsigned int _majorVersion,
  12372. unsigned int _minorVersion,
  12373. unsigned int _patchNumber,
  12374. char const * const _branchName,
  12375. unsigned int _buildNumber )
  12376. : majorVersion( _majorVersion ),
  12377. minorVersion( _minorVersion ),
  12378. patchNumber( _patchNumber ),
  12379. branchName( _branchName ),
  12380. buildNumber( _buildNumber )
  12381. {}
  12382. std::ostream& operator << ( std::ostream& os, Version const& version ) {
  12383. os << version.majorVersion << '.'
  12384. << version.minorVersion << '.'
  12385. << version.patchNumber;
  12386. // branchName is never null -> 0th char is \0 if it is empty
  12387. if (version.branchName[0]) {
  12388. os << '-' << version.branchName
  12389. << '.' << version.buildNumber;
  12390. }
  12391. return os;
  12392. }
  12393. Version const& libraryVersion() {
  12394. static Version version( 2, 9, 2, "", 0 );
  12395. return version;
  12396. }
  12397. }
  12398. // end catch_version.cpp
  12399. // start catch_wildcard_pattern.cpp
  12400. #include <sstream>
  12401. namespace Catch {
  12402. WildcardPattern::WildcardPattern( std::string const& pattern,
  12403. CaseSensitive::Choice caseSensitivity )
  12404. : m_caseSensitivity( caseSensitivity ),
  12405. m_pattern( adjustCase( pattern ) )
  12406. {
  12407. if( startsWith( m_pattern, '*' ) ) {
  12408. m_pattern = m_pattern.substr( 1 );
  12409. m_wildcard = WildcardAtStart;
  12410. }
  12411. if( endsWith( m_pattern, '*' ) ) {
  12412. m_pattern = m_pattern.substr( 0, m_pattern.size()-1 );
  12413. m_wildcard = static_cast<WildcardPosition>( m_wildcard | WildcardAtEnd );
  12414. }
  12415. }
  12416. bool WildcardPattern::matches( std::string const& str ) const {
  12417. switch( m_wildcard ) {
  12418. case NoWildcard:
  12419. return m_pattern == adjustCase( str );
  12420. case WildcardAtStart:
  12421. return endsWith( adjustCase( str ), m_pattern );
  12422. case WildcardAtEnd:
  12423. return startsWith( adjustCase( str ), m_pattern );
  12424. case WildcardAtBothEnds:
  12425. return contains( adjustCase( str ), m_pattern );
  12426. default:
  12427. CATCH_INTERNAL_ERROR( "Unknown enum" );
  12428. }
  12429. }
  12430. std::string WildcardPattern::adjustCase( std::string const& str ) const {
  12431. return m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str;
  12432. }
  12433. }
  12434. // end catch_wildcard_pattern.cpp
  12435. // start catch_xmlwriter.cpp
  12436. #include <iomanip>
  12437. using uchar = unsigned char;
  12438. namespace Catch {
  12439. namespace {
  12440. size_t trailingBytes(unsigned char c) {
  12441. if ((c & 0xE0) == 0xC0) {
  12442. return 2;
  12443. }
  12444. if ((c & 0xF0) == 0xE0) {
  12445. return 3;
  12446. }
  12447. if ((c & 0xF8) == 0xF0) {
  12448. return 4;
  12449. }
  12450. CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
  12451. }
  12452. uint32_t headerValue(unsigned char c) {
  12453. if ((c & 0xE0) == 0xC0) {
  12454. return c & 0x1F;
  12455. }
  12456. if ((c & 0xF0) == 0xE0) {
  12457. return c & 0x0F;
  12458. }
  12459. if ((c & 0xF8) == 0xF0) {
  12460. return c & 0x07;
  12461. }
  12462. CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
  12463. }
  12464. void hexEscapeChar(std::ostream& os, unsigned char c) {
  12465. std::ios_base::fmtflags f(os.flags());
  12466. os << "\\x"
  12467. << std::uppercase << std::hex << std::setfill('0') << std::setw(2)
  12468. << static_cast<int>(c);
  12469. os.flags(f);
  12470. }
  12471. } // anonymous namespace
  12472. XmlEncode::XmlEncode( std::string const& str, ForWhat forWhat )
  12473. : m_str( str ),
  12474. m_forWhat( forWhat )
  12475. {}
  12476. void XmlEncode::encodeTo( std::ostream& os ) const {
  12477. // Apostrophe escaping not necessary if we always use " to write attributes
  12478. // (see: http://www.w3.org/TR/xml/#syntax)
  12479. for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) {
  12480. uchar c = m_str[idx];
  12481. switch (c) {
  12482. case '<': os << "&lt;"; break;
  12483. case '&': os << "&amp;"; break;
  12484. case '>':
  12485. // See: http://www.w3.org/TR/xml/#syntax
  12486. if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']')
  12487. os << "&gt;";
  12488. else
  12489. os << c;
  12490. break;
  12491. case '\"':
  12492. if (m_forWhat == ForAttributes)
  12493. os << "&quot;";
  12494. else
  12495. os << c;
  12496. break;
  12497. default:
  12498. // Check for control characters and invalid utf-8
  12499. // Escape control characters in standard ascii
  12500. // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0
  12501. if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) {
  12502. hexEscapeChar(os, c);
  12503. break;
  12504. }
  12505. // Plain ASCII: Write it to stream
  12506. if (c < 0x7F) {
  12507. os << c;
  12508. break;
  12509. }
  12510. // UTF-8 territory
  12511. // Check if the encoding is valid and if it is not, hex escape bytes.
  12512. // Important: We do not check the exact decoded values for validity, only the encoding format
  12513. // First check that this bytes is a valid lead byte:
  12514. // This means that it is not encoded as 1111 1XXX
  12515. // Or as 10XX XXXX
  12516. if (c < 0xC0 ||
  12517. c >= 0xF8) {
  12518. hexEscapeChar(os, c);
  12519. break;
  12520. }
  12521. auto encBytes = trailingBytes(c);
  12522. // Are there enough bytes left to avoid accessing out-of-bounds memory?
  12523. if (idx + encBytes - 1 >= m_str.size()) {
  12524. hexEscapeChar(os, c);
  12525. break;
  12526. }
  12527. // The header is valid, check data
  12528. // The next encBytes bytes must together be a valid utf-8
  12529. // This means: bitpattern 10XX XXXX and the extracted value is sane (ish)
  12530. bool valid = true;
  12531. uint32_t value = headerValue(c);
  12532. for (std::size_t n = 1; n < encBytes; ++n) {
  12533. uchar nc = m_str[idx + n];
  12534. valid &= ((nc & 0xC0) == 0x80);
  12535. value = (value << 6) | (nc & 0x3F);
  12536. }
  12537. if (
  12538. // Wrong bit pattern of following bytes
  12539. (!valid) ||
  12540. // Overlong encodings
  12541. (value < 0x80) ||
  12542. (0x80 <= value && value < 0x800 && encBytes > 2) ||
  12543. (0x800 < value && value < 0x10000 && encBytes > 3) ||
  12544. // Encoded value out of range
  12545. (value >= 0x110000)
  12546. ) {
  12547. hexEscapeChar(os, c);
  12548. break;
  12549. }
  12550. // If we got here, this is in fact a valid(ish) utf-8 sequence
  12551. for (std::size_t n = 0; n < encBytes; ++n) {
  12552. os << m_str[idx + n];
  12553. }
  12554. idx += encBytes - 1;
  12555. break;
  12556. }
  12557. }
  12558. }
  12559. std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) {
  12560. xmlEncode.encodeTo( os );
  12561. return os;
  12562. }
  12563. XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer )
  12564. : m_writer( writer )
  12565. {}
  12566. XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept
  12567. : m_writer( other.m_writer ){
  12568. other.m_writer = nullptr;
  12569. }
  12570. XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) noexcept {
  12571. if ( m_writer ) {
  12572. m_writer->endElement();
  12573. }
  12574. m_writer = other.m_writer;
  12575. other.m_writer = nullptr;
  12576. return *this;
  12577. }
  12578. XmlWriter::ScopedElement::~ScopedElement() {
  12579. if( m_writer )
  12580. m_writer->endElement();
  12581. }
  12582. XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string const& text, bool indent ) {
  12583. m_writer->writeText( text, indent );
  12584. return *this;
  12585. }
  12586. XmlWriter::XmlWriter( std::ostream& os ) : m_os( os )
  12587. {
  12588. writeDeclaration();
  12589. }
  12590. XmlWriter::~XmlWriter() {
  12591. while( !m_tags.empty() )
  12592. endElement();
  12593. }
  12594. XmlWriter& XmlWriter::startElement( std::string const& name ) {
  12595. ensureTagClosed();
  12596. newlineIfNecessary();
  12597. m_os << m_indent << '<' << name;
  12598. m_tags.push_back( name );
  12599. m_indent += " ";
  12600. m_tagIsOpen = true;
  12601. return *this;
  12602. }
  12603. XmlWriter::ScopedElement XmlWriter::scopedElement( std::string const& name ) {
  12604. ScopedElement scoped( this );
  12605. startElement( name );
  12606. return scoped;
  12607. }
  12608. XmlWriter& XmlWriter::endElement() {
  12609. newlineIfNecessary();
  12610. m_indent = m_indent.substr( 0, m_indent.size()-2 );
  12611. if( m_tagIsOpen ) {
  12612. m_os << "/>";
  12613. m_tagIsOpen = false;
  12614. }
  12615. else {
  12616. m_os << m_indent << "</" << m_tags.back() << ">";
  12617. }
  12618. m_os << std::endl;
  12619. m_tags.pop_back();
  12620. return *this;
  12621. }
  12622. XmlWriter& XmlWriter::writeAttribute( std::string const& name, std::string const& attribute ) {
  12623. if( !name.empty() && !attribute.empty() )
  12624. m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"';
  12625. return *this;
  12626. }
  12627. XmlWriter& XmlWriter::writeAttribute( std::string const& name, bool attribute ) {
  12628. m_os << ' ' << name << "=\"" << ( attribute ? "true" : "false" ) << '"';
  12629. return *this;
  12630. }
  12631. XmlWriter& XmlWriter::writeText( std::string const& text, bool indent ) {
  12632. if( !text.empty() ){
  12633. bool tagWasOpen = m_tagIsOpen;
  12634. ensureTagClosed();
  12635. if( tagWasOpen && indent )
  12636. m_os << m_indent;
  12637. m_os << XmlEncode( text );
  12638. m_needsNewline = true;
  12639. }
  12640. return *this;
  12641. }
  12642. XmlWriter& XmlWriter::writeComment( std::string const& text ) {
  12643. ensureTagClosed();
  12644. m_os << m_indent << "<!--" << text << "-->";
  12645. m_needsNewline = true;
  12646. return *this;
  12647. }
  12648. void XmlWriter::writeStylesheetRef( std::string const& url ) {
  12649. m_os << "<?xml-stylesheet type=\"text/xsl\" href=\"" << url << "\"?>\n";
  12650. }
  12651. XmlWriter& XmlWriter::writeBlankLine() {
  12652. ensureTagClosed();
  12653. m_os << '\n';
  12654. return *this;
  12655. }
  12656. void XmlWriter::ensureTagClosed() {
  12657. if( m_tagIsOpen ) {
  12658. m_os << ">" << std::endl;
  12659. m_tagIsOpen = false;
  12660. }
  12661. }
  12662. void XmlWriter::writeDeclaration() {
  12663. m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
  12664. }
  12665. void XmlWriter::newlineIfNecessary() {
  12666. if( m_needsNewline ) {
  12667. m_os << std::endl;
  12668. m_needsNewline = false;
  12669. }
  12670. }
  12671. }
  12672. // end catch_xmlwriter.cpp
  12673. // start catch_reporter_bases.cpp
  12674. #include <cstring>
  12675. #include <cfloat>
  12676. #include <cstdio>
  12677. #include <cassert>
  12678. #include <memory>
  12679. namespace Catch {
  12680. void prepareExpandedExpression(AssertionResult& result) {
  12681. result.getExpandedExpression();
  12682. }
  12683. // Because formatting using c++ streams is stateful, drop down to C is required
  12684. // Alternatively we could use stringstream, but its performance is... not good.
  12685. std::string getFormattedDuration( double duration ) {
  12686. // Max exponent + 1 is required to represent the whole part
  12687. // + 1 for decimal point
  12688. // + 3 for the 3 decimal places
  12689. // + 1 for null terminator
  12690. const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1;
  12691. char buffer[maxDoubleSize];
  12692. // Save previous errno, to prevent sprintf from overwriting it
  12693. ErrnoGuard guard;
  12694. #ifdef _MSC_VER
  12695. sprintf_s(buffer, "%.3f", duration);
  12696. #else
  12697. std::sprintf(buffer, "%.3f", duration);
  12698. #endif
  12699. return std::string(buffer);
  12700. }
  12701. std::string serializeFilters( std::vector<std::string> const& container ) {
  12702. ReusableStringStream oss;
  12703. bool first = true;
  12704. for (auto&& filter : container)
  12705. {
  12706. if (!first)
  12707. oss << ' ';
  12708. else
  12709. first = false;
  12710. oss << filter;
  12711. }
  12712. return oss.str();
  12713. }
  12714. TestEventListenerBase::TestEventListenerBase(ReporterConfig const & _config)
  12715. :StreamingReporterBase(_config) {}
  12716. std::set<Verbosity> TestEventListenerBase::getSupportedVerbosities() {
  12717. return { Verbosity::Quiet, Verbosity::Normal, Verbosity::High };
  12718. }
  12719. void TestEventListenerBase::assertionStarting(AssertionInfo const &) {}
  12720. bool TestEventListenerBase::assertionEnded(AssertionStats const &) {
  12721. return false;
  12722. }
  12723. } // end namespace Catch
  12724. // end catch_reporter_bases.cpp
  12725. // start catch_reporter_compact.cpp
  12726. namespace {
  12727. #ifdef CATCH_PLATFORM_MAC
  12728. const char* failedString() { return "FAILED"; }
  12729. const char* passedString() { return "PASSED"; }
  12730. #else
  12731. const char* failedString() { return "failed"; }
  12732. const char* passedString() { return "passed"; }
  12733. #endif
  12734. // Colour::LightGrey
  12735. Catch::Colour::Code dimColour() { return Catch::Colour::FileName; }
  12736. std::string bothOrAll( std::size_t count ) {
  12737. return count == 1 ? std::string() :
  12738. count == 2 ? "both " : "all " ;
  12739. }
  12740. } // anon namespace
  12741. namespace Catch {
  12742. namespace {
  12743. // Colour, message variants:
  12744. // - white: No tests ran.
  12745. // - red: Failed [both/all] N test cases, failed [both/all] M assertions.
  12746. // - white: Passed [both/all] N test cases (no assertions).
  12747. // - red: Failed N tests cases, failed M assertions.
  12748. // - green: Passed [both/all] N tests cases with M assertions.
  12749. void printTotals(std::ostream& out, const Totals& totals) {
  12750. if (totals.testCases.total() == 0) {
  12751. out << "No tests ran.";
  12752. } else if (totals.testCases.failed == totals.testCases.total()) {
  12753. Colour colour(Colour::ResultError);
  12754. const std::string qualify_assertions_failed =
  12755. totals.assertions.failed == totals.assertions.total() ?
  12756. bothOrAll(totals.assertions.failed) : std::string();
  12757. out <<
  12758. "Failed " << bothOrAll(totals.testCases.failed)
  12759. << pluralise(totals.testCases.failed, "test case") << ", "
  12760. "failed " << qualify_assertions_failed <<
  12761. pluralise(totals.assertions.failed, "assertion") << '.';
  12762. } else if (totals.assertions.total() == 0) {
  12763. out <<
  12764. "Passed " << bothOrAll(totals.testCases.total())
  12765. << pluralise(totals.testCases.total(), "test case")
  12766. << " (no assertions).";
  12767. } else if (totals.assertions.failed) {
  12768. Colour colour(Colour::ResultError);
  12769. out <<
  12770. "Failed " << pluralise(totals.testCases.failed, "test case") << ", "
  12771. "failed " << pluralise(totals.assertions.failed, "assertion") << '.';
  12772. } else {
  12773. Colour colour(Colour::ResultSuccess);
  12774. out <<
  12775. "Passed " << bothOrAll(totals.testCases.passed)
  12776. << pluralise(totals.testCases.passed, "test case") <<
  12777. " with " << pluralise(totals.assertions.passed, "assertion") << '.';
  12778. }
  12779. }
  12780. // Implementation of CompactReporter formatting
  12781. class AssertionPrinter {
  12782. public:
  12783. AssertionPrinter& operator= (AssertionPrinter const&) = delete;
  12784. AssertionPrinter(AssertionPrinter const&) = delete;
  12785. AssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
  12786. : stream(_stream)
  12787. , result(_stats.assertionResult)
  12788. , messages(_stats.infoMessages)
  12789. , itMessage(_stats.infoMessages.begin())
  12790. , printInfoMessages(_printInfoMessages) {}
  12791. void print() {
  12792. printSourceInfo();
  12793. itMessage = messages.begin();
  12794. switch (result.getResultType()) {
  12795. case ResultWas::Ok:
  12796. printResultType(Colour::ResultSuccess, passedString());
  12797. printOriginalExpression();
  12798. printReconstructedExpression();
  12799. if (!result.hasExpression())
  12800. printRemainingMessages(Colour::None);
  12801. else
  12802. printRemainingMessages();
  12803. break;
  12804. case ResultWas::ExpressionFailed:
  12805. if (result.isOk())
  12806. printResultType(Colour::ResultSuccess, failedString() + std::string(" - but was ok"));
  12807. else
  12808. printResultType(Colour::Error, failedString());
  12809. printOriginalExpression();
  12810. printReconstructedExpression();
  12811. printRemainingMessages();
  12812. break;
  12813. case ResultWas::ThrewException:
  12814. printResultType(Colour::Error, failedString());
  12815. printIssue("unexpected exception with message:");
  12816. printMessage();
  12817. printExpressionWas();
  12818. printRemainingMessages();
  12819. break;
  12820. case ResultWas::FatalErrorCondition:
  12821. printResultType(Colour::Error, failedString());
  12822. printIssue("fatal error condition with message:");
  12823. printMessage();
  12824. printExpressionWas();
  12825. printRemainingMessages();
  12826. break;
  12827. case ResultWas::DidntThrowException:
  12828. printResultType(Colour::Error, failedString());
  12829. printIssue("expected exception, got none");
  12830. printExpressionWas();
  12831. printRemainingMessages();
  12832. break;
  12833. case ResultWas::Info:
  12834. printResultType(Colour::None, "info");
  12835. printMessage();
  12836. printRemainingMessages();
  12837. break;
  12838. case ResultWas::Warning:
  12839. printResultType(Colour::None, "warning");
  12840. printMessage();
  12841. printRemainingMessages();
  12842. break;
  12843. case ResultWas::ExplicitFailure:
  12844. printResultType(Colour::Error, failedString());
  12845. printIssue("explicitly");
  12846. printRemainingMessages(Colour::None);
  12847. break;
  12848. // These cases are here to prevent compiler warnings
  12849. case ResultWas::Unknown:
  12850. case ResultWas::FailureBit:
  12851. case ResultWas::Exception:
  12852. printResultType(Colour::Error, "** internal error **");
  12853. break;
  12854. }
  12855. }
  12856. private:
  12857. void printSourceInfo() const {
  12858. Colour colourGuard(Colour::FileName);
  12859. stream << result.getSourceInfo() << ':';
  12860. }
  12861. void printResultType(Colour::Code colour, std::string const& passOrFail) const {
  12862. if (!passOrFail.empty()) {
  12863. {
  12864. Colour colourGuard(colour);
  12865. stream << ' ' << passOrFail;
  12866. }
  12867. stream << ':';
  12868. }
  12869. }
  12870. void printIssue(std::string const& issue) const {
  12871. stream << ' ' << issue;
  12872. }
  12873. void printExpressionWas() {
  12874. if (result.hasExpression()) {
  12875. stream << ';';
  12876. {
  12877. Colour colour(dimColour());
  12878. stream << " expression was:";
  12879. }
  12880. printOriginalExpression();
  12881. }
  12882. }
  12883. void printOriginalExpression() const {
  12884. if (result.hasExpression()) {
  12885. stream << ' ' << result.getExpression();
  12886. }
  12887. }
  12888. void printReconstructedExpression() const {
  12889. if (result.hasExpandedExpression()) {
  12890. {
  12891. Colour colour(dimColour());
  12892. stream << " for: ";
  12893. }
  12894. stream << result.getExpandedExpression();
  12895. }
  12896. }
  12897. void printMessage() {
  12898. if (itMessage != messages.end()) {
  12899. stream << " '" << itMessage->message << '\'';
  12900. ++itMessage;
  12901. }
  12902. }
  12903. void printRemainingMessages(Colour::Code colour = dimColour()) {
  12904. if (itMessage == messages.end())
  12905. return;
  12906. const auto itEnd = messages.cend();
  12907. const auto N = static_cast<std::size_t>(std::distance(itMessage, itEnd));
  12908. {
  12909. Colour colourGuard(colour);
  12910. stream << " with " << pluralise(N, "message") << ':';
  12911. }
  12912. while (itMessage != itEnd) {
  12913. // If this assertion is a warning ignore any INFO messages
  12914. if (printInfoMessages || itMessage->type != ResultWas::Info) {
  12915. printMessage();
  12916. if (itMessage != itEnd) {
  12917. Colour colourGuard(dimColour());
  12918. stream << " and";
  12919. }
  12920. continue;
  12921. }
  12922. ++itMessage;
  12923. }
  12924. }
  12925. private:
  12926. std::ostream& stream;
  12927. AssertionResult const& result;
  12928. std::vector<MessageInfo> messages;
  12929. std::vector<MessageInfo>::const_iterator itMessage;
  12930. bool printInfoMessages;
  12931. };
  12932. } // anon namespace
  12933. std::string CompactReporter::getDescription() {
  12934. return "Reports test results on a single line, suitable for IDEs";
  12935. }
  12936. ReporterPreferences CompactReporter::getPreferences() const {
  12937. return m_reporterPrefs;
  12938. }
  12939. void CompactReporter::noMatchingTestCases( std::string const& spec ) {
  12940. stream << "No test cases matched '" << spec << '\'' << std::endl;
  12941. }
  12942. void CompactReporter::assertionStarting( AssertionInfo const& ) {}
  12943. bool CompactReporter::assertionEnded( AssertionStats const& _assertionStats ) {
  12944. AssertionResult const& result = _assertionStats.assertionResult;
  12945. bool printInfoMessages = true;
  12946. // Drop out if result was successful and we're not printing those
  12947. if( !m_config->includeSuccessfulResults() && result.isOk() ) {
  12948. if( result.getResultType() != ResultWas::Warning )
  12949. return false;
  12950. printInfoMessages = false;
  12951. }
  12952. AssertionPrinter printer( stream, _assertionStats, printInfoMessages );
  12953. printer.print();
  12954. stream << std::endl;
  12955. return true;
  12956. }
  12957. void CompactReporter::sectionEnded(SectionStats const& _sectionStats) {
  12958. if (m_config->showDurations() == ShowDurations::Always) {
  12959. stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  12960. }
  12961. }
  12962. void CompactReporter::testRunEnded( TestRunStats const& _testRunStats ) {
  12963. printTotals( stream, _testRunStats.totals );
  12964. stream << '\n' << std::endl;
  12965. StreamingReporterBase::testRunEnded( _testRunStats );
  12966. }
  12967. CompactReporter::~CompactReporter() {}
  12968. CATCH_REGISTER_REPORTER( "compact", CompactReporter )
  12969. } // end namespace Catch
  12970. // end catch_reporter_compact.cpp
  12971. // start catch_reporter_console.cpp
  12972. #include <cfloat>
  12973. #include <cstdio>
  12974. #if defined(_MSC_VER)
  12975. #pragma warning(push)
  12976. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  12977. // Note that 4062 (not all labels are handled and default is missing) is enabled
  12978. #endif
  12979. #if defined(__clang__)
  12980. # pragma clang diagnostic push
  12981. // For simplicity, benchmarking-only helpers are always enabled
  12982. # pragma clang diagnostic ignored "-Wunused-function"
  12983. #endif
  12984. namespace Catch {
  12985. namespace {
  12986. // Formatter impl for ConsoleReporter
  12987. class ConsoleAssertionPrinter {
  12988. public:
  12989. ConsoleAssertionPrinter& operator= (ConsoleAssertionPrinter const&) = delete;
  12990. ConsoleAssertionPrinter(ConsoleAssertionPrinter const&) = delete;
  12991. ConsoleAssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
  12992. : stream(_stream),
  12993. stats(_stats),
  12994. result(_stats.assertionResult),
  12995. colour(Colour::None),
  12996. message(result.getMessage()),
  12997. messages(_stats.infoMessages),
  12998. printInfoMessages(_printInfoMessages) {
  12999. switch (result.getResultType()) {
  13000. case ResultWas::Ok:
  13001. colour = Colour::Success;
  13002. passOrFail = "PASSED";
  13003. //if( result.hasMessage() )
  13004. if (_stats.infoMessages.size() == 1)
  13005. messageLabel = "with message";
  13006. if (_stats.infoMessages.size() > 1)
  13007. messageLabel = "with messages";
  13008. break;
  13009. case ResultWas::ExpressionFailed:
  13010. if (result.isOk()) {
  13011. colour = Colour::Success;
  13012. passOrFail = "FAILED - but was ok";
  13013. } else {
  13014. colour = Colour::Error;
  13015. passOrFail = "FAILED";
  13016. }
  13017. if (_stats.infoMessages.size() == 1)
  13018. messageLabel = "with message";
  13019. if (_stats.infoMessages.size() > 1)
  13020. messageLabel = "with messages";
  13021. break;
  13022. case ResultWas::ThrewException:
  13023. colour = Colour::Error;
  13024. passOrFail = "FAILED";
  13025. messageLabel = "due to unexpected exception with ";
  13026. if (_stats.infoMessages.size() == 1)
  13027. messageLabel += "message";
  13028. if (_stats.infoMessages.size() > 1)
  13029. messageLabel += "messages";
  13030. break;
  13031. case ResultWas::FatalErrorCondition:
  13032. colour = Colour::Error;
  13033. passOrFail = "FAILED";
  13034. messageLabel = "due to a fatal error condition";
  13035. break;
  13036. case ResultWas::DidntThrowException:
  13037. colour = Colour::Error;
  13038. passOrFail = "FAILED";
  13039. messageLabel = "because no exception was thrown where one was expected";
  13040. break;
  13041. case ResultWas::Info:
  13042. messageLabel = "info";
  13043. break;
  13044. case ResultWas::Warning:
  13045. messageLabel = "warning";
  13046. break;
  13047. case ResultWas::ExplicitFailure:
  13048. passOrFail = "FAILED";
  13049. colour = Colour::Error;
  13050. if (_stats.infoMessages.size() == 1)
  13051. messageLabel = "explicitly with message";
  13052. if (_stats.infoMessages.size() > 1)
  13053. messageLabel = "explicitly with messages";
  13054. break;
  13055. // These cases are here to prevent compiler warnings
  13056. case ResultWas::Unknown:
  13057. case ResultWas::FailureBit:
  13058. case ResultWas::Exception:
  13059. passOrFail = "** internal error **";
  13060. colour = Colour::Error;
  13061. break;
  13062. }
  13063. }
  13064. void print() const {
  13065. printSourceInfo();
  13066. if (stats.totals.assertions.total() > 0) {
  13067. printResultType();
  13068. printOriginalExpression();
  13069. printReconstructedExpression();
  13070. } else {
  13071. stream << '\n';
  13072. }
  13073. printMessage();
  13074. }
  13075. private:
  13076. void printResultType() const {
  13077. if (!passOrFail.empty()) {
  13078. Colour colourGuard(colour);
  13079. stream << passOrFail << ":\n";
  13080. }
  13081. }
  13082. void printOriginalExpression() const {
  13083. if (result.hasExpression()) {
  13084. Colour colourGuard(Colour::OriginalExpression);
  13085. stream << " ";
  13086. stream << result.getExpressionInMacro();
  13087. stream << '\n';
  13088. }
  13089. }
  13090. void printReconstructedExpression() const {
  13091. if (result.hasExpandedExpression()) {
  13092. stream << "with expansion:\n";
  13093. Colour colourGuard(Colour::ReconstructedExpression);
  13094. stream << Column(result.getExpandedExpression()).indent(2) << '\n';
  13095. }
  13096. }
  13097. void printMessage() const {
  13098. if (!messageLabel.empty())
  13099. stream << messageLabel << ':' << '\n';
  13100. for (auto const& msg : messages) {
  13101. // If this assertion is a warning ignore any INFO messages
  13102. if (printInfoMessages || msg.type != ResultWas::Info)
  13103. stream << Column(msg.message).indent(2) << '\n';
  13104. }
  13105. }
  13106. void printSourceInfo() const {
  13107. Colour colourGuard(Colour::FileName);
  13108. stream << result.getSourceInfo() << ": ";
  13109. }
  13110. std::ostream& stream;
  13111. AssertionStats const& stats;
  13112. AssertionResult const& result;
  13113. Colour::Code colour;
  13114. std::string passOrFail;
  13115. std::string messageLabel;
  13116. std::string message;
  13117. std::vector<MessageInfo> messages;
  13118. bool printInfoMessages;
  13119. };
  13120. std::size_t makeRatio(std::size_t number, std::size_t total) {
  13121. std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0;
  13122. return (ratio == 0 && number > 0) ? 1 : ratio;
  13123. }
  13124. std::size_t& findMax(std::size_t& i, std::size_t& j, std::size_t& k) {
  13125. if (i > j && i > k)
  13126. return i;
  13127. else if (j > k)
  13128. return j;
  13129. else
  13130. return k;
  13131. }
  13132. struct ColumnInfo {
  13133. enum Justification { Left, Right };
  13134. std::string name;
  13135. int width;
  13136. Justification justification;
  13137. };
  13138. struct ColumnBreak {};
  13139. struct RowBreak {};
  13140. class Duration {
  13141. enum class Unit {
  13142. Auto,
  13143. Nanoseconds,
  13144. Microseconds,
  13145. Milliseconds,
  13146. Seconds,
  13147. Minutes
  13148. };
  13149. static const uint64_t s_nanosecondsInAMicrosecond = 1000;
  13150. static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond;
  13151. static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond;
  13152. static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond;
  13153. uint64_t m_inNanoseconds;
  13154. Unit m_units;
  13155. public:
  13156. explicit Duration(double inNanoseconds, Unit units = Unit::Auto)
  13157. : Duration(static_cast<uint64_t>(inNanoseconds), units) {
  13158. }
  13159. explicit Duration(uint64_t inNanoseconds, Unit units = Unit::Auto)
  13160. : m_inNanoseconds(inNanoseconds),
  13161. m_units(units) {
  13162. if (m_units == Unit::Auto) {
  13163. if (m_inNanoseconds < s_nanosecondsInAMicrosecond)
  13164. m_units = Unit::Nanoseconds;
  13165. else if (m_inNanoseconds < s_nanosecondsInAMillisecond)
  13166. m_units = Unit::Microseconds;
  13167. else if (m_inNanoseconds < s_nanosecondsInASecond)
  13168. m_units = Unit::Milliseconds;
  13169. else if (m_inNanoseconds < s_nanosecondsInAMinute)
  13170. m_units = Unit::Seconds;
  13171. else
  13172. m_units = Unit::Minutes;
  13173. }
  13174. }
  13175. auto value() const -> double {
  13176. switch (m_units) {
  13177. case Unit::Microseconds:
  13178. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMicrosecond);
  13179. case Unit::Milliseconds:
  13180. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMillisecond);
  13181. case Unit::Seconds:
  13182. return m_inNanoseconds / static_cast<double>(s_nanosecondsInASecond);
  13183. case Unit::Minutes:
  13184. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMinute);
  13185. default:
  13186. return static_cast<double>(m_inNanoseconds);
  13187. }
  13188. }
  13189. auto unitsAsString() const -> std::string {
  13190. switch (m_units) {
  13191. case Unit::Nanoseconds:
  13192. return "ns";
  13193. case Unit::Microseconds:
  13194. return "us";
  13195. case Unit::Milliseconds:
  13196. return "ms";
  13197. case Unit::Seconds:
  13198. return "s";
  13199. case Unit::Minutes:
  13200. return "m";
  13201. default:
  13202. return "** internal error **";
  13203. }
  13204. }
  13205. friend auto operator << (std::ostream& os, Duration const& duration) -> std::ostream& {
  13206. return os << duration.value() << " " << duration.unitsAsString();
  13207. }
  13208. };
  13209. } // end anon namespace
  13210. class TablePrinter {
  13211. std::ostream& m_os;
  13212. std::vector<ColumnInfo> m_columnInfos;
  13213. std::ostringstream m_oss;
  13214. int m_currentColumn = -1;
  13215. bool m_isOpen = false;
  13216. public:
  13217. TablePrinter( std::ostream& os, std::vector<ColumnInfo> columnInfos )
  13218. : m_os( os ),
  13219. m_columnInfos( std::move( columnInfos ) ) {}
  13220. auto columnInfos() const -> std::vector<ColumnInfo> const& {
  13221. return m_columnInfos;
  13222. }
  13223. void open() {
  13224. if (!m_isOpen) {
  13225. m_isOpen = true;
  13226. *this << RowBreak();
  13227. Columns headerCols;
  13228. Spacer spacer(2);
  13229. for (auto const& info : m_columnInfos) {
  13230. headerCols += Column(info.name).width(static_cast<std::size_t>(info.width - 2));
  13231. headerCols += spacer;
  13232. }
  13233. m_os << headerCols << "\n";
  13234. m_os << Catch::getLineOfChars<'-'>() << "\n";
  13235. }
  13236. }
  13237. void close() {
  13238. if (m_isOpen) {
  13239. *this << RowBreak();
  13240. m_os << std::endl;
  13241. m_isOpen = false;
  13242. }
  13243. }
  13244. template<typename T>
  13245. friend TablePrinter& operator << (TablePrinter& tp, T const& value) {
  13246. tp.m_oss << value;
  13247. return tp;
  13248. }
  13249. friend TablePrinter& operator << (TablePrinter& tp, ColumnBreak) {
  13250. auto colStr = tp.m_oss.str();
  13251. // This takes account of utf8 encodings
  13252. auto strSize = Catch::StringRef(colStr).numberOfCharacters();
  13253. tp.m_oss.str("");
  13254. tp.open();
  13255. if (tp.m_currentColumn == static_cast<int>(tp.m_columnInfos.size() - 1)) {
  13256. tp.m_currentColumn = -1;
  13257. tp.m_os << "\n";
  13258. }
  13259. tp.m_currentColumn++;
  13260. auto colInfo = tp.m_columnInfos[tp.m_currentColumn];
  13261. auto padding = (strSize + 2 < static_cast<std::size_t>(colInfo.width))
  13262. ? std::string(colInfo.width - (strSize + 2), ' ')
  13263. : std::string();
  13264. if (colInfo.justification == ColumnInfo::Left)
  13265. tp.m_os << colStr << padding << " ";
  13266. else
  13267. tp.m_os << padding << colStr << " ";
  13268. return tp;
  13269. }
  13270. friend TablePrinter& operator << (TablePrinter& tp, RowBreak) {
  13271. if (tp.m_currentColumn > 0) {
  13272. tp.m_os << "\n";
  13273. tp.m_currentColumn = -1;
  13274. }
  13275. return tp;
  13276. }
  13277. };
  13278. ConsoleReporter::ConsoleReporter(ReporterConfig const& config)
  13279. : StreamingReporterBase(config),
  13280. m_tablePrinter(new TablePrinter(config.stream(),
  13281. {
  13282. { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 32, ColumnInfo::Left },
  13283. { "samples mean std dev", 14, ColumnInfo::Right },
  13284. { "iterations low mean low std dev", 14, ColumnInfo::Right },
  13285. { "estimated high mean high std dev", 14, ColumnInfo::Right }
  13286. })) {}
  13287. ConsoleReporter::~ConsoleReporter() = default;
  13288. std::string ConsoleReporter::getDescription() {
  13289. return "Reports test results as plain lines of text";
  13290. }
  13291. void ConsoleReporter::noMatchingTestCases(std::string const& spec) {
  13292. stream << "No test cases matched '" << spec << '\'' << std::endl;
  13293. }
  13294. void ConsoleReporter::assertionStarting(AssertionInfo const&) {}
  13295. bool ConsoleReporter::assertionEnded(AssertionStats const& _assertionStats) {
  13296. AssertionResult const& result = _assertionStats.assertionResult;
  13297. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  13298. // Drop out if result was successful but we're not printing them.
  13299. if (!includeResults && result.getResultType() != ResultWas::Warning)
  13300. return false;
  13301. lazyPrint();
  13302. ConsoleAssertionPrinter printer(stream, _assertionStats, includeResults);
  13303. printer.print();
  13304. stream << std::endl;
  13305. return true;
  13306. }
  13307. void ConsoleReporter::sectionStarting(SectionInfo const& _sectionInfo) {
  13308. m_tablePrinter->close();
  13309. m_headerPrinted = false;
  13310. StreamingReporterBase::sectionStarting(_sectionInfo);
  13311. }
  13312. void ConsoleReporter::sectionEnded(SectionStats const& _sectionStats) {
  13313. m_tablePrinter->close();
  13314. if (_sectionStats.missingAssertions) {
  13315. lazyPrint();
  13316. Colour colour(Colour::ResultError);
  13317. if (m_sectionStack.size() > 1)
  13318. stream << "\nNo assertions in section";
  13319. else
  13320. stream << "\nNo assertions in test case";
  13321. stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl;
  13322. }
  13323. if (m_config->showDurations() == ShowDurations::Always) {
  13324. stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  13325. }
  13326. if (m_headerPrinted) {
  13327. m_headerPrinted = false;
  13328. }
  13329. StreamingReporterBase::sectionEnded(_sectionStats);
  13330. }
  13331. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  13332. void ConsoleReporter::benchmarkPreparing(std::string const& name) {
  13333. lazyPrintWithoutClosingBenchmarkTable();
  13334. auto nameCol = Column(name).width(static_cast<std::size_t>(m_tablePrinter->columnInfos()[0].width - 2));
  13335. bool firstLine = true;
  13336. for (auto line : nameCol) {
  13337. if (!firstLine)
  13338. (*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak();
  13339. else
  13340. firstLine = false;
  13341. (*m_tablePrinter) << line << ColumnBreak();
  13342. }
  13343. }
  13344. void ConsoleReporter::benchmarkStarting(BenchmarkInfo const& info) {
  13345. (*m_tablePrinter) << info.samples << ColumnBreak()
  13346. << info.iterations << ColumnBreak()
  13347. << Duration(info.estimatedDuration) << ColumnBreak();
  13348. }
  13349. void ConsoleReporter::benchmarkEnded(BenchmarkStats<> const& stats) {
  13350. (*m_tablePrinter) << ColumnBreak()
  13351. << Duration(stats.mean.point.count()) << ColumnBreak()
  13352. << Duration(stats.mean.lower_bound.count()) << ColumnBreak()
  13353. << Duration(stats.mean.upper_bound.count()) << ColumnBreak() << ColumnBreak()
  13354. << Duration(stats.standardDeviation.point.count()) << ColumnBreak()
  13355. << Duration(stats.standardDeviation.lower_bound.count()) << ColumnBreak()
  13356. << Duration(stats.standardDeviation.upper_bound.count()) << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak();
  13357. }
  13358. void ConsoleReporter::benchmarkFailed(std::string const& error) {
  13359. Colour colour(Colour::Red);
  13360. (*m_tablePrinter)
  13361. << "Benchmark failed (" << error << ")"
  13362. << ColumnBreak() << RowBreak();
  13363. }
  13364. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  13365. void ConsoleReporter::testCaseEnded(TestCaseStats const& _testCaseStats) {
  13366. m_tablePrinter->close();
  13367. StreamingReporterBase::testCaseEnded(_testCaseStats);
  13368. m_headerPrinted = false;
  13369. }
  13370. void ConsoleReporter::testGroupEnded(TestGroupStats const& _testGroupStats) {
  13371. if (currentGroupInfo.used) {
  13372. printSummaryDivider();
  13373. stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n";
  13374. printTotals(_testGroupStats.totals);
  13375. stream << '\n' << std::endl;
  13376. }
  13377. StreamingReporterBase::testGroupEnded(_testGroupStats);
  13378. }
  13379. void ConsoleReporter::testRunEnded(TestRunStats const& _testRunStats) {
  13380. printTotalsDivider(_testRunStats.totals);
  13381. printTotals(_testRunStats.totals);
  13382. stream << std::endl;
  13383. StreamingReporterBase::testRunEnded(_testRunStats);
  13384. }
  13385. void ConsoleReporter::testRunStarting(TestRunInfo const& _testInfo) {
  13386. StreamingReporterBase::testRunStarting(_testInfo);
  13387. printTestFilters();
  13388. }
  13389. void ConsoleReporter::lazyPrint() {
  13390. m_tablePrinter->close();
  13391. lazyPrintWithoutClosingBenchmarkTable();
  13392. }
  13393. void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() {
  13394. if (!currentTestRunInfo.used)
  13395. lazyPrintRunInfo();
  13396. if (!currentGroupInfo.used)
  13397. lazyPrintGroupInfo();
  13398. if (!m_headerPrinted) {
  13399. printTestCaseAndSectionHeader();
  13400. m_headerPrinted = true;
  13401. }
  13402. }
  13403. void ConsoleReporter::lazyPrintRunInfo() {
  13404. stream << '\n' << getLineOfChars<'~'>() << '\n';
  13405. Colour colour(Colour::SecondaryText);
  13406. stream << currentTestRunInfo->name
  13407. << " is a Catch v" << libraryVersion() << " host application.\n"
  13408. << "Run with -? for options\n\n";
  13409. if (m_config->rngSeed() != 0)
  13410. stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n";
  13411. currentTestRunInfo.used = true;
  13412. }
  13413. void ConsoleReporter::lazyPrintGroupInfo() {
  13414. if (!currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1) {
  13415. printClosedHeader("Group: " + currentGroupInfo->name);
  13416. currentGroupInfo.used = true;
  13417. }
  13418. }
  13419. void ConsoleReporter::printTestCaseAndSectionHeader() {
  13420. assert(!m_sectionStack.empty());
  13421. printOpenHeader(currentTestCaseInfo->name);
  13422. if (m_sectionStack.size() > 1) {
  13423. Colour colourGuard(Colour::Headers);
  13424. auto
  13425. it = m_sectionStack.begin() + 1, // Skip first section (test case)
  13426. itEnd = m_sectionStack.end();
  13427. for (; it != itEnd; ++it)
  13428. printHeaderString(it->name, 2);
  13429. }
  13430. SourceLineInfo lineInfo = m_sectionStack.back().lineInfo;
  13431. if (!lineInfo.empty()) {
  13432. stream << getLineOfChars<'-'>() << '\n';
  13433. Colour colourGuard(Colour::FileName);
  13434. stream << lineInfo << '\n';
  13435. }
  13436. stream << getLineOfChars<'.'>() << '\n' << std::endl;
  13437. }
  13438. void ConsoleReporter::printClosedHeader(std::string const& _name) {
  13439. printOpenHeader(_name);
  13440. stream << getLineOfChars<'.'>() << '\n';
  13441. }
  13442. void ConsoleReporter::printOpenHeader(std::string const& _name) {
  13443. stream << getLineOfChars<'-'>() << '\n';
  13444. {
  13445. Colour colourGuard(Colour::Headers);
  13446. printHeaderString(_name);
  13447. }
  13448. }
  13449. // if string has a : in first line will set indent to follow it on
  13450. // subsequent lines
  13451. void ConsoleReporter::printHeaderString(std::string const& _string, std::size_t indent) {
  13452. std::size_t i = _string.find(": ");
  13453. if (i != std::string::npos)
  13454. i += 2;
  13455. else
  13456. i = 0;
  13457. stream << Column(_string).indent(indent + i).initialIndent(indent) << '\n';
  13458. }
  13459. struct SummaryColumn {
  13460. SummaryColumn( std::string _label, Colour::Code _colour )
  13461. : label( std::move( _label ) ),
  13462. colour( _colour ) {}
  13463. SummaryColumn addRow( std::size_t count ) {
  13464. ReusableStringStream rss;
  13465. rss << count;
  13466. std::string row = rss.str();
  13467. for (auto& oldRow : rows) {
  13468. while (oldRow.size() < row.size())
  13469. oldRow = ' ' + oldRow;
  13470. while (oldRow.size() > row.size())
  13471. row = ' ' + row;
  13472. }
  13473. rows.push_back(row);
  13474. return *this;
  13475. }
  13476. std::string label;
  13477. Colour::Code colour;
  13478. std::vector<std::string> rows;
  13479. };
  13480. void ConsoleReporter::printTotals( Totals const& totals ) {
  13481. if (totals.testCases.total() == 0) {
  13482. stream << Colour(Colour::Warning) << "No tests ran\n";
  13483. } else if (totals.assertions.total() > 0 && totals.testCases.allPassed()) {
  13484. stream << Colour(Colour::ResultSuccess) << "All tests passed";
  13485. stream << " ("
  13486. << pluralise(totals.assertions.passed, "assertion") << " in "
  13487. << pluralise(totals.testCases.passed, "test case") << ')'
  13488. << '\n';
  13489. } else {
  13490. std::vector<SummaryColumn> columns;
  13491. columns.push_back(SummaryColumn("", Colour::None)
  13492. .addRow(totals.testCases.total())
  13493. .addRow(totals.assertions.total()));
  13494. columns.push_back(SummaryColumn("passed", Colour::Success)
  13495. .addRow(totals.testCases.passed)
  13496. .addRow(totals.assertions.passed));
  13497. columns.push_back(SummaryColumn("failed", Colour::ResultError)
  13498. .addRow(totals.testCases.failed)
  13499. .addRow(totals.assertions.failed));
  13500. columns.push_back(SummaryColumn("failed as expected", Colour::ResultExpectedFailure)
  13501. .addRow(totals.testCases.failedButOk)
  13502. .addRow(totals.assertions.failedButOk));
  13503. printSummaryRow("test cases", columns, 0);
  13504. printSummaryRow("assertions", columns, 1);
  13505. }
  13506. }
  13507. void ConsoleReporter::printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row) {
  13508. for (auto col : cols) {
  13509. std::string value = col.rows[row];
  13510. if (col.label.empty()) {
  13511. stream << label << ": ";
  13512. if (value != "0")
  13513. stream << value;
  13514. else
  13515. stream << Colour(Colour::Warning) << "- none -";
  13516. } else if (value != "0") {
  13517. stream << Colour(Colour::LightGrey) << " | ";
  13518. stream << Colour(col.colour)
  13519. << value << ' ' << col.label;
  13520. }
  13521. }
  13522. stream << '\n';
  13523. }
  13524. void ConsoleReporter::printTotalsDivider(Totals const& totals) {
  13525. if (totals.testCases.total() > 0) {
  13526. std::size_t failedRatio = makeRatio(totals.testCases.failed, totals.testCases.total());
  13527. std::size_t failedButOkRatio = makeRatio(totals.testCases.failedButOk, totals.testCases.total());
  13528. std::size_t passedRatio = makeRatio(totals.testCases.passed, totals.testCases.total());
  13529. while (failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1)
  13530. findMax(failedRatio, failedButOkRatio, passedRatio)++;
  13531. while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1)
  13532. findMax(failedRatio, failedButOkRatio, passedRatio)--;
  13533. stream << Colour(Colour::Error) << std::string(failedRatio, '=');
  13534. stream << Colour(Colour::ResultExpectedFailure) << std::string(failedButOkRatio, '=');
  13535. if (totals.testCases.allPassed())
  13536. stream << Colour(Colour::ResultSuccess) << std::string(passedRatio, '=');
  13537. else
  13538. stream << Colour(Colour::Success) << std::string(passedRatio, '=');
  13539. } else {
  13540. stream << Colour(Colour::Warning) << std::string(CATCH_CONFIG_CONSOLE_WIDTH - 1, '=');
  13541. }
  13542. stream << '\n';
  13543. }
  13544. void ConsoleReporter::printSummaryDivider() {
  13545. stream << getLineOfChars<'-'>() << '\n';
  13546. }
  13547. void ConsoleReporter::printTestFilters() {
  13548. if (m_config->testSpec().hasFilters())
  13549. stream << Colour(Colour::BrightYellow) << "Filters: " << serializeFilters( m_config->getTestsOrTags() ) << '\n';
  13550. }
  13551. CATCH_REGISTER_REPORTER("console", ConsoleReporter)
  13552. } // end namespace Catch
  13553. #if defined(_MSC_VER)
  13554. #pragma warning(pop)
  13555. #endif
  13556. #if defined(__clang__)
  13557. # pragma clang diagnostic pop
  13558. #endif
  13559. // end catch_reporter_console.cpp
  13560. // start catch_reporter_junit.cpp
  13561. #include <cassert>
  13562. #include <sstream>
  13563. #include <ctime>
  13564. #include <algorithm>
  13565. namespace Catch {
  13566. namespace {
  13567. std::string getCurrentTimestamp() {
  13568. // Beware, this is not reentrant because of backward compatibility issues
  13569. // Also, UTC only, again because of backward compatibility (%z is C++11)
  13570. time_t rawtime;
  13571. std::time(&rawtime);
  13572. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  13573. #ifdef _MSC_VER
  13574. std::tm timeInfo = {};
  13575. gmtime_s(&timeInfo, &rawtime);
  13576. #else
  13577. std::tm* timeInfo;
  13578. timeInfo = std::gmtime(&rawtime);
  13579. #endif
  13580. char timeStamp[timeStampSize];
  13581. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  13582. #ifdef _MSC_VER
  13583. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  13584. #else
  13585. std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
  13586. #endif
  13587. return std::string(timeStamp);
  13588. }
  13589. std::string fileNameTag(const std::vector<std::string> &tags) {
  13590. auto it = std::find_if(begin(tags),
  13591. end(tags),
  13592. [] (std::string const& tag) {return tag.front() == '#'; });
  13593. if (it != tags.end())
  13594. return it->substr(1);
  13595. return std::string();
  13596. }
  13597. } // anonymous namespace
  13598. JunitReporter::JunitReporter( ReporterConfig const& _config )
  13599. : CumulativeReporterBase( _config ),
  13600. xml( _config.stream() )
  13601. {
  13602. m_reporterPrefs.shouldRedirectStdOut = true;
  13603. m_reporterPrefs.shouldReportAllAssertions = true;
  13604. }
  13605. JunitReporter::~JunitReporter() {}
  13606. std::string JunitReporter::getDescription() {
  13607. return "Reports test results in an XML format that looks like Ant's junitreport target";
  13608. }
  13609. void JunitReporter::noMatchingTestCases( std::string const& /*spec*/ ) {}
  13610. void JunitReporter::testRunStarting( TestRunInfo const& runInfo ) {
  13611. CumulativeReporterBase::testRunStarting( runInfo );
  13612. xml.startElement( "testsuites" );
  13613. }
  13614. void JunitReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  13615. suiteTimer.start();
  13616. stdOutForSuite.clear();
  13617. stdErrForSuite.clear();
  13618. unexpectedExceptions = 0;
  13619. CumulativeReporterBase::testGroupStarting( groupInfo );
  13620. }
  13621. void JunitReporter::testCaseStarting( TestCaseInfo const& testCaseInfo ) {
  13622. m_okToFail = testCaseInfo.okToFail();
  13623. }
  13624. bool JunitReporter::assertionEnded( AssertionStats const& assertionStats ) {
  13625. if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail )
  13626. unexpectedExceptions++;
  13627. return CumulativeReporterBase::assertionEnded( assertionStats );
  13628. }
  13629. void JunitReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  13630. stdOutForSuite += testCaseStats.stdOut;
  13631. stdErrForSuite += testCaseStats.stdErr;
  13632. CumulativeReporterBase::testCaseEnded( testCaseStats );
  13633. }
  13634. void JunitReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  13635. double suiteTime = suiteTimer.getElapsedSeconds();
  13636. CumulativeReporterBase::testGroupEnded( testGroupStats );
  13637. writeGroup( *m_testGroups.back(), suiteTime );
  13638. }
  13639. void JunitReporter::testRunEndedCumulative() {
  13640. xml.endElement();
  13641. }
  13642. void JunitReporter::writeGroup( TestGroupNode const& groupNode, double suiteTime ) {
  13643. XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" );
  13644. TestGroupStats const& stats = groupNode.value;
  13645. xml.writeAttribute( "name", stats.groupInfo.name );
  13646. xml.writeAttribute( "errors", unexpectedExceptions );
  13647. xml.writeAttribute( "failures", stats.totals.assertions.failed-unexpectedExceptions );
  13648. xml.writeAttribute( "tests", stats.totals.assertions.total() );
  13649. xml.writeAttribute( "hostname", "tbd" ); // !TBD
  13650. if( m_config->showDurations() == ShowDurations::Never )
  13651. xml.writeAttribute( "time", "" );
  13652. else
  13653. xml.writeAttribute( "time", suiteTime );
  13654. xml.writeAttribute( "timestamp", getCurrentTimestamp() );
  13655. // Write properties if there are any
  13656. if (m_config->hasTestFilters() || m_config->rngSeed() != 0) {
  13657. auto properties = xml.scopedElement("properties");
  13658. if (m_config->hasTestFilters()) {
  13659. xml.scopedElement("property")
  13660. .writeAttribute("name", "filters")
  13661. .writeAttribute("value", serializeFilters(m_config->getTestsOrTags()));
  13662. }
  13663. if (m_config->rngSeed() != 0) {
  13664. xml.scopedElement("property")
  13665. .writeAttribute("name", "random-seed")
  13666. .writeAttribute("value", m_config->rngSeed());
  13667. }
  13668. }
  13669. // Write test cases
  13670. for( auto const& child : groupNode.children )
  13671. writeTestCase( *child );
  13672. xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite ), false );
  13673. xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite ), false );
  13674. }
  13675. void JunitReporter::writeTestCase( TestCaseNode const& testCaseNode ) {
  13676. TestCaseStats const& stats = testCaseNode.value;
  13677. // All test cases have exactly one section - which represents the
  13678. // test case itself. That section may have 0-n nested sections
  13679. assert( testCaseNode.children.size() == 1 );
  13680. SectionNode const& rootSection = *testCaseNode.children.front();
  13681. std::string className = stats.testInfo.className;
  13682. if( className.empty() ) {
  13683. className = fileNameTag(stats.testInfo.tags);
  13684. if ( className.empty() )
  13685. className = "global";
  13686. }
  13687. if ( !m_config->name().empty() )
  13688. className = m_config->name() + "." + className;
  13689. writeSection( className, "", rootSection );
  13690. }
  13691. void JunitReporter::writeSection( std::string const& className,
  13692. std::string const& rootName,
  13693. SectionNode const& sectionNode ) {
  13694. std::string name = trim( sectionNode.stats.sectionInfo.name );
  13695. if( !rootName.empty() )
  13696. name = rootName + '/' + name;
  13697. if( !sectionNode.assertions.empty() ||
  13698. !sectionNode.stdOut.empty() ||
  13699. !sectionNode.stdErr.empty() ) {
  13700. XmlWriter::ScopedElement e = xml.scopedElement( "testcase" );
  13701. if( className.empty() ) {
  13702. xml.writeAttribute( "classname", name );
  13703. xml.writeAttribute( "name", "root" );
  13704. }
  13705. else {
  13706. xml.writeAttribute( "classname", className );
  13707. xml.writeAttribute( "name", name );
  13708. }
  13709. xml.writeAttribute( "time", ::Catch::Detail::stringify( sectionNode.stats.durationInSeconds ) );
  13710. writeAssertions( sectionNode );
  13711. if( !sectionNode.stdOut.empty() )
  13712. xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), false );
  13713. if( !sectionNode.stdErr.empty() )
  13714. xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), false );
  13715. }
  13716. for( auto const& childNode : sectionNode.childSections )
  13717. if( className.empty() )
  13718. writeSection( name, "", *childNode );
  13719. else
  13720. writeSection( className, name, *childNode );
  13721. }
  13722. void JunitReporter::writeAssertions( SectionNode const& sectionNode ) {
  13723. for( auto const& assertion : sectionNode.assertions )
  13724. writeAssertion( assertion );
  13725. }
  13726. void JunitReporter::writeAssertion( AssertionStats const& stats ) {
  13727. AssertionResult const& result = stats.assertionResult;
  13728. if( !result.isOk() ) {
  13729. std::string elementName;
  13730. switch( result.getResultType() ) {
  13731. case ResultWas::ThrewException:
  13732. case ResultWas::FatalErrorCondition:
  13733. elementName = "error";
  13734. break;
  13735. case ResultWas::ExplicitFailure:
  13736. elementName = "failure";
  13737. break;
  13738. case ResultWas::ExpressionFailed:
  13739. elementName = "failure";
  13740. break;
  13741. case ResultWas::DidntThrowException:
  13742. elementName = "failure";
  13743. break;
  13744. // We should never see these here:
  13745. case ResultWas::Info:
  13746. case ResultWas::Warning:
  13747. case ResultWas::Ok:
  13748. case ResultWas::Unknown:
  13749. case ResultWas::FailureBit:
  13750. case ResultWas::Exception:
  13751. elementName = "internalError";
  13752. break;
  13753. }
  13754. XmlWriter::ScopedElement e = xml.scopedElement( elementName );
  13755. xml.writeAttribute( "message", result.getExpandedExpression() );
  13756. xml.writeAttribute( "type", result.getTestMacroName() );
  13757. ReusableStringStream rss;
  13758. if( !result.getMessage().empty() )
  13759. rss << result.getMessage() << '\n';
  13760. for( auto const& msg : stats.infoMessages )
  13761. if( msg.type == ResultWas::Info )
  13762. rss << msg.message << '\n';
  13763. rss << "at " << result.getSourceInfo();
  13764. xml.writeText( rss.str(), false );
  13765. }
  13766. }
  13767. CATCH_REGISTER_REPORTER( "junit", JunitReporter )
  13768. } // end namespace Catch
  13769. // end catch_reporter_junit.cpp
  13770. // start catch_reporter_listening.cpp
  13771. #include <cassert>
  13772. namespace Catch {
  13773. ListeningReporter::ListeningReporter() {
  13774. // We will assume that listeners will always want all assertions
  13775. m_preferences.shouldReportAllAssertions = true;
  13776. }
  13777. void ListeningReporter::addListener( IStreamingReporterPtr&& listener ) {
  13778. m_listeners.push_back( std::move( listener ) );
  13779. }
  13780. void ListeningReporter::addReporter(IStreamingReporterPtr&& reporter) {
  13781. assert(!m_reporter && "Listening reporter can wrap only 1 real reporter");
  13782. m_reporter = std::move( reporter );
  13783. m_preferences.shouldRedirectStdOut = m_reporter->getPreferences().shouldRedirectStdOut;
  13784. }
  13785. ReporterPreferences ListeningReporter::getPreferences() const {
  13786. return m_preferences;
  13787. }
  13788. std::set<Verbosity> ListeningReporter::getSupportedVerbosities() {
  13789. return std::set<Verbosity>{ };
  13790. }
  13791. void ListeningReporter::noMatchingTestCases( std::string const& spec ) {
  13792. for ( auto const& listener : m_listeners ) {
  13793. listener->noMatchingTestCases( spec );
  13794. }
  13795. m_reporter->noMatchingTestCases( spec );
  13796. }
  13797. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  13798. void ListeningReporter::benchmarkPreparing( std::string const& name ) {
  13799. for (auto const& listener : m_listeners) {
  13800. listener->benchmarkPreparing(name);
  13801. }
  13802. m_reporter->benchmarkPreparing(name);
  13803. }
  13804. void ListeningReporter::benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) {
  13805. for ( auto const& listener : m_listeners ) {
  13806. listener->benchmarkStarting( benchmarkInfo );
  13807. }
  13808. m_reporter->benchmarkStarting( benchmarkInfo );
  13809. }
  13810. void ListeningReporter::benchmarkEnded( BenchmarkStats<> const& benchmarkStats ) {
  13811. for ( auto const& listener : m_listeners ) {
  13812. listener->benchmarkEnded( benchmarkStats );
  13813. }
  13814. m_reporter->benchmarkEnded( benchmarkStats );
  13815. }
  13816. void ListeningReporter::benchmarkFailed( std::string const& error ) {
  13817. for (auto const& listener : m_listeners) {
  13818. listener->benchmarkFailed(error);
  13819. }
  13820. m_reporter->benchmarkFailed(error);
  13821. }
  13822. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  13823. void ListeningReporter::testRunStarting( TestRunInfo const& testRunInfo ) {
  13824. for ( auto const& listener : m_listeners ) {
  13825. listener->testRunStarting( testRunInfo );
  13826. }
  13827. m_reporter->testRunStarting( testRunInfo );
  13828. }
  13829. void ListeningReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  13830. for ( auto const& listener : m_listeners ) {
  13831. listener->testGroupStarting( groupInfo );
  13832. }
  13833. m_reporter->testGroupStarting( groupInfo );
  13834. }
  13835. void ListeningReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
  13836. for ( auto const& listener : m_listeners ) {
  13837. listener->testCaseStarting( testInfo );
  13838. }
  13839. m_reporter->testCaseStarting( testInfo );
  13840. }
  13841. void ListeningReporter::sectionStarting( SectionInfo const& sectionInfo ) {
  13842. for ( auto const& listener : m_listeners ) {
  13843. listener->sectionStarting( sectionInfo );
  13844. }
  13845. m_reporter->sectionStarting( sectionInfo );
  13846. }
  13847. void ListeningReporter::assertionStarting( AssertionInfo const& assertionInfo ) {
  13848. for ( auto const& listener : m_listeners ) {
  13849. listener->assertionStarting( assertionInfo );
  13850. }
  13851. m_reporter->assertionStarting( assertionInfo );
  13852. }
  13853. // The return value indicates if the messages buffer should be cleared:
  13854. bool ListeningReporter::assertionEnded( AssertionStats const& assertionStats ) {
  13855. for( auto const& listener : m_listeners ) {
  13856. static_cast<void>( listener->assertionEnded( assertionStats ) );
  13857. }
  13858. return m_reporter->assertionEnded( assertionStats );
  13859. }
  13860. void ListeningReporter::sectionEnded( SectionStats const& sectionStats ) {
  13861. for ( auto const& listener : m_listeners ) {
  13862. listener->sectionEnded( sectionStats );
  13863. }
  13864. m_reporter->sectionEnded( sectionStats );
  13865. }
  13866. void ListeningReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  13867. for ( auto const& listener : m_listeners ) {
  13868. listener->testCaseEnded( testCaseStats );
  13869. }
  13870. m_reporter->testCaseEnded( testCaseStats );
  13871. }
  13872. void ListeningReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  13873. for ( auto const& listener : m_listeners ) {
  13874. listener->testGroupEnded( testGroupStats );
  13875. }
  13876. m_reporter->testGroupEnded( testGroupStats );
  13877. }
  13878. void ListeningReporter::testRunEnded( TestRunStats const& testRunStats ) {
  13879. for ( auto const& listener : m_listeners ) {
  13880. listener->testRunEnded( testRunStats );
  13881. }
  13882. m_reporter->testRunEnded( testRunStats );
  13883. }
  13884. void ListeningReporter::skipTest( TestCaseInfo const& testInfo ) {
  13885. for ( auto const& listener : m_listeners ) {
  13886. listener->skipTest( testInfo );
  13887. }
  13888. m_reporter->skipTest( testInfo );
  13889. }
  13890. bool ListeningReporter::isMulti() const {
  13891. return true;
  13892. }
  13893. } // end namespace Catch
  13894. // end catch_reporter_listening.cpp
  13895. // start catch_reporter_xml.cpp
  13896. #if defined(_MSC_VER)
  13897. #pragma warning(push)
  13898. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  13899. // Note that 4062 (not all labels are handled
  13900. // and default is missing) is enabled
  13901. #endif
  13902. namespace Catch {
  13903. XmlReporter::XmlReporter( ReporterConfig const& _config )
  13904. : StreamingReporterBase( _config ),
  13905. m_xml(_config.stream())
  13906. {
  13907. m_reporterPrefs.shouldRedirectStdOut = true;
  13908. m_reporterPrefs.shouldReportAllAssertions = true;
  13909. }
  13910. XmlReporter::~XmlReporter() = default;
  13911. std::string XmlReporter::getDescription() {
  13912. return "Reports test results as an XML document";
  13913. }
  13914. std::string XmlReporter::getStylesheetRef() const {
  13915. return std::string();
  13916. }
  13917. void XmlReporter::writeSourceInfo( SourceLineInfo const& sourceInfo ) {
  13918. m_xml
  13919. .writeAttribute( "filename", sourceInfo.file )
  13920. .writeAttribute( "line", sourceInfo.line );
  13921. }
  13922. void XmlReporter::noMatchingTestCases( std::string const& s ) {
  13923. StreamingReporterBase::noMatchingTestCases( s );
  13924. }
  13925. void XmlReporter::testRunStarting( TestRunInfo const& testInfo ) {
  13926. StreamingReporterBase::testRunStarting( testInfo );
  13927. std::string stylesheetRef = getStylesheetRef();
  13928. if( !stylesheetRef.empty() )
  13929. m_xml.writeStylesheetRef( stylesheetRef );
  13930. m_xml.startElement( "Catch" );
  13931. if( !m_config->name().empty() )
  13932. m_xml.writeAttribute( "name", m_config->name() );
  13933. if (m_config->testSpec().hasFilters())
  13934. m_xml.writeAttribute( "filters", serializeFilters( m_config->getTestsOrTags() ) );
  13935. if( m_config->rngSeed() != 0 )
  13936. m_xml.scopedElement( "Randomness" )
  13937. .writeAttribute( "seed", m_config->rngSeed() );
  13938. }
  13939. void XmlReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  13940. StreamingReporterBase::testGroupStarting( groupInfo );
  13941. m_xml.startElement( "Group" )
  13942. .writeAttribute( "name", groupInfo.name );
  13943. }
  13944. void XmlReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
  13945. StreamingReporterBase::testCaseStarting(testInfo);
  13946. m_xml.startElement( "TestCase" )
  13947. .writeAttribute( "name", trim( testInfo.name ) )
  13948. .writeAttribute( "description", testInfo.description )
  13949. .writeAttribute( "tags", testInfo.tagsAsString() );
  13950. writeSourceInfo( testInfo.lineInfo );
  13951. if ( m_config->showDurations() == ShowDurations::Always )
  13952. m_testCaseTimer.start();
  13953. m_xml.ensureTagClosed();
  13954. }
  13955. void XmlReporter::sectionStarting( SectionInfo const& sectionInfo ) {
  13956. StreamingReporterBase::sectionStarting( sectionInfo );
  13957. if( m_sectionDepth++ > 0 ) {
  13958. m_xml.startElement( "Section" )
  13959. .writeAttribute( "name", trim( sectionInfo.name ) );
  13960. writeSourceInfo( sectionInfo.lineInfo );
  13961. m_xml.ensureTagClosed();
  13962. }
  13963. }
  13964. void XmlReporter::assertionStarting( AssertionInfo const& ) { }
  13965. bool XmlReporter::assertionEnded( AssertionStats const& assertionStats ) {
  13966. AssertionResult const& result = assertionStats.assertionResult;
  13967. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  13968. if( includeResults || result.getResultType() == ResultWas::Warning ) {
  13969. // Print any info messages in <Info> tags.
  13970. for( auto const& msg : assertionStats.infoMessages ) {
  13971. if( msg.type == ResultWas::Info && includeResults ) {
  13972. m_xml.scopedElement( "Info" )
  13973. .writeText( msg.message );
  13974. } else if ( msg.type == ResultWas::Warning ) {
  13975. m_xml.scopedElement( "Warning" )
  13976. .writeText( msg.message );
  13977. }
  13978. }
  13979. }
  13980. // Drop out if result was successful but we're not printing them.
  13981. if( !includeResults && result.getResultType() != ResultWas::Warning )
  13982. return true;
  13983. // Print the expression if there is one.
  13984. if( result.hasExpression() ) {
  13985. m_xml.startElement( "Expression" )
  13986. .writeAttribute( "success", result.succeeded() )
  13987. .writeAttribute( "type", result.getTestMacroName() );
  13988. writeSourceInfo( result.getSourceInfo() );
  13989. m_xml.scopedElement( "Original" )
  13990. .writeText( result.getExpression() );
  13991. m_xml.scopedElement( "Expanded" )
  13992. .writeText( result.getExpandedExpression() );
  13993. }
  13994. // And... Print a result applicable to each result type.
  13995. switch( result.getResultType() ) {
  13996. case ResultWas::ThrewException:
  13997. m_xml.startElement( "Exception" );
  13998. writeSourceInfo( result.getSourceInfo() );
  13999. m_xml.writeText( result.getMessage() );
  14000. m_xml.endElement();
  14001. break;
  14002. case ResultWas::FatalErrorCondition:
  14003. m_xml.startElement( "FatalErrorCondition" );
  14004. writeSourceInfo( result.getSourceInfo() );
  14005. m_xml.writeText( result.getMessage() );
  14006. m_xml.endElement();
  14007. break;
  14008. case ResultWas::Info:
  14009. m_xml.scopedElement( "Info" )
  14010. .writeText( result.getMessage() );
  14011. break;
  14012. case ResultWas::Warning:
  14013. // Warning will already have been written
  14014. break;
  14015. case ResultWas::ExplicitFailure:
  14016. m_xml.startElement( "Failure" );
  14017. writeSourceInfo( result.getSourceInfo() );
  14018. m_xml.writeText( result.getMessage() );
  14019. m_xml.endElement();
  14020. break;
  14021. default:
  14022. break;
  14023. }
  14024. if( result.hasExpression() )
  14025. m_xml.endElement();
  14026. return true;
  14027. }
  14028. void XmlReporter::sectionEnded( SectionStats const& sectionStats ) {
  14029. StreamingReporterBase::sectionEnded( sectionStats );
  14030. if( --m_sectionDepth > 0 ) {
  14031. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResults" );
  14032. e.writeAttribute( "successes", sectionStats.assertions.passed );
  14033. e.writeAttribute( "failures", sectionStats.assertions.failed );
  14034. e.writeAttribute( "expectedFailures", sectionStats.assertions.failedButOk );
  14035. if ( m_config->showDurations() == ShowDurations::Always )
  14036. e.writeAttribute( "durationInSeconds", sectionStats.durationInSeconds );
  14037. m_xml.endElement();
  14038. }
  14039. }
  14040. void XmlReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  14041. StreamingReporterBase::testCaseEnded( testCaseStats );
  14042. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResult" );
  14043. e.writeAttribute( "success", testCaseStats.totals.assertions.allOk() );
  14044. if ( m_config->showDurations() == ShowDurations::Always )
  14045. e.writeAttribute( "durationInSeconds", m_testCaseTimer.getElapsedSeconds() );
  14046. if( !testCaseStats.stdOut.empty() )
  14047. m_xml.scopedElement( "StdOut" ).writeText( trim( testCaseStats.stdOut ), false );
  14048. if( !testCaseStats.stdErr.empty() )
  14049. m_xml.scopedElement( "StdErr" ).writeText( trim( testCaseStats.stdErr ), false );
  14050. m_xml.endElement();
  14051. }
  14052. void XmlReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  14053. StreamingReporterBase::testGroupEnded( testGroupStats );
  14054. // TODO: Check testGroupStats.aborting and act accordingly.
  14055. m_xml.scopedElement( "OverallResults" )
  14056. .writeAttribute( "successes", testGroupStats.totals.assertions.passed )
  14057. .writeAttribute( "failures", testGroupStats.totals.assertions.failed )
  14058. .writeAttribute( "expectedFailures", testGroupStats.totals.assertions.failedButOk );
  14059. m_xml.endElement();
  14060. }
  14061. void XmlReporter::testRunEnded( TestRunStats const& testRunStats ) {
  14062. StreamingReporterBase::testRunEnded( testRunStats );
  14063. m_xml.scopedElement( "OverallResults" )
  14064. .writeAttribute( "successes", testRunStats.totals.assertions.passed )
  14065. .writeAttribute( "failures", testRunStats.totals.assertions.failed )
  14066. .writeAttribute( "expectedFailures", testRunStats.totals.assertions.failedButOk );
  14067. m_xml.endElement();
  14068. }
  14069. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  14070. void XmlReporter::benchmarkPreparing(std::string const& name) {
  14071. m_xml.startElement("BenchmarkResults")
  14072. .writeAttribute("name", name);
  14073. }
  14074. void XmlReporter::benchmarkStarting(BenchmarkInfo const &info) {
  14075. m_xml.writeAttribute("samples", info.samples)
  14076. .writeAttribute("resamples", info.resamples)
  14077. .writeAttribute("iterations", info.iterations)
  14078. .writeAttribute("clockResolution", static_cast<uint64_t>(info.clockResolution))
  14079. .writeAttribute("estimatedDuration", static_cast<uint64_t>(info.estimatedDuration))
  14080. .writeComment("All values in nano seconds");
  14081. }
  14082. void XmlReporter::benchmarkEnded(BenchmarkStats<> const& benchmarkStats) {
  14083. m_xml.startElement("mean")
  14084. .writeAttribute("value", static_cast<uint64_t>(benchmarkStats.mean.point.count()))
  14085. .writeAttribute("lowerBound", static_cast<uint64_t>(benchmarkStats.mean.lower_bound.count()))
  14086. .writeAttribute("upperBound", static_cast<uint64_t>(benchmarkStats.mean.upper_bound.count()))
  14087. .writeAttribute("ci", benchmarkStats.mean.confidence_interval);
  14088. m_xml.endElement();
  14089. m_xml.startElement("standardDeviation")
  14090. .writeAttribute("value", benchmarkStats.standardDeviation.point.count())
  14091. .writeAttribute("lowerBound", benchmarkStats.standardDeviation.lower_bound.count())
  14092. .writeAttribute("upperBound", benchmarkStats.standardDeviation.upper_bound.count())
  14093. .writeAttribute("ci", benchmarkStats.standardDeviation.confidence_interval);
  14094. m_xml.endElement();
  14095. m_xml.startElement("outliers")
  14096. .writeAttribute("variance", benchmarkStats.outlierVariance)
  14097. .writeAttribute("lowMild", benchmarkStats.outliers.low_mild)
  14098. .writeAttribute("lowSevere", benchmarkStats.outliers.low_severe)
  14099. .writeAttribute("highMild", benchmarkStats.outliers.high_mild)
  14100. .writeAttribute("highSevere", benchmarkStats.outliers.high_severe);
  14101. m_xml.endElement();
  14102. m_xml.endElement();
  14103. }
  14104. void XmlReporter::benchmarkFailed(std::string const &error) {
  14105. m_xml.scopedElement("failed").
  14106. writeAttribute("message", error);
  14107. m_xml.endElement();
  14108. }
  14109. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  14110. CATCH_REGISTER_REPORTER( "xml", XmlReporter )
  14111. } // end namespace Catch
  14112. #if defined(_MSC_VER)
  14113. #pragma warning(pop)
  14114. #endif
  14115. // end catch_reporter_xml.cpp
  14116. namespace Catch {
  14117. LeakDetector leakDetector;
  14118. }
  14119. #ifdef __clang__
  14120. #pragma clang diagnostic pop
  14121. #endif
  14122. // end catch_impl.hpp
  14123. #endif
  14124. #ifdef CATCH_CONFIG_MAIN
  14125. // start catch_default_main.hpp
  14126. #ifndef __OBJC__
  14127. #if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN)
  14128. // Standard C/C++ Win32 Unicode wmain entry point
  14129. extern "C" int wmain (int argc, wchar_t * argv[], wchar_t * []) {
  14130. #else
  14131. // Standard C/C++ main entry point
  14132. int main (int argc, char * argv[]) {
  14133. #endif
  14134. return Catch::Session().run( argc, argv );
  14135. }
  14136. #else // __OBJC__
  14137. // Objective-C entry point
  14138. int main (int argc, char * const argv[]) {
  14139. #if !CATCH_ARC_ENABLED
  14140. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  14141. #endif
  14142. Catch::registerTestMethods();
  14143. int result = Catch::Session().run( argc, (char**)argv );
  14144. #if !CATCH_ARC_ENABLED
  14145. [pool drain];
  14146. #endif
  14147. return result;
  14148. }
  14149. #endif // __OBJC__
  14150. // end catch_default_main.hpp
  14151. #endif
  14152. #if !defined(CATCH_CONFIG_IMPL_ONLY)
  14153. #ifdef CLARA_CONFIG_MAIN_NOT_DEFINED
  14154. # undef CLARA_CONFIG_MAIN
  14155. #endif
  14156. #if !defined(CATCH_CONFIG_DISABLE)
  14157. //////
  14158. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  14159. #ifdef CATCH_CONFIG_PREFIX_ALL
  14160. #define CATCH_REQUIRE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  14161. #define CATCH_REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  14162. #define CATCH_REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  14163. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  14164. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  14165. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14166. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  14167. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  14168. #define CATCH_REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  14169. #define CATCH_CHECK( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14170. #define CATCH_CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  14171. #define CATCH_CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14172. #define CATCH_CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14173. #define CATCH_CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  14174. #define CATCH_CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14175. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  14176. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  14177. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14178. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  14179. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14180. #define CATCH_CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14181. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14182. #define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  14183. #define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  14184. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14185. #define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg )
  14186. #define CATCH_UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "CATCH_UNSCOPED_INFO", msg )
  14187. #define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  14188. #define CATCH_CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CATCH_CAPTURE",__VA_ARGS__ )
  14189. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  14190. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14191. #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  14192. #define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  14193. #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  14194. #define CATCH_DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
  14195. #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  14196. #define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14197. #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14198. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  14199. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  14200. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14201. #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ )
  14202. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14203. #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
  14204. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )
  14205. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ )
  14206. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14207. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
  14208. #else
  14209. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
  14210. #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) )
  14211. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  14212. #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
  14213. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )
  14214. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) )
  14215. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  14216. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
  14217. #endif
  14218. #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
  14219. #define CATCH_STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__ , #__VA_ARGS__ ); CATCH_SUCCEED( #__VA_ARGS__ )
  14220. #define CATCH_STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); CATCH_SUCCEED( #__VA_ARGS__ )
  14221. #else
  14222. #define CATCH_STATIC_REQUIRE( ... ) CATCH_REQUIRE( __VA_ARGS__ )
  14223. #define CATCH_STATIC_REQUIRE_FALSE( ... ) CATCH_REQUIRE_FALSE( __VA_ARGS__ )
  14224. #endif
  14225. // "BDD-style" convenience wrappers
  14226. #define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ )
  14227. #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  14228. #define CATCH_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
  14229. #define CATCH_AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
  14230. #define CATCH_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
  14231. #define CATCH_AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
  14232. #define CATCH_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
  14233. #define CATCH_AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
  14234. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  14235. #define CATCH_BENCHMARK(...) \
  14236. 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__,,))
  14237. #define CATCH_BENCHMARK_ADVANCED(name) \
  14238. INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), name)
  14239. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  14240. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  14241. #else
  14242. #define REQUIRE(...) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  14243. #define REQUIRE_FALSE(...) INTERNAL_CATCH_TEST( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  14244. #define REQUIRE_THROWS(...) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  14245. #define REQUIRE_THROWS_AS(expr, exceptionType) INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  14246. #define REQUIRE_THROWS_WITH(expr, matcher) INTERNAL_CATCH_THROWS_STR_MATCHES( "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  14247. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14248. #define REQUIRE_THROWS_MATCHES(expr, exceptionType, matcher) INTERNAL_CATCH_THROWS_MATCHES( "REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  14249. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14250. #define REQUIRE_NOTHROW(...) INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  14251. #define CHECK(...) INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14252. #define CHECK_FALSE(...) INTERNAL_CATCH_TEST( "CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  14253. #define CHECKED_IF(...) INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14254. #define CHECKED_ELSE(...) INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14255. #define CHECK_NOFAIL(...) INTERNAL_CATCH_TEST( "CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  14256. #define CHECK_THROWS(...) INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14257. #define CHECK_THROWS_AS(expr, exceptionType) INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  14258. #define CHECK_THROWS_WITH(expr, matcher) INTERNAL_CATCH_THROWS_STR_MATCHES( "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  14259. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14260. #define CHECK_THROWS_MATCHES(expr, exceptionType, matcher) INTERNAL_CATCH_THROWS_MATCHES( "CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  14261. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14262. #define CHECK_NOTHROW(...) INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14263. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14264. #define CHECK_THAT(arg, matcher) INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  14265. #define REQUIRE_THAT(arg, matcher) INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  14266. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14267. #define INFO(msg) INTERNAL_CATCH_INFO( "INFO", msg )
  14268. #define UNSCOPED_INFO(msg) INTERNAL_CATCH_UNSCOPED_INFO( "UNSCOPED_INFO", msg )
  14269. #define WARN(msg) INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  14270. #define CAPTURE(...) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CAPTURE",__VA_ARGS__ )
  14271. #define TEST_CASE(...) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  14272. #define TEST_CASE_METHOD(className, ...) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14273. #define METHOD_AS_TEST_CASE(method, ...) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  14274. #define REGISTER_TEST_CASE(Function, ...) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  14275. #define SECTION(...) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  14276. #define DYNAMIC_SECTION(...) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
  14277. #define FAIL(...) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  14278. #define FAIL_CHECK(...) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14279. #define SUCCEED(...) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14280. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  14281. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  14282. #define TEMPLATE_TEST_CASE(...) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14283. #define TEMPLATE_TEST_CASE_SIG(...) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ )
  14284. #define TEMPLATE_TEST_CASE_METHOD(className, ...) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14285. #define TEMPLATE_TEST_CASE_METHOD_SIG(className, ...) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
  14286. #define TEMPLATE_PRODUCT_TEST_CASE(...) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )
  14287. #define TEMPLATE_PRODUCT_TEST_CASE_SIG(...) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ )
  14288. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, ...) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14289. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, ...) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
  14290. #define TEMPLATE_LIST_TEST_CASE(...) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(__VA_ARGS__)
  14291. #define TEMPLATE_LIST_TEST_CASE_METHOD(className, ...) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14292. #else
  14293. #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
  14294. #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) )
  14295. #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  14296. #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
  14297. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )
  14298. #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) )
  14299. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  14300. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
  14301. #define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE( __VA_ARGS__ ) )
  14302. #define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  14303. #endif
  14304. #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
  14305. #define STATIC_REQUIRE(...) static_assert( __VA_ARGS__, #__VA_ARGS__ ); SUCCEED( #__VA_ARGS__ )
  14306. #define STATIC_REQUIRE_FALSE(...) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); SUCCEED( "!(" #__VA_ARGS__ ")" )
  14307. #else
  14308. #define STATIC_REQUIRE( ... ) REQUIRE( __VA_ARGS__ )
  14309. #define STATIC_REQUIRE_FALSE( ... ) REQUIRE_FALSE( __VA_ARGS__ )
  14310. #endif
  14311. #endif
  14312. #define CATCH_TRANSLATE_EXCEPTION(signature) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature )
  14313. // "BDD-style" convenience wrappers
  14314. #define SCENARIO(...) TEST_CASE( "Scenario: " __VA_ARGS__ )
  14315. #define SCENARIO_METHOD(className, ...) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  14316. #define GIVEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
  14317. #define AND_GIVEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
  14318. #define WHEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
  14319. #define AND_WHEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
  14320. #define THEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
  14321. #define AND_THEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
  14322. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  14323. #define BENCHMARK(...) \
  14324. 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__,,))
  14325. #define BENCHMARK_ADVANCED(name) \
  14326. INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), name)
  14327. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  14328. using Catch::Detail::Approx;
  14329. #else // CATCH_CONFIG_DISABLE
  14330. //////
  14331. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  14332. #ifdef CATCH_CONFIG_PREFIX_ALL
  14333. #define CATCH_REQUIRE( ... ) (void)(0)
  14334. #define CATCH_REQUIRE_FALSE( ... ) (void)(0)
  14335. #define CATCH_REQUIRE_THROWS( ... ) (void)(0)
  14336. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  14337. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  14338. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14339. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  14340. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  14341. #define CATCH_REQUIRE_NOTHROW( ... ) (void)(0)
  14342. #define CATCH_CHECK( ... ) (void)(0)
  14343. #define CATCH_CHECK_FALSE( ... ) (void)(0)
  14344. #define CATCH_CHECKED_IF( ... ) if (__VA_ARGS__)
  14345. #define CATCH_CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  14346. #define CATCH_CHECK_NOFAIL( ... ) (void)(0)
  14347. #define CATCH_CHECK_THROWS( ... ) (void)(0)
  14348. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  14349. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  14350. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14351. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  14352. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14353. #define CATCH_CHECK_NOTHROW( ... ) (void)(0)
  14354. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14355. #define CATCH_CHECK_THAT( arg, matcher ) (void)(0)
  14356. #define CATCH_REQUIRE_THAT( arg, matcher ) (void)(0)
  14357. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14358. #define CATCH_INFO( msg ) (void)(0)
  14359. #define CATCH_UNSCOPED_INFO( msg ) (void)(0)
  14360. #define CATCH_WARN( msg ) (void)(0)
  14361. #define CATCH_CAPTURE( msg ) (void)(0)
  14362. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  14363. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  14364. #define CATCH_METHOD_AS_TEST_CASE( method, ... )
  14365. #define CATCH_REGISTER_TEST_CASE( Function, ... ) (void)(0)
  14366. #define CATCH_SECTION( ... )
  14367. #define CATCH_DYNAMIC_SECTION( ... )
  14368. #define CATCH_FAIL( ... ) (void)(0)
  14369. #define CATCH_FAIL_CHECK( ... ) (void)(0)
  14370. #define CATCH_SUCCEED( ... ) (void)(0)
  14371. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  14372. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  14373. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
  14374. #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
  14375. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
  14376. #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ )
  14377. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14378. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14379. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14380. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14381. #else
  14382. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) )
  14383. #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) )
  14384. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) )
  14385. #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) )
  14386. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14387. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14388. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14389. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14390. #endif
  14391. // "BDD-style" convenience wrappers
  14392. #define CATCH_SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  14393. #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 )
  14394. #define CATCH_GIVEN( desc )
  14395. #define CATCH_AND_GIVEN( desc )
  14396. #define CATCH_WHEN( desc )
  14397. #define CATCH_AND_WHEN( desc )
  14398. #define CATCH_THEN( desc )
  14399. #define CATCH_AND_THEN( desc )
  14400. #define CATCH_STATIC_REQUIRE( ... ) (void)(0)
  14401. #define CATCH_STATIC_REQUIRE_FALSE( ... ) (void)(0)
  14402. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  14403. #else
  14404. #define REQUIRE( ... ) (void)(0)
  14405. #define REQUIRE_FALSE( ... ) (void)(0)
  14406. #define REQUIRE_THROWS( ... ) (void)(0)
  14407. #define REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  14408. #define REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  14409. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14410. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  14411. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14412. #define REQUIRE_NOTHROW( ... ) (void)(0)
  14413. #define CHECK( ... ) (void)(0)
  14414. #define CHECK_FALSE( ... ) (void)(0)
  14415. #define CHECKED_IF( ... ) if (__VA_ARGS__)
  14416. #define CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  14417. #define CHECK_NOFAIL( ... ) (void)(0)
  14418. #define CHECK_THROWS( ... ) (void)(0)
  14419. #define CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  14420. #define CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  14421. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14422. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  14423. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14424. #define CHECK_NOTHROW( ... ) (void)(0)
  14425. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14426. #define CHECK_THAT( arg, matcher ) (void)(0)
  14427. #define REQUIRE_THAT( arg, matcher ) (void)(0)
  14428. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14429. #define INFO( msg ) (void)(0)
  14430. #define UNSCOPED_INFO( msg ) (void)(0)
  14431. #define WARN( msg ) (void)(0)
  14432. #define CAPTURE( msg ) (void)(0)
  14433. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  14434. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  14435. #define METHOD_AS_TEST_CASE( method, ... )
  14436. #define REGISTER_TEST_CASE( Function, ... ) (void)(0)
  14437. #define SECTION( ... )
  14438. #define DYNAMIC_SECTION( ... )
  14439. #define FAIL( ... ) (void)(0)
  14440. #define FAIL_CHECK( ... ) (void)(0)
  14441. #define SUCCEED( ... ) (void)(0)
  14442. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  14443. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  14444. #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
  14445. #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
  14446. #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
  14447. #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ )
  14448. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14449. #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14450. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14451. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14452. #else
  14453. #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) )
  14454. #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) )
  14455. #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) )
  14456. #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) )
  14457. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14458. #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14459. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14460. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14461. #endif
  14462. #define STATIC_REQUIRE( ... ) (void)(0)
  14463. #define STATIC_REQUIRE_FALSE( ... ) (void)(0)
  14464. #endif
  14465. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
  14466. // "BDD-style" convenience wrappers
  14467. #define SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) )
  14468. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className )
  14469. #define GIVEN( desc )
  14470. #define AND_GIVEN( desc )
  14471. #define WHEN( desc )
  14472. #define AND_WHEN( desc )
  14473. #define THEN( desc )
  14474. #define AND_THEN( desc )
  14475. using Catch::Detail::Approx;
  14476. #endif
  14477. #endif // ! CATCH_CONFIG_IMPL_ONLY
  14478. // start catch_reenable_warnings.h
  14479. #ifdef __clang__
  14480. # ifdef __ICC // icpc defines the __clang__ macro
  14481. # pragma warning(pop)
  14482. # else
  14483. # pragma clang diagnostic pop
  14484. # endif
  14485. #elif defined __GNUC__
  14486. # pragma GCC diagnostic pop
  14487. #endif
  14488. // end catch_reenable_warnings.h
  14489. // end catch.hpp
  14490. #endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED