catch.hpp 440 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287
  1. /*
  2. * Catch v2.2.3
  3. * Generated: 2018-06-06 23:11:57.601416
  4. * ----------------------------------------------------------
  5. * This file has been merged from multiple headers. Please don't edit it directly
  6. * Copyright (c) 2018 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 2
  16. #define CATCH_VERSION_PATCH 3
  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 ignored "-Wunused-variable"
  29. # pragma clang diagnostic push
  30. # pragma clang diagnostic ignored "-Wpadded"
  31. # pragma clang diagnostic ignored "-Wswitch-enum"
  32. # pragma clang diagnostic ignored "-Wcovered-switch-default"
  33. # endif
  34. #elif defined __GNUC__
  35. # pragma GCC diagnostic ignored "-Wparentheses"
  36. # pragma GCC diagnostic push
  37. # pragma GCC diagnostic ignored "-Wunused-variable"
  38. # pragma GCC diagnostic ignored "-Wpadded"
  39. #endif
  40. // end catch_suppress_warnings.h
  41. #if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER)
  42. # define CATCH_IMPL
  43. # define CATCH_CONFIG_ALL_PARTS
  44. #endif
  45. // In the impl file, we want to have access to all parts of the headers
  46. // Can also be used to sanely support PCHs
  47. #if defined(CATCH_CONFIG_ALL_PARTS)
  48. # define CATCH_CONFIG_EXTERNAL_INTERFACES
  49. # if defined(CATCH_CONFIG_DISABLE_MATCHERS)
  50. # undef CATCH_CONFIG_DISABLE_MATCHERS
  51. # endif
  52. # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  53. #endif
  54. #if !defined(CATCH_CONFIG_IMPL_ONLY)
  55. // start catch_platform.h
  56. #ifdef __APPLE__
  57. # include <TargetConditionals.h>
  58. # if TARGET_OS_OSX == 1
  59. # define CATCH_PLATFORM_MAC
  60. # elif TARGET_OS_IPHONE == 1
  61. # define CATCH_PLATFORM_IPHONE
  62. # endif
  63. #elif defined(linux) || defined(__linux) || defined(__linux__)
  64. # define CATCH_PLATFORM_LINUX
  65. #elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) || defined(__MINGW32__)
  66. # define CATCH_PLATFORM_WINDOWS
  67. #endif
  68. // end catch_platform.h
  69. #ifdef CATCH_IMPL
  70. # ifndef CLARA_CONFIG_MAIN
  71. # define CLARA_CONFIG_MAIN_NOT_DEFINED
  72. # define CLARA_CONFIG_MAIN
  73. # endif
  74. #endif
  75. // start catch_user_interfaces.h
  76. namespace Catch {
  77. unsigned int rngSeed();
  78. }
  79. // end catch_user_interfaces.h
  80. // start catch_tag_alias_autoregistrar.h
  81. // start catch_common.h
  82. // start catch_compiler_capabilities.h
  83. // Detect a number of compiler features - by compiler
  84. // The following features are defined:
  85. //
  86. // CATCH_CONFIG_COUNTER : is the __COUNTER__ macro supported?
  87. // CATCH_CONFIG_WINDOWS_SEH : is Windows SEH supported?
  88. // CATCH_CONFIG_POSIX_SIGNALS : are POSIX signals supported?
  89. // ****************
  90. // Note to maintainers: if new toggles are added please document them
  91. // in configuration.md, too
  92. // ****************
  93. // In general each macro has a _NO_<feature name> form
  94. // (e.g. CATCH_CONFIG_NO_POSIX_SIGNALS) which disables the feature.
  95. // Many features, at point of detection, define an _INTERNAL_ macro, so they
  96. // can be combined, en-mass, with the _NO_ forms later.
  97. #ifdef __cplusplus
  98. # if __cplusplus >= 201402L
  99. # define CATCH_CPP14_OR_GREATER
  100. # endif
  101. # if __cplusplus >= 201703L
  102. # define CATCH_CPP17_OR_GREATER
  103. # endif
  104. #endif
  105. #if defined(CATCH_CPP17_OR_GREATER)
  106. # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
  107. #endif
  108. #ifdef __clang__
  109. # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  110. _Pragma( "clang diagnostic push" ) \
  111. _Pragma( "clang diagnostic ignored \"-Wexit-time-destructors\"" ) \
  112. _Pragma( "clang diagnostic ignored \"-Wglobal-constructors\"")
  113. # define CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  114. _Pragma( "clang diagnostic pop" )
  115. # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
  116. _Pragma( "clang diagnostic push" ) \
  117. _Pragma( "clang diagnostic ignored \"-Wparentheses\"" )
  118. # define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
  119. _Pragma( "clang diagnostic pop" )
  120. #endif // __clang__
  121. ////////////////////////////////////////////////////////////////////////////////
  122. // Assume that non-Windows platforms support posix signals by default
  123. #if !defined(CATCH_PLATFORM_WINDOWS)
  124. #define CATCH_INTERNAL_CONFIG_POSIX_SIGNALS
  125. #endif
  126. ////////////////////////////////////////////////////////////////////////////////
  127. // We know some environments not to support full POSIX signals
  128. #if defined(__CYGWIN__) || defined(__QNX__) || defined(__EMSCRIPTEN__) || defined(__DJGPP__)
  129. #define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
  130. #endif
  131. #ifdef __OS400__
  132. # define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
  133. # define CATCH_CONFIG_COLOUR_NONE
  134. #endif
  135. ////////////////////////////////////////////////////////////////////////////////
  136. // Android somehow still does not support std::to_string
  137. #if defined(__ANDROID__)
  138. # define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
  139. #endif
  140. ////////////////////////////////////////////////////////////////////////////////
  141. // Not all Windows environments support SEH properly
  142. #if defined(__MINGW32__)
  143. # define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH
  144. #endif
  145. ////////////////////////////////////////////////////////////////////////////////
  146. // Cygwin
  147. #ifdef __CYGWIN__
  148. // Required for some versions of Cygwin to declare gettimeofday
  149. // see: http://stackoverflow.com/questions/36901803/gettimeofday-not-declared-in-this-scope-cygwin
  150. # define _BSD_SOURCE
  151. #endif // __CYGWIN__
  152. ////////////////////////////////////////////////////////////////////////////////
  153. // Visual C++
  154. #ifdef _MSC_VER
  155. # if _MSC_VER >= 1900 // Visual Studio 2015 or newer
  156. # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
  157. # endif
  158. // Universal Windows platform does not support SEH
  159. // Or console colours (or console at all...)
  160. # if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP)
  161. # define CATCH_CONFIG_COLOUR_NONE
  162. # else
  163. # define CATCH_INTERNAL_CONFIG_WINDOWS_SEH
  164. # endif
  165. #endif // _MSC_VER
  166. ////////////////////////////////////////////////////////////////////////////////
  167. // DJGPP
  168. #ifdef __DJGPP__
  169. # define CATCH_INTERNAL_CONFIG_NO_WCHAR
  170. #endif // __DJGPP__
  171. ////////////////////////////////////////////////////////////////////////////////
  172. // Use of __COUNTER__ is suppressed during code analysis in
  173. // CLion/AppCode 2017.2.x and former, because __COUNTER__ is not properly
  174. // handled by it.
  175. // Otherwise all supported compilers support COUNTER macro,
  176. // but user still might want to turn it off
  177. #if ( !defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L )
  178. #define CATCH_INTERNAL_CONFIG_COUNTER
  179. #endif
  180. #if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER)
  181. # define CATCH_CONFIG_COUNTER
  182. #endif
  183. #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)
  184. # define CATCH_CONFIG_WINDOWS_SEH
  185. #endif
  186. // This is set by default, because we assume that unix compilers are posix-signal-compatible by default.
  187. #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)
  188. # define CATCH_CONFIG_POSIX_SIGNALS
  189. #endif
  190. // This is set by default, because we assume that compilers with no wchar_t support are just rare exceptions.
  191. #if !defined(CATCH_INTERNAL_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_WCHAR)
  192. # define CATCH_CONFIG_WCHAR
  193. #endif
  194. #if !defined(CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_CPP11_TO_STRING)
  195. # define CATCH_CONFIG_CPP11_TO_STRING
  196. #endif
  197. #if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
  198. # define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
  199. #endif
  200. #if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS)
  201. # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS
  202. # define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS
  203. #endif
  204. #if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS)
  205. # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  206. # define CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  207. #endif
  208. // end catch_compiler_capabilities.h
  209. #define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line
  210. #define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line )
  211. #ifdef CATCH_CONFIG_COUNTER
  212. # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ )
  213. #else
  214. # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ )
  215. #endif
  216. #include <iosfwd>
  217. #include <string>
  218. #include <cstdint>
  219. namespace Catch {
  220. struct CaseSensitive { enum Choice {
  221. Yes,
  222. No
  223. }; };
  224. class NonCopyable {
  225. NonCopyable( NonCopyable const& ) = delete;
  226. NonCopyable( NonCopyable && ) = delete;
  227. NonCopyable& operator = ( NonCopyable const& ) = delete;
  228. NonCopyable& operator = ( NonCopyable && ) = delete;
  229. protected:
  230. NonCopyable();
  231. virtual ~NonCopyable();
  232. };
  233. struct SourceLineInfo {
  234. SourceLineInfo() = delete;
  235. SourceLineInfo( char const* _file, std::size_t _line ) noexcept
  236. : file( _file ),
  237. line( _line )
  238. {}
  239. SourceLineInfo( SourceLineInfo const& other ) = default;
  240. SourceLineInfo( SourceLineInfo && ) = default;
  241. SourceLineInfo& operator = ( SourceLineInfo const& ) = default;
  242. SourceLineInfo& operator = ( SourceLineInfo && ) = default;
  243. bool empty() const noexcept;
  244. bool operator == ( SourceLineInfo const& other ) const noexcept;
  245. bool operator < ( SourceLineInfo const& other ) const noexcept;
  246. char const* file;
  247. std::size_t line;
  248. };
  249. std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info );
  250. // Use this in variadic streaming macros to allow
  251. // >> +StreamEndStop
  252. // as well as
  253. // >> stuff +StreamEndStop
  254. struct StreamEndStop {
  255. std::string operator+() const;
  256. };
  257. template<typename T>
  258. T const& operator + ( T const& value, StreamEndStop ) {
  259. return value;
  260. }
  261. }
  262. #define CATCH_INTERNAL_LINEINFO \
  263. ::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) )
  264. // end catch_common.h
  265. namespace Catch {
  266. struct RegistrarForTagAliases {
  267. RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo );
  268. };
  269. } // end namespace Catch
  270. #define CATCH_REGISTER_TAG_ALIAS( alias, spec ) \
  271. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  272. namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } \
  273. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  274. // end catch_tag_alias_autoregistrar.h
  275. // start catch_test_registry.h
  276. // start catch_interfaces_testcase.h
  277. #include <vector>
  278. #include <memory>
  279. namespace Catch {
  280. class TestSpec;
  281. struct ITestInvoker {
  282. virtual void invoke () const = 0;
  283. virtual ~ITestInvoker();
  284. };
  285. using ITestCasePtr = std::shared_ptr<ITestInvoker>;
  286. class TestCase;
  287. struct IConfig;
  288. struct ITestCaseRegistry {
  289. virtual ~ITestCaseRegistry();
  290. virtual std::vector<TestCase> const& getAllTests() const = 0;
  291. virtual std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const = 0;
  292. };
  293. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
  294. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
  295. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
  296. }
  297. // end catch_interfaces_testcase.h
  298. // start catch_stringref.h
  299. #include <cstddef>
  300. #include <string>
  301. #include <iosfwd>
  302. namespace Catch {
  303. class StringData;
  304. /// A non-owning string class (similar to the forthcoming std::string_view)
  305. /// Note that, because a StringRef may be a substring of another string,
  306. /// it may not be null terminated. c_str() must return a null terminated
  307. /// string, however, and so the StringRef will internally take ownership
  308. /// (taking a copy), if necessary. In theory this ownership is not externally
  309. /// visible - but it does mean (substring) StringRefs should not be shared between
  310. /// threads.
  311. class StringRef {
  312. public:
  313. using size_type = std::size_t;
  314. private:
  315. friend struct StringRefTestAccess;
  316. char const* m_start;
  317. size_type m_size;
  318. char* m_data = nullptr;
  319. void takeOwnership();
  320. static constexpr char const* const s_empty = "";
  321. public: // construction/ assignment
  322. StringRef() noexcept
  323. : StringRef( s_empty, 0 )
  324. {}
  325. StringRef( StringRef const& other ) noexcept
  326. : m_start( other.m_start ),
  327. m_size( other.m_size )
  328. {}
  329. StringRef( StringRef&& other ) noexcept
  330. : m_start( other.m_start ),
  331. m_size( other.m_size ),
  332. m_data( other.m_data )
  333. {
  334. other.m_data = nullptr;
  335. }
  336. StringRef( char const* rawChars ) noexcept;
  337. StringRef( char const* rawChars, size_type size ) noexcept
  338. : m_start( rawChars ),
  339. m_size( size )
  340. {}
  341. StringRef( std::string const& stdString ) noexcept
  342. : m_start( stdString.c_str() ),
  343. m_size( stdString.size() )
  344. {}
  345. ~StringRef() noexcept {
  346. delete[] m_data;
  347. }
  348. auto operator = ( StringRef const &other ) noexcept -> StringRef& {
  349. delete[] m_data;
  350. m_data = nullptr;
  351. m_start = other.m_start;
  352. m_size = other.m_size;
  353. return *this;
  354. }
  355. operator std::string() const;
  356. void swap( StringRef& other ) noexcept;
  357. public: // operators
  358. auto operator == ( StringRef const& other ) const noexcept -> bool;
  359. auto operator != ( StringRef const& other ) const noexcept -> bool;
  360. auto operator[] ( size_type index ) const noexcept -> char;
  361. public: // named queries
  362. auto empty() const noexcept -> bool {
  363. return m_size == 0;
  364. }
  365. auto size() const noexcept -> size_type {
  366. return m_size;
  367. }
  368. auto numberOfCharacters() const noexcept -> size_type;
  369. auto c_str() const -> char const*;
  370. public: // substrings and searches
  371. auto substr( size_type start, size_type size ) const noexcept -> StringRef;
  372. // Returns the current start pointer.
  373. // Note that the pointer can change when if the StringRef is a substring
  374. auto currentData() const noexcept -> char const*;
  375. private: // ownership queries - may not be consistent between calls
  376. auto isOwned() const noexcept -> bool;
  377. auto isSubstring() const noexcept -> bool;
  378. };
  379. auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string;
  380. auto operator + ( StringRef const& lhs, char const* rhs ) -> std::string;
  381. auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string;
  382. auto operator += ( std::string& lhs, StringRef const& sr ) -> std::string&;
  383. auto operator << ( std::ostream& os, StringRef const& sr ) -> std::ostream&;
  384. inline auto operator "" _sr( char const* rawChars, std::size_t size ) noexcept -> StringRef {
  385. return StringRef( rawChars, size );
  386. }
  387. } // namespace Catch
  388. // end catch_stringref.h
  389. namespace Catch {
  390. template<typename C>
  391. class TestInvokerAsMethod : public ITestInvoker {
  392. void (C::*m_testAsMethod)();
  393. public:
  394. TestInvokerAsMethod( void (C::*testAsMethod)() ) noexcept : m_testAsMethod( testAsMethod ) {}
  395. void invoke() const override {
  396. C obj;
  397. (obj.*m_testAsMethod)();
  398. }
  399. };
  400. auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker*;
  401. template<typename C>
  402. auto makeTestInvoker( void (C::*testAsMethod)() ) noexcept -> ITestInvoker* {
  403. return new(std::nothrow) TestInvokerAsMethod<C>( testAsMethod );
  404. }
  405. struct NameAndTags {
  406. NameAndTags( StringRef const& name_ = StringRef(), StringRef const& tags_ = StringRef() ) noexcept;
  407. StringRef name;
  408. StringRef tags;
  409. };
  410. struct AutoReg : NonCopyable {
  411. AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept;
  412. ~AutoReg();
  413. };
  414. } // end namespace Catch
  415. #define INTERNAL_CATCH_EXPAND1(param) INTERNAL_CATCH_EXPAND2(param)
  416. #define INTERNAL_CATCH_EXPAND2(...) INTERNAL_CATCH_NO## __VA_ARGS__
  417. #define INTERNAL_CATCH_DEF(...) INTERNAL_CATCH_DEF __VA_ARGS__
  418. #define INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
  419. #if defined(CATCH_CONFIG_DISABLE)
  420. #define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( TestName, ... ) \
  421. static void TestName()
  422. #define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( TestName, ClassName, ... ) \
  423. namespace{ \
  424. struct TestName : INTERNAL_CATCH_EXPAND1(INTERNAL_CATCH_DEF ClassName) { \
  425. void test(); \
  426. }; \
  427. } \
  428. void TestName::test()
  429. #endif
  430. ///////////////////////////////////////////////////////////////////////////////
  431. #define INTERNAL_CATCH_TESTCASE2( TestName, ... ) \
  432. static void TestName(); \
  433. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  434. namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &TestName ), CATCH_INTERNAL_LINEINFO, "", Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
  435. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  436. static void TestName()
  437. #define INTERNAL_CATCH_TESTCASE( ... ) \
  438. INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), __VA_ARGS__ )
  439. ///////////////////////////////////////////////////////////////////////////////
  440. #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \
  441. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  442. namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &QualifiedMethod ), CATCH_INTERNAL_LINEINFO, "&" #QualifiedMethod, Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
  443. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  444. ///////////////////////////////////////////////////////////////////////////////
  445. #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestName, ClassName, ... )\
  446. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  447. namespace{ \
  448. struct TestName : INTERNAL_CATCH_EXPAND1(INTERNAL_CATCH_DEF ClassName) { \
  449. void test(); \
  450. }; \
  451. Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( Catch::makeTestInvoker( &TestName::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
  452. } \
  453. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  454. void TestName::test()
  455. #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \
  456. INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, __VA_ARGS__ )
  457. ///////////////////////////////////////////////////////////////////////////////
  458. #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \
  459. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  460. Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( Function ), CATCH_INTERNAL_LINEINFO, "", Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
  461. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  462. // end catch_test_registry.h
  463. // start catch_capture.hpp
  464. // start catch_assertionhandler.h
  465. // start catch_assertioninfo.h
  466. // start catch_result_type.h
  467. namespace Catch {
  468. // ResultWas::OfType enum
  469. struct ResultWas { enum OfType {
  470. Unknown = -1,
  471. Ok = 0,
  472. Info = 1,
  473. Warning = 2,
  474. FailureBit = 0x10,
  475. ExpressionFailed = FailureBit | 1,
  476. ExplicitFailure = FailureBit | 2,
  477. Exception = 0x100 | FailureBit,
  478. ThrewException = Exception | 1,
  479. DidntThrowException = Exception | 2,
  480. FatalErrorCondition = 0x200 | FailureBit
  481. }; };
  482. bool isOk( ResultWas::OfType resultType );
  483. bool isJustInfo( int flags );
  484. // ResultDisposition::Flags enum
  485. struct ResultDisposition { enum Flags {
  486. Normal = 0x01,
  487. ContinueOnFailure = 0x02, // Failures fail test, but execution continues
  488. FalseTest = 0x04, // Prefix expression with !
  489. SuppressFail = 0x08 // Failures are reported but do not fail the test
  490. }; };
  491. ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs );
  492. bool shouldContinueOnFailure( int flags );
  493. inline bool isFalseTest( int flags ) { return ( flags & ResultDisposition::FalseTest ) != 0; }
  494. bool shouldSuppressFailure( int flags );
  495. } // end namespace Catch
  496. // end catch_result_type.h
  497. namespace Catch {
  498. struct AssertionInfo
  499. {
  500. StringRef macroName;
  501. SourceLineInfo lineInfo;
  502. StringRef capturedExpression;
  503. ResultDisposition::Flags resultDisposition;
  504. // We want to delete this constructor but a compiler bug in 4.8 means
  505. // the struct is then treated as non-aggregate
  506. //AssertionInfo() = delete;
  507. };
  508. } // end namespace Catch
  509. // end catch_assertioninfo.h
  510. // start catch_decomposer.h
  511. // start catch_tostring.h
  512. #include <vector>
  513. #include <cstddef>
  514. #include <type_traits>
  515. #include <string>
  516. // start catch_stream.h
  517. #include <iosfwd>
  518. #include <cstddef>
  519. #include <ostream>
  520. namespace Catch {
  521. std::ostream& cout();
  522. std::ostream& cerr();
  523. std::ostream& clog();
  524. class StringRef;
  525. struct IStream {
  526. virtual ~IStream();
  527. virtual std::ostream& stream() const = 0;
  528. };
  529. auto makeStream( StringRef const &filename ) -> IStream const*;
  530. class ReusableStringStream {
  531. std::size_t m_index;
  532. std::ostream* m_oss;
  533. public:
  534. ReusableStringStream();
  535. ~ReusableStringStream();
  536. auto str() const -> std::string;
  537. template<typename T>
  538. auto operator << ( T const& value ) -> ReusableStringStream& {
  539. *m_oss << value;
  540. return *this;
  541. }
  542. auto get() -> std::ostream& { return *m_oss; }
  543. static void cleanup();
  544. };
  545. }
  546. // end catch_stream.h
  547. #ifdef __OBJC__
  548. // start catch_objc_arc.hpp
  549. #import <Foundation/Foundation.h>
  550. #ifdef __has_feature
  551. #define CATCH_ARC_ENABLED __has_feature(objc_arc)
  552. #else
  553. #define CATCH_ARC_ENABLED 0
  554. #endif
  555. void arcSafeRelease( NSObject* obj );
  556. id performOptionalSelector( id obj, SEL sel );
  557. #if !CATCH_ARC_ENABLED
  558. inline void arcSafeRelease( NSObject* obj ) {
  559. [obj release];
  560. }
  561. inline id performOptionalSelector( id obj, SEL sel ) {
  562. if( [obj respondsToSelector: sel] )
  563. return [obj performSelector: sel];
  564. return nil;
  565. }
  566. #define CATCH_UNSAFE_UNRETAINED
  567. #define CATCH_ARC_STRONG
  568. #else
  569. inline void arcSafeRelease( NSObject* ){}
  570. inline id performOptionalSelector( id obj, SEL sel ) {
  571. #ifdef __clang__
  572. #pragma clang diagnostic push
  573. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  574. #endif
  575. if( [obj respondsToSelector: sel] )
  576. return [obj performSelector: sel];
  577. #ifdef __clang__
  578. #pragma clang diagnostic pop
  579. #endif
  580. return nil;
  581. }
  582. #define CATCH_UNSAFE_UNRETAINED __unsafe_unretained
  583. #define CATCH_ARC_STRONG __strong
  584. #endif
  585. // end catch_objc_arc.hpp
  586. #endif
  587. #ifdef _MSC_VER
  588. #pragma warning(push)
  589. #pragma warning(disable:4180) // We attempt to stream a function (address) by const&, which MSVC complains about but is harmless
  590. #endif
  591. // We need a dummy global operator<< so we can bring it into Catch namespace later
  592. struct Catch_global_namespace_dummy {};
  593. std::ostream& operator<<(std::ostream&, Catch_global_namespace_dummy);
  594. namespace Catch {
  595. // Bring in operator<< from global namespace into Catch namespace
  596. using ::operator<<;
  597. namespace Detail {
  598. extern const std::string unprintableString;
  599. std::string rawMemoryToString( const void *object, std::size_t size );
  600. template<typename T>
  601. std::string rawMemoryToString( const T& object ) {
  602. return rawMemoryToString( &object, sizeof(object) );
  603. }
  604. template<typename T>
  605. class IsStreamInsertable {
  606. template<typename SS, typename TT>
  607. static auto test(int)
  608. -> decltype(std::declval<SS&>() << std::declval<TT>(), std::true_type());
  609. template<typename, typename>
  610. static auto test(...)->std::false_type;
  611. public:
  612. static const bool value = decltype(test<std::ostream, const T&>(0))::value;
  613. };
  614. template<typename E>
  615. std::string convertUnknownEnumToString( E e );
  616. template<typename T>
  617. typename std::enable_if<
  618. !std::is_enum<T>::value && !std::is_base_of<std::exception, T>::value,
  619. std::string>::type convertUnstreamable( T const& ) {
  620. return Detail::unprintableString;
  621. }
  622. template<typename T>
  623. typename std::enable_if<
  624. !std::is_enum<T>::value && std::is_base_of<std::exception, T>::value,
  625. std::string>::type convertUnstreamable(T const& ex) {
  626. return ex.what();
  627. }
  628. template<typename T>
  629. typename std::enable_if<
  630. std::is_enum<T>::value
  631. , std::string>::type convertUnstreamable( T const& value ) {
  632. return convertUnknownEnumToString( value );
  633. }
  634. #if defined(_MANAGED)
  635. //! Convert a CLR string to a utf8 std::string
  636. template<typename T>
  637. std::string clrReferenceToString( T^ ref ) {
  638. if (ref == nullptr)
  639. return std::string("null");
  640. auto bytes = System::Text::Encoding::UTF8->GetBytes(ref->ToString());
  641. cli::pin_ptr<System::Byte> p = &bytes[0];
  642. return std::string(reinterpret_cast<char const *>(p), bytes->Length);
  643. }
  644. #endif
  645. } // namespace Detail
  646. // If we decide for C++14, change these to enable_if_ts
  647. template <typename T, typename = void>
  648. struct StringMaker {
  649. template <typename Fake = T>
  650. static
  651. typename std::enable_if<::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
  652. convert(const Fake& value) {
  653. ReusableStringStream rss;
  654. // NB: call using the function-like syntax to avoid ambiguity with
  655. // user-defined templated operator<< under clang.
  656. rss.operator<<(value);
  657. return rss.str();
  658. }
  659. template <typename Fake = T>
  660. static
  661. typename std::enable_if<!::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
  662. convert( const Fake& value ) {
  663. #if !defined(CATCH_CONFIG_FALLBACK_STRINGIFIER)
  664. return Detail::convertUnstreamable(value);
  665. #else
  666. return CATCH_CONFIG_FALLBACK_STRINGIFIER(value);
  667. #endif
  668. }
  669. };
  670. namespace Detail {
  671. // This function dispatches all stringification requests inside of Catch.
  672. // Should be preferably called fully qualified, like ::Catch::Detail::stringify
  673. template <typename T>
  674. std::string stringify(const T& e) {
  675. return ::Catch::StringMaker<typename std::remove_cv<typename std::remove_reference<T>::type>::type>::convert(e);
  676. }
  677. template<typename E>
  678. std::string convertUnknownEnumToString( E e ) {
  679. return ::Catch::Detail::stringify(static_cast<typename std::underlying_type<E>::type>(e));
  680. }
  681. #if defined(_MANAGED)
  682. template <typename T>
  683. std::string stringify( T^ e ) {
  684. return ::Catch::StringMaker<T^>::convert(e);
  685. }
  686. #endif
  687. } // namespace Detail
  688. // Some predefined specializations
  689. template<>
  690. struct StringMaker<std::string> {
  691. static std::string convert(const std::string& str);
  692. };
  693. #ifdef CATCH_CONFIG_WCHAR
  694. template<>
  695. struct StringMaker<std::wstring> {
  696. static std::string convert(const std::wstring& wstr);
  697. };
  698. #endif
  699. template<>
  700. struct StringMaker<char const *> {
  701. static std::string convert(char const * str);
  702. };
  703. template<>
  704. struct StringMaker<char *> {
  705. static std::string convert(char * str);
  706. };
  707. #ifdef CATCH_CONFIG_WCHAR
  708. template<>
  709. struct StringMaker<wchar_t const *> {
  710. static std::string convert(wchar_t const * str);
  711. };
  712. template<>
  713. struct StringMaker<wchar_t *> {
  714. static std::string convert(wchar_t * str);
  715. };
  716. #endif
  717. // TBD: Should we use `strnlen` to ensure that we don't go out of the buffer,
  718. // while keeping string semantics?
  719. template<int SZ>
  720. struct StringMaker<char[SZ]> {
  721. static std::string convert(char const* str) {
  722. return ::Catch::Detail::stringify(std::string{ str });
  723. }
  724. };
  725. template<int SZ>
  726. struct StringMaker<signed char[SZ]> {
  727. static std::string convert(signed char const* str) {
  728. return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) });
  729. }
  730. };
  731. template<int SZ>
  732. struct StringMaker<unsigned char[SZ]> {
  733. static std::string convert(unsigned char const* str) {
  734. return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) });
  735. }
  736. };
  737. template<>
  738. struct StringMaker<int> {
  739. static std::string convert(int value);
  740. };
  741. template<>
  742. struct StringMaker<long> {
  743. static std::string convert(long value);
  744. };
  745. template<>
  746. struct StringMaker<long long> {
  747. static std::string convert(long long value);
  748. };
  749. template<>
  750. struct StringMaker<unsigned int> {
  751. static std::string convert(unsigned int value);
  752. };
  753. template<>
  754. struct StringMaker<unsigned long> {
  755. static std::string convert(unsigned long value);
  756. };
  757. template<>
  758. struct StringMaker<unsigned long long> {
  759. static std::string convert(unsigned long long value);
  760. };
  761. template<>
  762. struct StringMaker<bool> {
  763. static std::string convert(bool b);
  764. };
  765. template<>
  766. struct StringMaker<char> {
  767. static std::string convert(char c);
  768. };
  769. template<>
  770. struct StringMaker<signed char> {
  771. static std::string convert(signed char c);
  772. };
  773. template<>
  774. struct StringMaker<unsigned char> {
  775. static std::string convert(unsigned char c);
  776. };
  777. template<>
  778. struct StringMaker<std::nullptr_t> {
  779. static std::string convert(std::nullptr_t);
  780. };
  781. template<>
  782. struct StringMaker<float> {
  783. static std::string convert(float value);
  784. };
  785. template<>
  786. struct StringMaker<double> {
  787. static std::string convert(double value);
  788. };
  789. template <typename T>
  790. struct StringMaker<T*> {
  791. template <typename U>
  792. static std::string convert(U* p) {
  793. if (p) {
  794. return ::Catch::Detail::rawMemoryToString(p);
  795. } else {
  796. return "nullptr";
  797. }
  798. }
  799. };
  800. template <typename R, typename C>
  801. struct StringMaker<R C::*> {
  802. static std::string convert(R C::* p) {
  803. if (p) {
  804. return ::Catch::Detail::rawMemoryToString(p);
  805. } else {
  806. return "nullptr";
  807. }
  808. }
  809. };
  810. #if defined(_MANAGED)
  811. template <typename T>
  812. struct StringMaker<T^> {
  813. static std::string convert( T^ ref ) {
  814. return ::Catch::Detail::clrReferenceToString(ref);
  815. }
  816. };
  817. #endif
  818. namespace Detail {
  819. template<typename InputIterator>
  820. std::string rangeToString(InputIterator first, InputIterator last) {
  821. ReusableStringStream rss;
  822. rss << "{ ";
  823. if (first != last) {
  824. rss << ::Catch::Detail::stringify(*first);
  825. for (++first; first != last; ++first)
  826. rss << ", " << ::Catch::Detail::stringify(*first);
  827. }
  828. rss << " }";
  829. return rss.str();
  830. }
  831. }
  832. #ifdef __OBJC__
  833. template<>
  834. struct StringMaker<NSString*> {
  835. static std::string convert(NSString * nsstring) {
  836. if (!nsstring)
  837. return "nil";
  838. return std::string("@") + [nsstring UTF8String];
  839. }
  840. };
  841. template<>
  842. struct StringMaker<NSObject*> {
  843. static std::string convert(NSObject* nsObject) {
  844. return ::Catch::Detail::stringify([nsObject description]);
  845. }
  846. };
  847. namespace Detail {
  848. inline std::string stringify( NSString* nsstring ) {
  849. return StringMaker<NSString*>::convert( nsstring );
  850. }
  851. } // namespace Detail
  852. #endif // __OBJC__
  853. } // namespace Catch
  854. //////////////////////////////////////////////////////
  855. // Separate std-lib types stringification, so it can be selectively enabled
  856. // This means that we do not bring in
  857. #if defined(CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS)
  858. # define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
  859. # define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
  860. # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  861. #endif
  862. // Separate std::pair specialization
  863. #if defined(CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER)
  864. #include <utility>
  865. namespace Catch {
  866. template<typename T1, typename T2>
  867. struct StringMaker<std::pair<T1, T2> > {
  868. static std::string convert(const std::pair<T1, T2>& pair) {
  869. ReusableStringStream rss;
  870. rss << "{ "
  871. << ::Catch::Detail::stringify(pair.first)
  872. << ", "
  873. << ::Catch::Detail::stringify(pair.second)
  874. << " }";
  875. return rss.str();
  876. }
  877. };
  878. }
  879. #endif // CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
  880. // Separate std::tuple specialization
  881. #if defined(CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER)
  882. #include <tuple>
  883. namespace Catch {
  884. namespace Detail {
  885. template<
  886. typename Tuple,
  887. std::size_t N = 0,
  888. bool = (N < std::tuple_size<Tuple>::value)
  889. >
  890. struct TupleElementPrinter {
  891. static void print(const Tuple& tuple, std::ostream& os) {
  892. os << (N ? ", " : " ")
  893. << ::Catch::Detail::stringify(std::get<N>(tuple));
  894. TupleElementPrinter<Tuple, N + 1>::print(tuple, os);
  895. }
  896. };
  897. template<
  898. typename Tuple,
  899. std::size_t N
  900. >
  901. struct TupleElementPrinter<Tuple, N, false> {
  902. static void print(const Tuple&, std::ostream&) {}
  903. };
  904. }
  905. template<typename ...Types>
  906. struct StringMaker<std::tuple<Types...>> {
  907. static std::string convert(const std::tuple<Types...>& tuple) {
  908. ReusableStringStream rss;
  909. rss << '{';
  910. Detail::TupleElementPrinter<std::tuple<Types...>>::print(tuple, rss.get());
  911. rss << " }";
  912. return rss.str();
  913. }
  914. };
  915. }
  916. #endif // CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
  917. namespace Catch {
  918. struct not_this_one {}; // Tag type for detecting which begin/ end are being selected
  919. // Import begin/ end from std here so they are considered alongside the fallback (...) overloads in this namespace
  920. using std::begin;
  921. using std::end;
  922. not_this_one begin( ... );
  923. not_this_one end( ... );
  924. template <typename T>
  925. struct is_range {
  926. static const bool value =
  927. !std::is_same<decltype(begin(std::declval<T>())), not_this_one>::value &&
  928. !std::is_same<decltype(end(std::declval<T>())), not_this_one>::value;
  929. };
  930. #if defined(_MANAGED) // Managed types are never ranges
  931. template <typename T>
  932. struct is_range<T^> {
  933. static const bool value = false;
  934. };
  935. #endif
  936. template<typename Range>
  937. std::string rangeToString( Range const& range ) {
  938. return ::Catch::Detail::rangeToString( begin( range ), end( range ) );
  939. }
  940. // Handle vector<bool> specially
  941. template<typename Allocator>
  942. std::string rangeToString( std::vector<bool, Allocator> const& v ) {
  943. ReusableStringStream rss;
  944. rss << "{ ";
  945. bool first = true;
  946. for( bool b : v ) {
  947. if( first )
  948. first = false;
  949. else
  950. rss << ", ";
  951. rss << ::Catch::Detail::stringify( b );
  952. }
  953. rss << " }";
  954. return rss.str();
  955. }
  956. template<typename R>
  957. struct StringMaker<R, typename std::enable_if<is_range<R>::value && !::Catch::Detail::IsStreamInsertable<R>::value>::type> {
  958. static std::string convert( R const& range ) {
  959. return rangeToString( range );
  960. }
  961. };
  962. template <typename T, int SZ>
  963. struct StringMaker<T[SZ]> {
  964. static std::string convert(T const(&arr)[SZ]) {
  965. return rangeToString(arr);
  966. }
  967. };
  968. } // namespace Catch
  969. // Separate std::chrono::duration specialization
  970. #if defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  971. #include <ctime>
  972. #include <ratio>
  973. #include <chrono>
  974. namespace Catch {
  975. template <class Ratio>
  976. struct ratio_string {
  977. static std::string symbol();
  978. };
  979. template <class Ratio>
  980. std::string ratio_string<Ratio>::symbol() {
  981. Catch::ReusableStringStream rss;
  982. rss << '[' << Ratio::num << '/'
  983. << Ratio::den << ']';
  984. return rss.str();
  985. }
  986. template <>
  987. struct ratio_string<std::atto> {
  988. static std::string symbol();
  989. };
  990. template <>
  991. struct ratio_string<std::femto> {
  992. static std::string symbol();
  993. };
  994. template <>
  995. struct ratio_string<std::pico> {
  996. static std::string symbol();
  997. };
  998. template <>
  999. struct ratio_string<std::nano> {
  1000. static std::string symbol();
  1001. };
  1002. template <>
  1003. struct ratio_string<std::micro> {
  1004. static std::string symbol();
  1005. };
  1006. template <>
  1007. struct ratio_string<std::milli> {
  1008. static std::string symbol();
  1009. };
  1010. ////////////
  1011. // std::chrono::duration specializations
  1012. template<typename Value, typename Ratio>
  1013. struct StringMaker<std::chrono::duration<Value, Ratio>> {
  1014. static std::string convert(std::chrono::duration<Value, Ratio> const& duration) {
  1015. ReusableStringStream rss;
  1016. rss << duration.count() << ' ' << ratio_string<Ratio>::symbol() << 's';
  1017. return rss.str();
  1018. }
  1019. };
  1020. template<typename Value>
  1021. struct StringMaker<std::chrono::duration<Value, std::ratio<1>>> {
  1022. static std::string convert(std::chrono::duration<Value, std::ratio<1>> const& duration) {
  1023. ReusableStringStream rss;
  1024. rss << duration.count() << " s";
  1025. return rss.str();
  1026. }
  1027. };
  1028. template<typename Value>
  1029. struct StringMaker<std::chrono::duration<Value, std::ratio<60>>> {
  1030. static std::string convert(std::chrono::duration<Value, std::ratio<60>> const& duration) {
  1031. ReusableStringStream rss;
  1032. rss << duration.count() << " m";
  1033. return rss.str();
  1034. }
  1035. };
  1036. template<typename Value>
  1037. struct StringMaker<std::chrono::duration<Value, std::ratio<3600>>> {
  1038. static std::string convert(std::chrono::duration<Value, std::ratio<3600>> const& duration) {
  1039. ReusableStringStream rss;
  1040. rss << duration.count() << " h";
  1041. return rss.str();
  1042. }
  1043. };
  1044. ////////////
  1045. // std::chrono::time_point specialization
  1046. // Generic time_point cannot be specialized, only std::chrono::time_point<system_clock>
  1047. template<typename Clock, typename Duration>
  1048. struct StringMaker<std::chrono::time_point<Clock, Duration>> {
  1049. static std::string convert(std::chrono::time_point<Clock, Duration> const& time_point) {
  1050. return ::Catch::Detail::stringify(time_point.time_since_epoch()) + " since epoch";
  1051. }
  1052. };
  1053. // std::chrono::time_point<system_clock> specialization
  1054. template<typename Duration>
  1055. struct StringMaker<std::chrono::time_point<std::chrono::system_clock, Duration>> {
  1056. static std::string convert(std::chrono::time_point<std::chrono::system_clock, Duration> const& time_point) {
  1057. auto converted = std::chrono::system_clock::to_time_t(time_point);
  1058. #ifdef _MSC_VER
  1059. std::tm timeInfo = {};
  1060. gmtime_s(&timeInfo, &converted);
  1061. #else
  1062. std::tm* timeInfo = std::gmtime(&converted);
  1063. #endif
  1064. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  1065. char timeStamp[timeStampSize];
  1066. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  1067. #ifdef _MSC_VER
  1068. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  1069. #else
  1070. std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
  1071. #endif
  1072. return std::string(timeStamp);
  1073. }
  1074. };
  1075. }
  1076. #endif // CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  1077. #ifdef _MSC_VER
  1078. #pragma warning(pop)
  1079. #endif
  1080. // end catch_tostring.h
  1081. #include <iosfwd>
  1082. #ifdef _MSC_VER
  1083. #pragma warning(push)
  1084. #pragma warning(disable:4389) // '==' : signed/unsigned mismatch
  1085. #pragma warning(disable:4018) // more "signed/unsigned mismatch"
  1086. #pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform)
  1087. #pragma warning(disable:4180) // qualifier applied to function type has no meaning
  1088. #endif
  1089. namespace Catch {
  1090. struct ITransientExpression {
  1091. auto isBinaryExpression() const -> bool { return m_isBinaryExpression; }
  1092. auto getResult() const -> bool { return m_result; }
  1093. virtual void streamReconstructedExpression( std::ostream &os ) const = 0;
  1094. ITransientExpression( bool isBinaryExpression, bool result )
  1095. : m_isBinaryExpression( isBinaryExpression ),
  1096. m_result( result )
  1097. {}
  1098. // We don't actually need a virtual destructor, but many static analysers
  1099. // complain if it's not here :-(
  1100. virtual ~ITransientExpression();
  1101. bool m_isBinaryExpression;
  1102. bool m_result;
  1103. };
  1104. void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs );
  1105. template<typename LhsT, typename RhsT>
  1106. class BinaryExpr : public ITransientExpression {
  1107. LhsT m_lhs;
  1108. StringRef m_op;
  1109. RhsT m_rhs;
  1110. void streamReconstructedExpression( std::ostream &os ) const override {
  1111. formatReconstructedExpression
  1112. ( os, Catch::Detail::stringify( m_lhs ), m_op, Catch::Detail::stringify( m_rhs ) );
  1113. }
  1114. public:
  1115. BinaryExpr( bool comparisonResult, LhsT lhs, StringRef op, RhsT rhs )
  1116. : ITransientExpression{ true, comparisonResult },
  1117. m_lhs( lhs ),
  1118. m_op( op ),
  1119. m_rhs( rhs )
  1120. {}
  1121. };
  1122. template<typename LhsT>
  1123. class UnaryExpr : public ITransientExpression {
  1124. LhsT m_lhs;
  1125. void streamReconstructedExpression( std::ostream &os ) const override {
  1126. os << Catch::Detail::stringify( m_lhs );
  1127. }
  1128. public:
  1129. explicit UnaryExpr( LhsT lhs )
  1130. : ITransientExpression{ false, lhs ? true : false },
  1131. m_lhs( lhs )
  1132. {}
  1133. };
  1134. // Specialised comparison functions to handle equality comparisons between ints and pointers (NULL deduces as an int)
  1135. template<typename LhsT, typename RhsT>
  1136. auto compareEqual( LhsT const& lhs, RhsT const& rhs ) -> bool { return static_cast<bool>(lhs == rhs); }
  1137. template<typename T>
  1138. auto compareEqual( T* const& lhs, int rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
  1139. template<typename T>
  1140. auto compareEqual( T* const& lhs, long rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
  1141. template<typename T>
  1142. auto compareEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
  1143. template<typename T>
  1144. auto compareEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
  1145. template<typename LhsT, typename RhsT>
  1146. auto compareNotEqual( LhsT const& lhs, RhsT&& rhs ) -> bool { return static_cast<bool>(lhs != rhs); }
  1147. template<typename T>
  1148. auto compareNotEqual( T* const& lhs, int rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
  1149. template<typename T>
  1150. auto compareNotEqual( T* const& lhs, long rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
  1151. template<typename T>
  1152. auto compareNotEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
  1153. template<typename T>
  1154. auto compareNotEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
  1155. template<typename LhsT>
  1156. class ExprLhs {
  1157. LhsT m_lhs;
  1158. public:
  1159. explicit ExprLhs( LhsT lhs ) : m_lhs( lhs ) {}
  1160. template<typename RhsT>
  1161. auto operator == ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1162. return { compareEqual( m_lhs, rhs ), m_lhs, "==", rhs };
  1163. }
  1164. auto operator == ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
  1165. return { m_lhs == rhs, m_lhs, "==", rhs };
  1166. }
  1167. template<typename RhsT>
  1168. auto operator != ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1169. return { compareNotEqual( m_lhs, rhs ), m_lhs, "!=", rhs };
  1170. }
  1171. auto operator != ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
  1172. return { m_lhs != rhs, m_lhs, "!=", rhs };
  1173. }
  1174. template<typename RhsT>
  1175. auto operator > ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1176. return { static_cast<bool>(m_lhs > rhs), m_lhs, ">", rhs };
  1177. }
  1178. template<typename RhsT>
  1179. auto operator < ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1180. return { static_cast<bool>(m_lhs < rhs), m_lhs, "<", rhs };
  1181. }
  1182. template<typename RhsT>
  1183. auto operator >= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1184. return { static_cast<bool>(m_lhs >= rhs), m_lhs, ">=", rhs };
  1185. }
  1186. template<typename RhsT>
  1187. auto operator <= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1188. return { static_cast<bool>(m_lhs <= rhs), m_lhs, "<=", rhs };
  1189. }
  1190. auto makeUnaryExpr() const -> UnaryExpr<LhsT> {
  1191. return UnaryExpr<LhsT>{ m_lhs };
  1192. }
  1193. };
  1194. void handleExpression( ITransientExpression const& expr );
  1195. template<typename T>
  1196. void handleExpression( ExprLhs<T> const& expr ) {
  1197. handleExpression( expr.makeUnaryExpr() );
  1198. }
  1199. struct Decomposer {
  1200. template<typename T>
  1201. auto operator <= ( T const& lhs ) -> ExprLhs<T const&> {
  1202. return ExprLhs<T const&>{ lhs };
  1203. }
  1204. auto operator <=( bool value ) -> ExprLhs<bool> {
  1205. return ExprLhs<bool>{ value };
  1206. }
  1207. };
  1208. } // end namespace Catch
  1209. #ifdef _MSC_VER
  1210. #pragma warning(pop)
  1211. #endif
  1212. // end catch_decomposer.h
  1213. // start catch_interfaces_capture.h
  1214. #include <string>
  1215. namespace Catch {
  1216. class AssertionResult;
  1217. struct AssertionInfo;
  1218. struct SectionInfo;
  1219. struct SectionEndInfo;
  1220. struct MessageInfo;
  1221. struct Counts;
  1222. struct BenchmarkInfo;
  1223. struct BenchmarkStats;
  1224. struct AssertionReaction;
  1225. struct ITransientExpression;
  1226. struct IResultCapture {
  1227. virtual ~IResultCapture();
  1228. virtual bool sectionStarted( SectionInfo const& sectionInfo,
  1229. Counts& assertions ) = 0;
  1230. virtual void sectionEnded( SectionEndInfo const& endInfo ) = 0;
  1231. virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) = 0;
  1232. virtual void benchmarkStarting( BenchmarkInfo const& info ) = 0;
  1233. virtual void benchmarkEnded( BenchmarkStats const& stats ) = 0;
  1234. virtual void pushScopedMessage( MessageInfo const& message ) = 0;
  1235. virtual void popScopedMessage( MessageInfo const& message ) = 0;
  1236. virtual void handleFatalErrorCondition( StringRef message ) = 0;
  1237. virtual void handleExpr
  1238. ( AssertionInfo const& info,
  1239. ITransientExpression const& expr,
  1240. AssertionReaction& reaction ) = 0;
  1241. virtual void handleMessage
  1242. ( AssertionInfo const& info,
  1243. ResultWas::OfType resultType,
  1244. StringRef const& message,
  1245. AssertionReaction& reaction ) = 0;
  1246. virtual void handleUnexpectedExceptionNotThrown
  1247. ( AssertionInfo const& info,
  1248. AssertionReaction& reaction ) = 0;
  1249. virtual void handleUnexpectedInflightException
  1250. ( AssertionInfo const& info,
  1251. std::string const& message,
  1252. AssertionReaction& reaction ) = 0;
  1253. virtual void handleIncomplete
  1254. ( AssertionInfo const& info ) = 0;
  1255. virtual void handleNonExpr
  1256. ( AssertionInfo const &info,
  1257. ResultWas::OfType resultType,
  1258. AssertionReaction &reaction ) = 0;
  1259. virtual bool lastAssertionPassed() = 0;
  1260. virtual void assertionPassed() = 0;
  1261. // Deprecated, do not use:
  1262. virtual std::string getCurrentTestName() const = 0;
  1263. virtual const AssertionResult* getLastResult() const = 0;
  1264. virtual void exceptionEarlyReported() = 0;
  1265. };
  1266. IResultCapture& getResultCapture();
  1267. }
  1268. // end catch_interfaces_capture.h
  1269. namespace Catch {
  1270. struct TestFailureException{};
  1271. struct AssertionResultData;
  1272. struct IResultCapture;
  1273. class RunContext;
  1274. class LazyExpression {
  1275. friend class AssertionHandler;
  1276. friend struct AssertionStats;
  1277. friend class RunContext;
  1278. ITransientExpression const* m_transientExpression = nullptr;
  1279. bool m_isNegated;
  1280. public:
  1281. LazyExpression( bool isNegated );
  1282. LazyExpression( LazyExpression const& other );
  1283. LazyExpression& operator = ( LazyExpression const& ) = delete;
  1284. explicit operator bool() const;
  1285. friend auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream&;
  1286. };
  1287. struct AssertionReaction {
  1288. bool shouldDebugBreak = false;
  1289. bool shouldThrow = false;
  1290. };
  1291. class AssertionHandler {
  1292. AssertionInfo m_assertionInfo;
  1293. AssertionReaction m_reaction;
  1294. bool m_completed = false;
  1295. IResultCapture& m_resultCapture;
  1296. public:
  1297. AssertionHandler
  1298. ( StringRef macroName,
  1299. SourceLineInfo const& lineInfo,
  1300. StringRef capturedExpression,
  1301. ResultDisposition::Flags resultDisposition );
  1302. ~AssertionHandler() {
  1303. if ( !m_completed ) {
  1304. m_resultCapture.handleIncomplete( m_assertionInfo );
  1305. }
  1306. }
  1307. template<typename T>
  1308. void handleExpr( ExprLhs<T> const& expr ) {
  1309. handleExpr( expr.makeUnaryExpr() );
  1310. }
  1311. void handleExpr( ITransientExpression const& expr );
  1312. void handleMessage(ResultWas::OfType resultType, StringRef const& message);
  1313. void handleExceptionThrownAsExpected();
  1314. void handleUnexpectedExceptionNotThrown();
  1315. void handleExceptionNotThrownAsExpected();
  1316. void handleThrowingCallSkipped();
  1317. void handleUnexpectedInflightException();
  1318. void complete();
  1319. void setCompleted();
  1320. // query
  1321. auto allowThrows() const -> bool;
  1322. };
  1323. void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef matcherString );
  1324. } // namespace Catch
  1325. // end catch_assertionhandler.h
  1326. // start catch_message.h
  1327. #include <string>
  1328. namespace Catch {
  1329. struct MessageInfo {
  1330. MessageInfo( std::string const& _macroName,
  1331. SourceLineInfo const& _lineInfo,
  1332. ResultWas::OfType _type );
  1333. std::string macroName;
  1334. std::string message;
  1335. SourceLineInfo lineInfo;
  1336. ResultWas::OfType type;
  1337. unsigned int sequence;
  1338. bool operator == ( MessageInfo const& other ) const;
  1339. bool operator < ( MessageInfo const& other ) const;
  1340. private:
  1341. static unsigned int globalCount;
  1342. };
  1343. struct MessageStream {
  1344. template<typename T>
  1345. MessageStream& operator << ( T const& value ) {
  1346. m_stream << value;
  1347. return *this;
  1348. }
  1349. ReusableStringStream m_stream;
  1350. };
  1351. struct MessageBuilder : MessageStream {
  1352. MessageBuilder( std::string const& macroName,
  1353. SourceLineInfo const& lineInfo,
  1354. ResultWas::OfType type );
  1355. template<typename T>
  1356. MessageBuilder& operator << ( T const& value ) {
  1357. m_stream << value;
  1358. return *this;
  1359. }
  1360. MessageInfo m_info;
  1361. };
  1362. class ScopedMessage {
  1363. public:
  1364. explicit ScopedMessage( MessageBuilder const& builder );
  1365. ~ScopedMessage();
  1366. MessageInfo m_info;
  1367. };
  1368. } // end namespace Catch
  1369. // end catch_message.h
  1370. #if !defined(CATCH_CONFIG_DISABLE)
  1371. #if !defined(CATCH_CONFIG_DISABLE_STRINGIFICATION)
  1372. #define CATCH_INTERNAL_STRINGIFY(...) #__VA_ARGS__
  1373. #else
  1374. #define CATCH_INTERNAL_STRINGIFY(...) "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION"
  1375. #endif
  1376. #if defined(CATCH_CONFIG_FAST_COMPILE)
  1377. ///////////////////////////////////////////////////////////////////////////////
  1378. // Another way to speed-up compilation is to omit local try-catch for REQUIRE*
  1379. // macros.
  1380. #define INTERNAL_CATCH_TRY
  1381. #define INTERNAL_CATCH_CATCH( capturer )
  1382. #else // CATCH_CONFIG_FAST_COMPILE
  1383. #define INTERNAL_CATCH_TRY try
  1384. #define INTERNAL_CATCH_CATCH( handler ) catch(...) { handler.handleUnexpectedInflightException(); }
  1385. #endif
  1386. #define INTERNAL_CATCH_REACT( handler ) handler.complete();
  1387. ///////////////////////////////////////////////////////////////////////////////
  1388. #define INTERNAL_CATCH_TEST( macroName, resultDisposition, ... ) \
  1389. do { \
  1390. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
  1391. INTERNAL_CATCH_TRY { \
  1392. CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
  1393. catchAssertionHandler.handleExpr( Catch::Decomposer() <= __VA_ARGS__ ); \
  1394. CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
  1395. } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
  1396. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1397. } 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
  1398. // The double negation silences MSVC's C4800 warning, the static_cast forces short-circuit evaluation if the type has overloaded &&.
  1399. ///////////////////////////////////////////////////////////////////////////////
  1400. #define INTERNAL_CATCH_IF( macroName, resultDisposition, ... ) \
  1401. INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
  1402. if( Catch::getResultCapture().lastAssertionPassed() )
  1403. ///////////////////////////////////////////////////////////////////////////////
  1404. #define INTERNAL_CATCH_ELSE( macroName, resultDisposition, ... ) \
  1405. INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
  1406. if( !Catch::getResultCapture().lastAssertionPassed() )
  1407. ///////////////////////////////////////////////////////////////////////////////
  1408. #define INTERNAL_CATCH_NO_THROW( macroName, resultDisposition, ... ) \
  1409. do { \
  1410. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
  1411. try { \
  1412. static_cast<void>(__VA_ARGS__); \
  1413. catchAssertionHandler.handleExceptionNotThrownAsExpected(); \
  1414. } \
  1415. catch( ... ) { \
  1416. catchAssertionHandler.handleUnexpectedInflightException(); \
  1417. } \
  1418. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1419. } while( false )
  1420. ///////////////////////////////////////////////////////////////////////////////
  1421. #define INTERNAL_CATCH_THROWS( macroName, resultDisposition, ... ) \
  1422. do { \
  1423. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition); \
  1424. if( catchAssertionHandler.allowThrows() ) \
  1425. try { \
  1426. static_cast<void>(__VA_ARGS__); \
  1427. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  1428. } \
  1429. catch( ... ) { \
  1430. catchAssertionHandler.handleExceptionThrownAsExpected(); \
  1431. } \
  1432. else \
  1433. catchAssertionHandler.handleThrowingCallSkipped(); \
  1434. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1435. } while( false )
  1436. ///////////////////////////////////////////////////////////////////////////////
  1437. #define INTERNAL_CATCH_THROWS_AS( macroName, exceptionType, resultDisposition, expr ) \
  1438. do { \
  1439. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType), resultDisposition ); \
  1440. if( catchAssertionHandler.allowThrows() ) \
  1441. try { \
  1442. static_cast<void>(expr); \
  1443. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  1444. } \
  1445. catch( exceptionType const& ) { \
  1446. catchAssertionHandler.handleExceptionThrownAsExpected(); \
  1447. } \
  1448. catch( ... ) { \
  1449. catchAssertionHandler.handleUnexpectedInflightException(); \
  1450. } \
  1451. else \
  1452. catchAssertionHandler.handleThrowingCallSkipped(); \
  1453. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1454. } while( false )
  1455. ///////////////////////////////////////////////////////////////////////////////
  1456. #define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, ... ) \
  1457. do { \
  1458. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, "", resultDisposition ); \
  1459. catchAssertionHandler.handleMessage( messageType, ( Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop() ).m_stream.str() ); \
  1460. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1461. } while( false )
  1462. ///////////////////////////////////////////////////////////////////////////////
  1463. #define INTERNAL_CATCH_INFO( macroName, log ) \
  1464. Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage )( Catch::MessageBuilder( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log );
  1465. ///////////////////////////////////////////////////////////////////////////////
  1466. // Although this is matcher-based, it can be used with just a string
  1467. #define INTERNAL_CATCH_THROWS_STR_MATCHES( macroName, resultDisposition, matcher, ... ) \
  1468. do { \
  1469. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  1470. if( catchAssertionHandler.allowThrows() ) \
  1471. try { \
  1472. static_cast<void>(__VA_ARGS__); \
  1473. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  1474. } \
  1475. catch( ... ) { \
  1476. Catch::handleExceptionMatchExpr( catchAssertionHandler, matcher, #matcher ); \
  1477. } \
  1478. else \
  1479. catchAssertionHandler.handleThrowingCallSkipped(); \
  1480. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1481. } while( false )
  1482. #endif // CATCH_CONFIG_DISABLE
  1483. // end catch_capture.hpp
  1484. // start catch_section.h
  1485. // start catch_section_info.h
  1486. // start catch_totals.h
  1487. #include <cstddef>
  1488. namespace Catch {
  1489. struct Counts {
  1490. Counts operator - ( Counts const& other ) const;
  1491. Counts& operator += ( Counts const& other );
  1492. std::size_t total() const;
  1493. bool allPassed() const;
  1494. bool allOk() const;
  1495. std::size_t passed = 0;
  1496. std::size_t failed = 0;
  1497. std::size_t failedButOk = 0;
  1498. };
  1499. struct Totals {
  1500. Totals operator - ( Totals const& other ) const;
  1501. Totals& operator += ( Totals const& other );
  1502. Totals delta( Totals const& prevTotals ) const;
  1503. int error = 0;
  1504. Counts assertions;
  1505. Counts testCases;
  1506. };
  1507. }
  1508. // end catch_totals.h
  1509. #include <string>
  1510. namespace Catch {
  1511. struct SectionInfo {
  1512. SectionInfo
  1513. ( SourceLineInfo const& _lineInfo,
  1514. std::string const& _name,
  1515. std::string const& _description = std::string() );
  1516. std::string name;
  1517. std::string description;
  1518. SourceLineInfo lineInfo;
  1519. };
  1520. struct SectionEndInfo {
  1521. SectionEndInfo( SectionInfo const& _sectionInfo, Counts const& _prevAssertions, double _durationInSeconds );
  1522. SectionInfo sectionInfo;
  1523. Counts prevAssertions;
  1524. double durationInSeconds;
  1525. };
  1526. } // end namespace Catch
  1527. // end catch_section_info.h
  1528. // start catch_timer.h
  1529. #include <cstdint>
  1530. namespace Catch {
  1531. auto getCurrentNanosecondsSinceEpoch() -> uint64_t;
  1532. auto getEstimatedClockResolution() -> uint64_t;
  1533. class Timer {
  1534. uint64_t m_nanoseconds = 0;
  1535. public:
  1536. void start();
  1537. auto getElapsedNanoseconds() const -> uint64_t;
  1538. auto getElapsedMicroseconds() const -> uint64_t;
  1539. auto getElapsedMilliseconds() const -> unsigned int;
  1540. auto getElapsedSeconds() const -> double;
  1541. };
  1542. } // namespace Catch
  1543. // end catch_timer.h
  1544. #include <string>
  1545. namespace Catch {
  1546. class Section : NonCopyable {
  1547. public:
  1548. Section( SectionInfo const& info );
  1549. ~Section();
  1550. // This indicates whether the section should be executed or not
  1551. explicit operator bool() const;
  1552. private:
  1553. SectionInfo m_info;
  1554. std::string m_name;
  1555. Counts m_assertions;
  1556. bool m_sectionIncluded;
  1557. Timer m_timer;
  1558. };
  1559. } // end namespace Catch
  1560. #define INTERNAL_CATCH_SECTION( ... ) \
  1561. if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) )
  1562. // end catch_section.h
  1563. // start catch_benchmark.h
  1564. #include <cstdint>
  1565. #include <string>
  1566. namespace Catch {
  1567. class BenchmarkLooper {
  1568. std::string m_name;
  1569. std::size_t m_count = 0;
  1570. std::size_t m_iterationsToRun = 1;
  1571. uint64_t m_resolution;
  1572. Timer m_timer;
  1573. static auto getResolution() -> uint64_t;
  1574. public:
  1575. // Keep most of this inline as it's on the code path that is being timed
  1576. BenchmarkLooper( StringRef name )
  1577. : m_name( name ),
  1578. m_resolution( getResolution() )
  1579. {
  1580. reportStart();
  1581. m_timer.start();
  1582. }
  1583. explicit operator bool() {
  1584. if( m_count < m_iterationsToRun )
  1585. return true;
  1586. return needsMoreIterations();
  1587. }
  1588. void increment() {
  1589. ++m_count;
  1590. }
  1591. void reportStart();
  1592. auto needsMoreIterations() -> bool;
  1593. };
  1594. } // end namespace Catch
  1595. #define BENCHMARK( name ) \
  1596. for( Catch::BenchmarkLooper looper( name ); looper; looper.increment() )
  1597. // end catch_benchmark.h
  1598. // start catch_interfaces_exception.h
  1599. // start catch_interfaces_registry_hub.h
  1600. #include <string>
  1601. #include <memory>
  1602. namespace Catch {
  1603. class TestCase;
  1604. struct ITestCaseRegistry;
  1605. struct IExceptionTranslatorRegistry;
  1606. struct IExceptionTranslator;
  1607. struct IReporterRegistry;
  1608. struct IReporterFactory;
  1609. struct ITagAliasRegistry;
  1610. class StartupExceptionRegistry;
  1611. using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
  1612. struct IRegistryHub {
  1613. virtual ~IRegistryHub();
  1614. virtual IReporterRegistry const& getReporterRegistry() const = 0;
  1615. virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0;
  1616. virtual ITagAliasRegistry const& getTagAliasRegistry() const = 0;
  1617. virtual IExceptionTranslatorRegistry& getExceptionTranslatorRegistry() = 0;
  1618. virtual StartupExceptionRegistry const& getStartupExceptionRegistry() const = 0;
  1619. };
  1620. struct IMutableRegistryHub {
  1621. virtual ~IMutableRegistryHub();
  1622. virtual void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) = 0;
  1623. virtual void registerListener( IReporterFactoryPtr const& factory ) = 0;
  1624. virtual void registerTest( TestCase const& testInfo ) = 0;
  1625. virtual void registerTranslator( const IExceptionTranslator* translator ) = 0;
  1626. virtual void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) = 0;
  1627. virtual void registerStartupException() noexcept = 0;
  1628. };
  1629. IRegistryHub& getRegistryHub();
  1630. IMutableRegistryHub& getMutableRegistryHub();
  1631. void cleanUp();
  1632. std::string translateActiveException();
  1633. }
  1634. // end catch_interfaces_registry_hub.h
  1635. #if defined(CATCH_CONFIG_DISABLE)
  1636. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( translatorName, signature) \
  1637. static std::string translatorName( signature )
  1638. #endif
  1639. #include <exception>
  1640. #include <string>
  1641. #include <vector>
  1642. namespace Catch {
  1643. using exceptionTranslateFunction = std::string(*)();
  1644. struct IExceptionTranslator;
  1645. using ExceptionTranslators = std::vector<std::unique_ptr<IExceptionTranslator const>>;
  1646. struct IExceptionTranslator {
  1647. virtual ~IExceptionTranslator();
  1648. virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const = 0;
  1649. };
  1650. struct IExceptionTranslatorRegistry {
  1651. virtual ~IExceptionTranslatorRegistry();
  1652. virtual std::string translateActiveException() const = 0;
  1653. };
  1654. class ExceptionTranslatorRegistrar {
  1655. template<typename T>
  1656. class ExceptionTranslator : public IExceptionTranslator {
  1657. public:
  1658. ExceptionTranslator( std::string(*translateFunction)( T& ) )
  1659. : m_translateFunction( translateFunction )
  1660. {}
  1661. std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const override {
  1662. try {
  1663. if( it == itEnd )
  1664. std::rethrow_exception(std::current_exception());
  1665. else
  1666. return (*it)->translate( it+1, itEnd );
  1667. }
  1668. catch( T& ex ) {
  1669. return m_translateFunction( ex );
  1670. }
  1671. }
  1672. protected:
  1673. std::string(*m_translateFunction)( T& );
  1674. };
  1675. public:
  1676. template<typename T>
  1677. ExceptionTranslatorRegistrar( std::string(*translateFunction)( T& ) ) {
  1678. getMutableRegistryHub().registerTranslator
  1679. ( new ExceptionTranslator<T>( translateFunction ) );
  1680. }
  1681. };
  1682. }
  1683. ///////////////////////////////////////////////////////////////////////////////
  1684. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION2( translatorName, signature ) \
  1685. static std::string translatorName( signature ); \
  1686. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  1687. namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &translatorName ); } \
  1688. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  1689. static std::string translatorName( signature )
  1690. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
  1691. // end catch_interfaces_exception.h
  1692. // start catch_approx.h
  1693. #include <type_traits>
  1694. #include <stdexcept>
  1695. namespace Catch {
  1696. namespace Detail {
  1697. class Approx {
  1698. private:
  1699. bool equalityComparisonImpl(double other) const;
  1700. public:
  1701. explicit Approx ( double value );
  1702. static Approx custom();
  1703. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1704. Approx operator()( T const& value ) {
  1705. Approx approx( static_cast<double>(value) );
  1706. approx.epsilon( m_epsilon );
  1707. approx.margin( m_margin );
  1708. approx.scale( m_scale );
  1709. return approx;
  1710. }
  1711. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1712. explicit Approx( T const& value ): Approx(static_cast<double>(value))
  1713. {}
  1714. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1715. friend bool operator == ( const T& lhs, Approx const& rhs ) {
  1716. auto lhs_v = static_cast<double>(lhs);
  1717. return rhs.equalityComparisonImpl(lhs_v);
  1718. }
  1719. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1720. friend bool operator == ( Approx const& lhs, const T& rhs ) {
  1721. return operator==( rhs, lhs );
  1722. }
  1723. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1724. friend bool operator != ( T const& lhs, Approx const& rhs ) {
  1725. return !operator==( lhs, rhs );
  1726. }
  1727. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1728. friend bool operator != ( Approx const& lhs, T const& rhs ) {
  1729. return !operator==( rhs, lhs );
  1730. }
  1731. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1732. friend bool operator <= ( T const& lhs, Approx const& rhs ) {
  1733. return static_cast<double>(lhs) < rhs.m_value || lhs == rhs;
  1734. }
  1735. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1736. friend bool operator <= ( Approx const& lhs, T const& rhs ) {
  1737. return lhs.m_value < static_cast<double>(rhs) || lhs == rhs;
  1738. }
  1739. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1740. friend bool operator >= ( T const& lhs, Approx const& rhs ) {
  1741. return static_cast<double>(lhs) > rhs.m_value || lhs == rhs;
  1742. }
  1743. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1744. friend bool operator >= ( Approx const& lhs, T const& rhs ) {
  1745. return lhs.m_value > static_cast<double>(rhs) || lhs == rhs;
  1746. }
  1747. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1748. Approx& epsilon( T const& newEpsilon ) {
  1749. double epsilonAsDouble = static_cast<double>(newEpsilon);
  1750. if( epsilonAsDouble < 0 || epsilonAsDouble > 1.0 ) {
  1751. throw std::domain_error
  1752. ( "Invalid Approx::epsilon: " +
  1753. Catch::Detail::stringify( epsilonAsDouble ) +
  1754. ", Approx::epsilon has to be between 0 and 1" );
  1755. }
  1756. m_epsilon = epsilonAsDouble;
  1757. return *this;
  1758. }
  1759. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1760. Approx& margin( T const& newMargin ) {
  1761. double marginAsDouble = static_cast<double>(newMargin);
  1762. if( marginAsDouble < 0 ) {
  1763. throw std::domain_error
  1764. ( "Invalid Approx::margin: " +
  1765. Catch::Detail::stringify( marginAsDouble ) +
  1766. ", Approx::Margin has to be non-negative." );
  1767. }
  1768. m_margin = marginAsDouble;
  1769. return *this;
  1770. }
  1771. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1772. Approx& scale( T const& newScale ) {
  1773. m_scale = static_cast<double>(newScale);
  1774. return *this;
  1775. }
  1776. std::string toString() const;
  1777. private:
  1778. double m_epsilon;
  1779. double m_margin;
  1780. double m_scale;
  1781. double m_value;
  1782. };
  1783. }
  1784. template<>
  1785. struct StringMaker<Catch::Detail::Approx> {
  1786. static std::string convert(Catch::Detail::Approx const& value);
  1787. };
  1788. } // end namespace Catch
  1789. // end catch_approx.h
  1790. // start catch_string_manip.h
  1791. #include <string>
  1792. #include <iosfwd>
  1793. namespace Catch {
  1794. bool startsWith( std::string const& s, std::string const& prefix );
  1795. bool startsWith( std::string const& s, char prefix );
  1796. bool endsWith( std::string const& s, std::string const& suffix );
  1797. bool endsWith( std::string const& s, char suffix );
  1798. bool contains( std::string const& s, std::string const& infix );
  1799. void toLowerInPlace( std::string& s );
  1800. std::string toLower( std::string const& s );
  1801. std::string trim( std::string const& str );
  1802. bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis );
  1803. struct pluralise {
  1804. pluralise( std::size_t count, std::string const& label );
  1805. friend std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser );
  1806. std::size_t m_count;
  1807. std::string m_label;
  1808. };
  1809. }
  1810. // end catch_string_manip.h
  1811. #ifndef CATCH_CONFIG_DISABLE_MATCHERS
  1812. // start catch_capture_matchers.h
  1813. // start catch_matchers.h
  1814. #include <string>
  1815. #include <vector>
  1816. namespace Catch {
  1817. namespace Matchers {
  1818. namespace Impl {
  1819. template<typename ArgT> struct MatchAllOf;
  1820. template<typename ArgT> struct MatchAnyOf;
  1821. template<typename ArgT> struct MatchNotOf;
  1822. class MatcherUntypedBase {
  1823. public:
  1824. MatcherUntypedBase() = default;
  1825. MatcherUntypedBase ( MatcherUntypedBase const& ) = default;
  1826. MatcherUntypedBase& operator = ( MatcherUntypedBase const& ) = delete;
  1827. std::string toString() const;
  1828. protected:
  1829. virtual ~MatcherUntypedBase();
  1830. virtual std::string describe() const = 0;
  1831. mutable std::string m_cachedToString;
  1832. };
  1833. template<typename ObjectT>
  1834. struct MatcherMethod {
  1835. virtual bool match( ObjectT const& arg ) const = 0;
  1836. };
  1837. template<typename PtrT>
  1838. struct MatcherMethod<PtrT*> {
  1839. virtual bool match( PtrT* arg ) const = 0;
  1840. };
  1841. template<typename T>
  1842. struct MatcherBase : MatcherUntypedBase, MatcherMethod<T> {
  1843. MatchAllOf<T> operator && ( MatcherBase const& other ) const;
  1844. MatchAnyOf<T> operator || ( MatcherBase const& other ) const;
  1845. MatchNotOf<T> operator ! () const;
  1846. };
  1847. template<typename ArgT>
  1848. struct MatchAllOf : MatcherBase<ArgT> {
  1849. bool match( ArgT const& arg ) const override {
  1850. for( auto matcher : m_matchers ) {
  1851. if (!matcher->match(arg))
  1852. return false;
  1853. }
  1854. return true;
  1855. }
  1856. std::string describe() const override {
  1857. std::string description;
  1858. description.reserve( 4 + m_matchers.size()*32 );
  1859. description += "( ";
  1860. bool first = true;
  1861. for( auto matcher : m_matchers ) {
  1862. if( first )
  1863. first = false;
  1864. else
  1865. description += " and ";
  1866. description += matcher->toString();
  1867. }
  1868. description += " )";
  1869. return description;
  1870. }
  1871. MatchAllOf<ArgT>& operator && ( MatcherBase<ArgT> const& other ) {
  1872. m_matchers.push_back( &other );
  1873. return *this;
  1874. }
  1875. std::vector<MatcherBase<ArgT> const*> m_matchers;
  1876. };
  1877. template<typename ArgT>
  1878. struct MatchAnyOf : MatcherBase<ArgT> {
  1879. bool match( ArgT const& arg ) const override {
  1880. for( auto matcher : m_matchers ) {
  1881. if (matcher->match(arg))
  1882. return true;
  1883. }
  1884. return false;
  1885. }
  1886. std::string describe() const override {
  1887. std::string description;
  1888. description.reserve( 4 + m_matchers.size()*32 );
  1889. description += "( ";
  1890. bool first = true;
  1891. for( auto matcher : m_matchers ) {
  1892. if( first )
  1893. first = false;
  1894. else
  1895. description += " or ";
  1896. description += matcher->toString();
  1897. }
  1898. description += " )";
  1899. return description;
  1900. }
  1901. MatchAnyOf<ArgT>& operator || ( MatcherBase<ArgT> const& other ) {
  1902. m_matchers.push_back( &other );
  1903. return *this;
  1904. }
  1905. std::vector<MatcherBase<ArgT> const*> m_matchers;
  1906. };
  1907. template<typename ArgT>
  1908. struct MatchNotOf : MatcherBase<ArgT> {
  1909. MatchNotOf( MatcherBase<ArgT> const& underlyingMatcher ) : m_underlyingMatcher( underlyingMatcher ) {}
  1910. bool match( ArgT const& arg ) const override {
  1911. return !m_underlyingMatcher.match( arg );
  1912. }
  1913. std::string describe() const override {
  1914. return "not " + m_underlyingMatcher.toString();
  1915. }
  1916. MatcherBase<ArgT> const& m_underlyingMatcher;
  1917. };
  1918. template<typename T>
  1919. MatchAllOf<T> MatcherBase<T>::operator && ( MatcherBase const& other ) const {
  1920. return MatchAllOf<T>() && *this && other;
  1921. }
  1922. template<typename T>
  1923. MatchAnyOf<T> MatcherBase<T>::operator || ( MatcherBase const& other ) const {
  1924. return MatchAnyOf<T>() || *this || other;
  1925. }
  1926. template<typename T>
  1927. MatchNotOf<T> MatcherBase<T>::operator ! () const {
  1928. return MatchNotOf<T>( *this );
  1929. }
  1930. } // namespace Impl
  1931. } // namespace Matchers
  1932. using namespace Matchers;
  1933. using Matchers::Impl::MatcherBase;
  1934. } // namespace Catch
  1935. // end catch_matchers.h
  1936. // start catch_matchers_floating.h
  1937. #include <type_traits>
  1938. #include <cmath>
  1939. namespace Catch {
  1940. namespace Matchers {
  1941. namespace Floating {
  1942. enum class FloatingPointKind : uint8_t;
  1943. struct WithinAbsMatcher : MatcherBase<double> {
  1944. WithinAbsMatcher(double target, double margin);
  1945. bool match(double const& matchee) const override;
  1946. std::string describe() const override;
  1947. private:
  1948. double m_target;
  1949. double m_margin;
  1950. };
  1951. struct WithinUlpsMatcher : MatcherBase<double> {
  1952. WithinUlpsMatcher(double target, int ulps, FloatingPointKind baseType);
  1953. bool match(double const& matchee) const override;
  1954. std::string describe() const override;
  1955. private:
  1956. double m_target;
  1957. int m_ulps;
  1958. FloatingPointKind m_type;
  1959. };
  1960. } // namespace Floating
  1961. // The following functions create the actual matcher objects.
  1962. // This allows the types to be inferred
  1963. Floating::WithinUlpsMatcher WithinULP(double target, int maxUlpDiff);
  1964. Floating::WithinUlpsMatcher WithinULP(float target, int maxUlpDiff);
  1965. Floating::WithinAbsMatcher WithinAbs(double target, double margin);
  1966. } // namespace Matchers
  1967. } // namespace Catch
  1968. // end catch_matchers_floating.h
  1969. // start catch_matchers_generic.hpp
  1970. #include <functional>
  1971. #include <string>
  1972. namespace Catch {
  1973. namespace Matchers {
  1974. namespace Generic {
  1975. namespace Detail {
  1976. std::string finalizeDescription(const std::string& desc);
  1977. }
  1978. template <typename T>
  1979. class PredicateMatcher : public MatcherBase<T> {
  1980. std::function<bool(T const&)> m_predicate;
  1981. std::string m_description;
  1982. public:
  1983. PredicateMatcher(std::function<bool(T const&)> const& elem, std::string const& descr)
  1984. :m_predicate(std::move(elem)),
  1985. m_description(Detail::finalizeDescription(descr))
  1986. {}
  1987. bool match( T const& item ) const override {
  1988. return m_predicate(item);
  1989. }
  1990. std::string describe() const override {
  1991. return m_description;
  1992. }
  1993. };
  1994. } // namespace Generic
  1995. // The following functions create the actual matcher objects.
  1996. // The user has to explicitly specify type to the function, because
  1997. // infering std::function<bool(T const&)> is hard (but possible) and
  1998. // requires a lot of TMP.
  1999. template<typename T>
  2000. Generic::PredicateMatcher<T> Predicate(std::function<bool(T const&)> const& predicate, std::string const& description = "") {
  2001. return Generic::PredicateMatcher<T>(predicate, description);
  2002. }
  2003. } // namespace Matchers
  2004. } // namespace Catch
  2005. // end catch_matchers_generic.hpp
  2006. // start catch_matchers_string.h
  2007. #include <string>
  2008. namespace Catch {
  2009. namespace Matchers {
  2010. namespace StdString {
  2011. struct CasedString
  2012. {
  2013. CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity );
  2014. std::string adjustString( std::string const& str ) const;
  2015. std::string caseSensitivitySuffix() const;
  2016. CaseSensitive::Choice m_caseSensitivity;
  2017. std::string m_str;
  2018. };
  2019. struct StringMatcherBase : MatcherBase<std::string> {
  2020. StringMatcherBase( std::string const& operation, CasedString const& comparator );
  2021. std::string describe() const override;
  2022. CasedString m_comparator;
  2023. std::string m_operation;
  2024. };
  2025. struct EqualsMatcher : StringMatcherBase {
  2026. EqualsMatcher( CasedString const& comparator );
  2027. bool match( std::string const& source ) const override;
  2028. };
  2029. struct ContainsMatcher : StringMatcherBase {
  2030. ContainsMatcher( CasedString const& comparator );
  2031. bool match( std::string const& source ) const override;
  2032. };
  2033. struct StartsWithMatcher : StringMatcherBase {
  2034. StartsWithMatcher( CasedString const& comparator );
  2035. bool match( std::string const& source ) const override;
  2036. };
  2037. struct EndsWithMatcher : StringMatcherBase {
  2038. EndsWithMatcher( CasedString const& comparator );
  2039. bool match( std::string const& source ) const override;
  2040. };
  2041. struct RegexMatcher : MatcherBase<std::string> {
  2042. RegexMatcher( std::string regex, CaseSensitive::Choice caseSensitivity );
  2043. bool match( std::string const& matchee ) const override;
  2044. std::string describe() const override;
  2045. private:
  2046. std::string m_regex;
  2047. CaseSensitive::Choice m_caseSensitivity;
  2048. };
  2049. } // namespace StdString
  2050. // The following functions create the actual matcher objects.
  2051. // This allows the types to be inferred
  2052. StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2053. StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2054. StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2055. StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2056. StdString::RegexMatcher Matches( std::string const& regex, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2057. } // namespace Matchers
  2058. } // namespace Catch
  2059. // end catch_matchers_string.h
  2060. // start catch_matchers_vector.h
  2061. #include <algorithm>
  2062. namespace Catch {
  2063. namespace Matchers {
  2064. namespace Vector {
  2065. namespace Detail {
  2066. template <typename InputIterator, typename T>
  2067. size_t count(InputIterator first, InputIterator last, T const& item) {
  2068. size_t cnt = 0;
  2069. for (; first != last; ++first) {
  2070. if (*first == item) {
  2071. ++cnt;
  2072. }
  2073. }
  2074. return cnt;
  2075. }
  2076. template <typename InputIterator, typename T>
  2077. bool contains(InputIterator first, InputIterator last, T const& item) {
  2078. for (; first != last; ++first) {
  2079. if (*first == item) {
  2080. return true;
  2081. }
  2082. }
  2083. return false;
  2084. }
  2085. }
  2086. template<typename T>
  2087. struct ContainsElementMatcher : MatcherBase<std::vector<T>> {
  2088. ContainsElementMatcher(T const &comparator) : m_comparator( comparator) {}
  2089. bool match(std::vector<T> const &v) const override {
  2090. for (auto const& el : v) {
  2091. if (el == m_comparator) {
  2092. return true;
  2093. }
  2094. }
  2095. return false;
  2096. }
  2097. std::string describe() const override {
  2098. return "Contains: " + ::Catch::Detail::stringify( m_comparator );
  2099. }
  2100. T const& m_comparator;
  2101. };
  2102. template<typename T>
  2103. struct ContainsMatcher : MatcherBase<std::vector<T>> {
  2104. ContainsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}
  2105. bool match(std::vector<T> const &v) const override {
  2106. // !TBD: see note in EqualsMatcher
  2107. if (m_comparator.size() > v.size())
  2108. return false;
  2109. for (auto const& comparator : m_comparator) {
  2110. auto present = false;
  2111. for (const auto& el : v) {
  2112. if (el == comparator) {
  2113. present = true;
  2114. break;
  2115. }
  2116. }
  2117. if (!present) {
  2118. return false;
  2119. }
  2120. }
  2121. return true;
  2122. }
  2123. std::string describe() const override {
  2124. return "Contains: " + ::Catch::Detail::stringify( m_comparator );
  2125. }
  2126. std::vector<T> const& m_comparator;
  2127. };
  2128. template<typename T>
  2129. struct EqualsMatcher : MatcherBase<std::vector<T>> {
  2130. EqualsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}
  2131. bool match(std::vector<T> const &v) const override {
  2132. // !TBD: This currently works if all elements can be compared using !=
  2133. // - a more general approach would be via a compare template that defaults
  2134. // to using !=. but could be specialised for, e.g. std::vector<T> etc
  2135. // - then just call that directly
  2136. if (m_comparator.size() != v.size())
  2137. return false;
  2138. for (std::size_t i = 0; i < v.size(); ++i)
  2139. if (m_comparator[i] != v[i])
  2140. return false;
  2141. return true;
  2142. }
  2143. std::string describe() const override {
  2144. return "Equals: " + ::Catch::Detail::stringify( m_comparator );
  2145. }
  2146. std::vector<T> const& m_comparator;
  2147. };
  2148. template<typename T>
  2149. struct UnorderedEqualsMatcher : MatcherBase<std::vector<T>> {
  2150. UnorderedEqualsMatcher(std::vector<T> const& target) : m_target(target) {}
  2151. bool match(std::vector<T> const& vec) const override {
  2152. // Note: This is a reimplementation of std::is_permutation,
  2153. // because I don't want to include <algorithm> inside the common path
  2154. if (m_target.size() != vec.size()) {
  2155. return false;
  2156. }
  2157. auto lfirst = m_target.begin(), llast = m_target.end();
  2158. auto rfirst = vec.begin(), rlast = vec.end();
  2159. // Cut common prefix to optimize checking of permuted parts
  2160. while (lfirst != llast && *lfirst != *rfirst) {
  2161. ++lfirst; ++rfirst;
  2162. }
  2163. if (lfirst == llast) {
  2164. return true;
  2165. }
  2166. for (auto mid = lfirst; mid != llast; ++mid) {
  2167. // Skip already counted items
  2168. if (Detail::contains(lfirst, mid, *mid)) {
  2169. continue;
  2170. }
  2171. size_t num_vec = Detail::count(rfirst, rlast, *mid);
  2172. if (num_vec == 0 || Detail::count(lfirst, llast, *mid) != num_vec) {
  2173. return false;
  2174. }
  2175. }
  2176. return true;
  2177. }
  2178. std::string describe() const override {
  2179. return "UnorderedEquals: " + ::Catch::Detail::stringify(m_target);
  2180. }
  2181. private:
  2182. std::vector<T> const& m_target;
  2183. };
  2184. } // namespace Vector
  2185. // The following functions create the actual matcher objects.
  2186. // This allows the types to be inferred
  2187. template<typename T>
  2188. Vector::ContainsMatcher<T> Contains( std::vector<T> const& comparator ) {
  2189. return Vector::ContainsMatcher<T>( comparator );
  2190. }
  2191. template<typename T>
  2192. Vector::ContainsElementMatcher<T> VectorContains( T const& comparator ) {
  2193. return Vector::ContainsElementMatcher<T>( comparator );
  2194. }
  2195. template<typename T>
  2196. Vector::EqualsMatcher<T> Equals( std::vector<T> const& comparator ) {
  2197. return Vector::EqualsMatcher<T>( comparator );
  2198. }
  2199. template<typename T>
  2200. Vector::UnorderedEqualsMatcher<T> UnorderedEquals(std::vector<T> const& target) {
  2201. return Vector::UnorderedEqualsMatcher<T>(target);
  2202. }
  2203. } // namespace Matchers
  2204. } // namespace Catch
  2205. // end catch_matchers_vector.h
  2206. namespace Catch {
  2207. template<typename ArgT, typename MatcherT>
  2208. class MatchExpr : public ITransientExpression {
  2209. ArgT const& m_arg;
  2210. MatcherT m_matcher;
  2211. StringRef m_matcherString;
  2212. public:
  2213. MatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef matcherString )
  2214. : ITransientExpression{ true, matcher.match( arg ) },
  2215. m_arg( arg ),
  2216. m_matcher( matcher ),
  2217. m_matcherString( matcherString )
  2218. {}
  2219. void streamReconstructedExpression( std::ostream &os ) const override {
  2220. auto matcherAsString = m_matcher.toString();
  2221. os << Catch::Detail::stringify( m_arg ) << ' ';
  2222. if( matcherAsString == Detail::unprintableString )
  2223. os << m_matcherString;
  2224. else
  2225. os << matcherAsString;
  2226. }
  2227. };
  2228. using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
  2229. void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef matcherString );
  2230. template<typename ArgT, typename MatcherT>
  2231. auto makeMatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef matcherString ) -> MatchExpr<ArgT, MatcherT> {
  2232. return MatchExpr<ArgT, MatcherT>( arg, matcher, matcherString );
  2233. }
  2234. } // namespace Catch
  2235. ///////////////////////////////////////////////////////////////////////////////
  2236. #define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \
  2237. do { \
  2238. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  2239. INTERNAL_CATCH_TRY { \
  2240. catchAssertionHandler.handleExpr( Catch::makeMatchExpr( arg, matcher, #matcher ) ); \
  2241. } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
  2242. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2243. } while( false )
  2244. ///////////////////////////////////////////////////////////////////////////////
  2245. #define INTERNAL_CATCH_THROWS_MATCHES( macroName, exceptionType, resultDisposition, matcher, ... ) \
  2246. do { \
  2247. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(exceptionType) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  2248. if( catchAssertionHandler.allowThrows() ) \
  2249. try { \
  2250. static_cast<void>(__VA_ARGS__ ); \
  2251. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  2252. } \
  2253. catch( exceptionType const& ex ) { \
  2254. catchAssertionHandler.handleExpr( Catch::makeMatchExpr( ex, matcher, #matcher ) ); \
  2255. } \
  2256. catch( ... ) { \
  2257. catchAssertionHandler.handleUnexpectedInflightException(); \
  2258. } \
  2259. else \
  2260. catchAssertionHandler.handleThrowingCallSkipped(); \
  2261. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2262. } while( false )
  2263. // end catch_capture_matchers.h
  2264. #endif
  2265. // These files are included here so the single_include script doesn't put them
  2266. // in the conditionally compiled sections
  2267. // start catch_test_case_info.h
  2268. #include <string>
  2269. #include <vector>
  2270. #include <memory>
  2271. #ifdef __clang__
  2272. #pragma clang diagnostic push
  2273. #pragma clang diagnostic ignored "-Wpadded"
  2274. #endif
  2275. namespace Catch {
  2276. struct ITestInvoker;
  2277. struct TestCaseInfo {
  2278. enum SpecialProperties{
  2279. None = 0,
  2280. IsHidden = 1 << 1,
  2281. ShouldFail = 1 << 2,
  2282. MayFail = 1 << 3,
  2283. Throws = 1 << 4,
  2284. NonPortable = 1 << 5,
  2285. Benchmark = 1 << 6
  2286. };
  2287. TestCaseInfo( std::string const& _name,
  2288. std::string const& _className,
  2289. std::string const& _description,
  2290. std::vector<std::string> const& _tags,
  2291. SourceLineInfo const& _lineInfo );
  2292. friend void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags );
  2293. bool isHidden() const;
  2294. bool throws() const;
  2295. bool okToFail() const;
  2296. bool expectedToFail() const;
  2297. std::string tagsAsString() const;
  2298. std::string name;
  2299. std::string className;
  2300. std::string description;
  2301. std::vector<std::string> tags;
  2302. std::vector<std::string> lcaseTags;
  2303. SourceLineInfo lineInfo;
  2304. SpecialProperties properties;
  2305. };
  2306. class TestCase : public TestCaseInfo {
  2307. public:
  2308. TestCase( ITestInvoker* testCase, TestCaseInfo&& info );
  2309. TestCase withName( std::string const& _newName ) const;
  2310. void invoke() const;
  2311. TestCaseInfo const& getTestCaseInfo() const;
  2312. bool operator == ( TestCase const& other ) const;
  2313. bool operator < ( TestCase const& other ) const;
  2314. private:
  2315. std::shared_ptr<ITestInvoker> test;
  2316. };
  2317. TestCase makeTestCase( ITestInvoker* testCase,
  2318. std::string const& className,
  2319. NameAndTags const& nameAndTags,
  2320. SourceLineInfo const& lineInfo );
  2321. }
  2322. #ifdef __clang__
  2323. #pragma clang diagnostic pop
  2324. #endif
  2325. // end catch_test_case_info.h
  2326. // start catch_interfaces_runner.h
  2327. namespace Catch {
  2328. struct IRunner {
  2329. virtual ~IRunner();
  2330. virtual bool aborting() const = 0;
  2331. };
  2332. }
  2333. // end catch_interfaces_runner.h
  2334. #ifdef __OBJC__
  2335. // start catch_objc.hpp
  2336. #import <objc/runtime.h>
  2337. #include <string>
  2338. // NB. Any general catch headers included here must be included
  2339. // in catch.hpp first to make sure they are included by the single
  2340. // header for non obj-usage
  2341. ///////////////////////////////////////////////////////////////////////////////
  2342. // This protocol is really only here for (self) documenting purposes, since
  2343. // all its methods are optional.
  2344. @protocol OcFixture
  2345. @optional
  2346. -(void) setUp;
  2347. -(void) tearDown;
  2348. @end
  2349. namespace Catch {
  2350. class OcMethod : public ITestInvoker {
  2351. public:
  2352. OcMethod( Class cls, SEL sel ) : m_cls( cls ), m_sel( sel ) {}
  2353. virtual void invoke() const {
  2354. id obj = [[m_cls alloc] init];
  2355. performOptionalSelector( obj, @selector(setUp) );
  2356. performOptionalSelector( obj, m_sel );
  2357. performOptionalSelector( obj, @selector(tearDown) );
  2358. arcSafeRelease( obj );
  2359. }
  2360. private:
  2361. virtual ~OcMethod() {}
  2362. Class m_cls;
  2363. SEL m_sel;
  2364. };
  2365. namespace Detail{
  2366. inline std::string getAnnotation( Class cls,
  2367. std::string const& annotationName,
  2368. std::string const& testCaseName ) {
  2369. NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()];
  2370. SEL sel = NSSelectorFromString( selStr );
  2371. arcSafeRelease( selStr );
  2372. id value = performOptionalSelector( cls, sel );
  2373. if( value )
  2374. return [(NSString*)value UTF8String];
  2375. return "";
  2376. }
  2377. }
  2378. inline std::size_t registerTestMethods() {
  2379. std::size_t noTestMethods = 0;
  2380. int noClasses = objc_getClassList( nullptr, 0 );
  2381. Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc( sizeof(Class) * noClasses);
  2382. objc_getClassList( classes, noClasses );
  2383. for( int c = 0; c < noClasses; c++ ) {
  2384. Class cls = classes[c];
  2385. {
  2386. u_int count;
  2387. Method* methods = class_copyMethodList( cls, &count );
  2388. for( u_int m = 0; m < count ; m++ ) {
  2389. SEL selector = method_getName(methods[m]);
  2390. std::string methodName = sel_getName(selector);
  2391. if( startsWith( methodName, "Catch_TestCase_" ) ) {
  2392. std::string testCaseName = methodName.substr( 15 );
  2393. std::string name = Detail::getAnnotation( cls, "Name", testCaseName );
  2394. std::string desc = Detail::getAnnotation( cls, "Description", testCaseName );
  2395. const char* className = class_getName( cls );
  2396. getMutableRegistryHub().registerTest( makeTestCase( new OcMethod( cls, selector ), className, name.c_str(), desc.c_str(), SourceLineInfo("",0) ) );
  2397. noTestMethods++;
  2398. }
  2399. }
  2400. free(methods);
  2401. }
  2402. }
  2403. return noTestMethods;
  2404. }
  2405. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  2406. namespace Matchers {
  2407. namespace Impl {
  2408. namespace NSStringMatchers {
  2409. struct StringHolder : MatcherBase<NSString*>{
  2410. StringHolder( NSString* substr ) : m_substr( [substr copy] ){}
  2411. StringHolder( StringHolder const& other ) : m_substr( [other.m_substr copy] ){}
  2412. StringHolder() {
  2413. arcSafeRelease( m_substr );
  2414. }
  2415. bool match( NSString* arg ) const override {
  2416. return false;
  2417. }
  2418. NSString* CATCH_ARC_STRONG m_substr;
  2419. };
  2420. struct Equals : StringHolder {
  2421. Equals( NSString* substr ) : StringHolder( substr ){}
  2422. bool match( NSString* str ) const override {
  2423. return (str != nil || m_substr == nil ) &&
  2424. [str isEqualToString:m_substr];
  2425. }
  2426. std::string describe() const override {
  2427. return "equals string: " + Catch::Detail::stringify( m_substr );
  2428. }
  2429. };
  2430. struct Contains : StringHolder {
  2431. Contains( NSString* substr ) : StringHolder( substr ){}
  2432. bool match( NSString* str ) const {
  2433. return (str != nil || m_substr == nil ) &&
  2434. [str rangeOfString:m_substr].location != NSNotFound;
  2435. }
  2436. std::string describe() const override {
  2437. return "contains string: " + Catch::Detail::stringify( m_substr );
  2438. }
  2439. };
  2440. struct StartsWith : StringHolder {
  2441. StartsWith( NSString* substr ) : StringHolder( substr ){}
  2442. bool match( NSString* str ) const override {
  2443. return (str != nil || m_substr == nil ) &&
  2444. [str rangeOfString:m_substr].location == 0;
  2445. }
  2446. std::string describe() const override {
  2447. return "starts with: " + Catch::Detail::stringify( m_substr );
  2448. }
  2449. };
  2450. struct EndsWith : StringHolder {
  2451. EndsWith( NSString* substr ) : StringHolder( substr ){}
  2452. bool match( NSString* str ) const override {
  2453. return (str != nil || m_substr == nil ) &&
  2454. [str rangeOfString:m_substr].location == [str length] - [m_substr length];
  2455. }
  2456. std::string describe() const override {
  2457. return "ends with: " + Catch::Detail::stringify( m_substr );
  2458. }
  2459. };
  2460. } // namespace NSStringMatchers
  2461. } // namespace Impl
  2462. inline Impl::NSStringMatchers::Equals
  2463. Equals( NSString* substr ){ return Impl::NSStringMatchers::Equals( substr ); }
  2464. inline Impl::NSStringMatchers::Contains
  2465. Contains( NSString* substr ){ return Impl::NSStringMatchers::Contains( substr ); }
  2466. inline Impl::NSStringMatchers::StartsWith
  2467. StartsWith( NSString* substr ){ return Impl::NSStringMatchers::StartsWith( substr ); }
  2468. inline Impl::NSStringMatchers::EndsWith
  2469. EndsWith( NSString* substr ){ return Impl::NSStringMatchers::EndsWith( substr ); }
  2470. } // namespace Matchers
  2471. using namespace Matchers;
  2472. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  2473. } // namespace Catch
  2474. ///////////////////////////////////////////////////////////////////////////////
  2475. #define OC_MAKE_UNIQUE_NAME( root, uniqueSuffix ) root##uniqueSuffix
  2476. #define OC_TEST_CASE2( name, desc, uniqueSuffix ) \
  2477. +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Name_test_, uniqueSuffix ) \
  2478. { \
  2479. return @ name; \
  2480. } \
  2481. +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Description_test_, uniqueSuffix ) \
  2482. { \
  2483. return @ desc; \
  2484. } \
  2485. -(void) OC_MAKE_UNIQUE_NAME( Catch_TestCase_test_, uniqueSuffix )
  2486. #define OC_TEST_CASE( name, desc ) OC_TEST_CASE2( name, desc, __LINE__ )
  2487. // end catch_objc.hpp
  2488. #endif
  2489. #ifdef CATCH_CONFIG_EXTERNAL_INTERFACES
  2490. // start catch_external_interfaces.h
  2491. // start catch_reporter_bases.hpp
  2492. // start catch_interfaces_reporter.h
  2493. // start catch_config.hpp
  2494. // start catch_test_spec_parser.h
  2495. #ifdef __clang__
  2496. #pragma clang diagnostic push
  2497. #pragma clang diagnostic ignored "-Wpadded"
  2498. #endif
  2499. // start catch_test_spec.h
  2500. #ifdef __clang__
  2501. #pragma clang diagnostic push
  2502. #pragma clang diagnostic ignored "-Wpadded"
  2503. #endif
  2504. // start catch_wildcard_pattern.h
  2505. namespace Catch
  2506. {
  2507. class WildcardPattern {
  2508. enum WildcardPosition {
  2509. NoWildcard = 0,
  2510. WildcardAtStart = 1,
  2511. WildcardAtEnd = 2,
  2512. WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd
  2513. };
  2514. public:
  2515. WildcardPattern( std::string const& pattern, CaseSensitive::Choice caseSensitivity );
  2516. virtual ~WildcardPattern() = default;
  2517. virtual bool matches( std::string const& str ) const;
  2518. private:
  2519. std::string adjustCase( std::string const& str ) const;
  2520. CaseSensitive::Choice m_caseSensitivity;
  2521. WildcardPosition m_wildcard = NoWildcard;
  2522. std::string m_pattern;
  2523. };
  2524. }
  2525. // end catch_wildcard_pattern.h
  2526. #include <string>
  2527. #include <vector>
  2528. #include <memory>
  2529. namespace Catch {
  2530. class TestSpec {
  2531. struct Pattern {
  2532. virtual ~Pattern();
  2533. virtual bool matches( TestCaseInfo const& testCase ) const = 0;
  2534. };
  2535. using PatternPtr = std::shared_ptr<Pattern>;
  2536. class NamePattern : public Pattern {
  2537. public:
  2538. NamePattern( std::string const& name );
  2539. virtual ~NamePattern();
  2540. virtual bool matches( TestCaseInfo const& testCase ) const override;
  2541. private:
  2542. WildcardPattern m_wildcardPattern;
  2543. };
  2544. class TagPattern : public Pattern {
  2545. public:
  2546. TagPattern( std::string const& tag );
  2547. virtual ~TagPattern();
  2548. virtual bool matches( TestCaseInfo const& testCase ) const override;
  2549. private:
  2550. std::string m_tag;
  2551. };
  2552. class ExcludedPattern : public Pattern {
  2553. public:
  2554. ExcludedPattern( PatternPtr const& underlyingPattern );
  2555. virtual ~ExcludedPattern();
  2556. virtual bool matches( TestCaseInfo const& testCase ) const override;
  2557. private:
  2558. PatternPtr m_underlyingPattern;
  2559. };
  2560. struct Filter {
  2561. std::vector<PatternPtr> m_patterns;
  2562. bool matches( TestCaseInfo const& testCase ) const;
  2563. };
  2564. public:
  2565. bool hasFilters() const;
  2566. bool matches( TestCaseInfo const& testCase ) const;
  2567. private:
  2568. std::vector<Filter> m_filters;
  2569. friend class TestSpecParser;
  2570. };
  2571. }
  2572. #ifdef __clang__
  2573. #pragma clang diagnostic pop
  2574. #endif
  2575. // end catch_test_spec.h
  2576. // start catch_interfaces_tag_alias_registry.h
  2577. #include <string>
  2578. namespace Catch {
  2579. struct TagAlias;
  2580. struct ITagAliasRegistry {
  2581. virtual ~ITagAliasRegistry();
  2582. // Nullptr if not present
  2583. virtual TagAlias const* find( std::string const& alias ) const = 0;
  2584. virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const = 0;
  2585. static ITagAliasRegistry const& get();
  2586. };
  2587. } // end namespace Catch
  2588. // end catch_interfaces_tag_alias_registry.h
  2589. namespace Catch {
  2590. class TestSpecParser {
  2591. enum Mode{ None, Name, QuotedName, Tag, EscapedName };
  2592. Mode m_mode = None;
  2593. bool m_exclusion = false;
  2594. std::size_t m_start = std::string::npos, m_pos = 0;
  2595. std::string m_arg;
  2596. std::vector<std::size_t> m_escapeChars;
  2597. TestSpec::Filter m_currentFilter;
  2598. TestSpec m_testSpec;
  2599. ITagAliasRegistry const* m_tagAliases = nullptr;
  2600. public:
  2601. TestSpecParser( ITagAliasRegistry const& tagAliases );
  2602. TestSpecParser& parse( std::string const& arg );
  2603. TestSpec testSpec();
  2604. private:
  2605. void visitChar( char c );
  2606. void startNewMode( Mode mode, std::size_t start );
  2607. void escape();
  2608. std::string subString() const;
  2609. template<typename T>
  2610. void addPattern() {
  2611. std::string token = subString();
  2612. for( std::size_t i = 0; i < m_escapeChars.size(); ++i )
  2613. token = token.substr( 0, m_escapeChars[i]-m_start-i ) + token.substr( m_escapeChars[i]-m_start-i+1 );
  2614. m_escapeChars.clear();
  2615. if( startsWith( token, "exclude:" ) ) {
  2616. m_exclusion = true;
  2617. token = token.substr( 8 );
  2618. }
  2619. if( !token.empty() ) {
  2620. TestSpec::PatternPtr pattern = std::make_shared<T>( token );
  2621. if( m_exclusion )
  2622. pattern = std::make_shared<TestSpec::ExcludedPattern>( pattern );
  2623. m_currentFilter.m_patterns.push_back( pattern );
  2624. }
  2625. m_exclusion = false;
  2626. m_mode = None;
  2627. }
  2628. void addFilter();
  2629. };
  2630. TestSpec parseTestSpec( std::string const& arg );
  2631. } // namespace Catch
  2632. #ifdef __clang__
  2633. #pragma clang diagnostic pop
  2634. #endif
  2635. // end catch_test_spec_parser.h
  2636. // start catch_interfaces_config.h
  2637. #include <iosfwd>
  2638. #include <string>
  2639. #include <vector>
  2640. #include <memory>
  2641. namespace Catch {
  2642. enum class Verbosity {
  2643. Quiet = 0,
  2644. Normal,
  2645. High
  2646. };
  2647. struct WarnAbout { enum What {
  2648. Nothing = 0x00,
  2649. NoAssertions = 0x01,
  2650. NoTests = 0x02
  2651. }; };
  2652. struct ShowDurations { enum OrNot {
  2653. DefaultForReporter,
  2654. Always,
  2655. Never
  2656. }; };
  2657. struct RunTests { enum InWhatOrder {
  2658. InDeclarationOrder,
  2659. InLexicographicalOrder,
  2660. InRandomOrder
  2661. }; };
  2662. struct UseColour { enum YesOrNo {
  2663. Auto,
  2664. Yes,
  2665. No
  2666. }; };
  2667. struct WaitForKeypress { enum When {
  2668. Never,
  2669. BeforeStart = 1,
  2670. BeforeExit = 2,
  2671. BeforeStartAndExit = BeforeStart | BeforeExit
  2672. }; };
  2673. class TestSpec;
  2674. struct IConfig : NonCopyable {
  2675. virtual ~IConfig();
  2676. virtual bool allowThrows() const = 0;
  2677. virtual std::ostream& stream() const = 0;
  2678. virtual std::string name() const = 0;
  2679. virtual bool includeSuccessfulResults() const = 0;
  2680. virtual bool shouldDebugBreak() const = 0;
  2681. virtual bool warnAboutMissingAssertions() const = 0;
  2682. virtual bool warnAboutNoTests() const = 0;
  2683. virtual int abortAfter() const = 0;
  2684. virtual bool showInvisibles() const = 0;
  2685. virtual ShowDurations::OrNot showDurations() const = 0;
  2686. virtual TestSpec const& testSpec() const = 0;
  2687. virtual bool hasTestFilters() const = 0;
  2688. virtual RunTests::InWhatOrder runOrder() const = 0;
  2689. virtual unsigned int rngSeed() const = 0;
  2690. virtual int benchmarkResolutionMultiple() const = 0;
  2691. virtual UseColour::YesOrNo useColour() const = 0;
  2692. virtual std::vector<std::string> const& getSectionsToRun() const = 0;
  2693. virtual Verbosity verbosity() const = 0;
  2694. };
  2695. using IConfigPtr = std::shared_ptr<IConfig const>;
  2696. }
  2697. // end catch_interfaces_config.h
  2698. // Libstdc++ doesn't like incomplete classes for unique_ptr
  2699. #include <memory>
  2700. #include <vector>
  2701. #include <string>
  2702. #ifndef CATCH_CONFIG_CONSOLE_WIDTH
  2703. #define CATCH_CONFIG_CONSOLE_WIDTH 80
  2704. #endif
  2705. namespace Catch {
  2706. struct IStream;
  2707. struct ConfigData {
  2708. bool listTests = false;
  2709. bool listTags = false;
  2710. bool listReporters = false;
  2711. bool listTestNamesOnly = false;
  2712. bool showSuccessfulTests = false;
  2713. bool shouldDebugBreak = false;
  2714. bool noThrow = false;
  2715. bool showHelp = false;
  2716. bool showInvisibles = false;
  2717. bool filenamesAsTags = false;
  2718. bool libIdentify = false;
  2719. int abortAfter = -1;
  2720. unsigned int rngSeed = 0;
  2721. int benchmarkResolutionMultiple = 100;
  2722. Verbosity verbosity = Verbosity::Normal;
  2723. WarnAbout::What warnings = WarnAbout::Nothing;
  2724. ShowDurations::OrNot showDurations = ShowDurations::DefaultForReporter;
  2725. RunTests::InWhatOrder runOrder = RunTests::InDeclarationOrder;
  2726. UseColour::YesOrNo useColour = UseColour::Auto;
  2727. WaitForKeypress::When waitForKeypress = WaitForKeypress::Never;
  2728. std::string outputFilename;
  2729. std::string name;
  2730. std::string processName;
  2731. #ifndef CATCH_CONFIG_DEFAULT_REPORTER
  2732. #define CATCH_CONFIG_DEFAULT_REPORTER "console"
  2733. #endif
  2734. std::string reporterName = CATCH_CONFIG_DEFAULT_REPORTER;
  2735. #undef CATCH_CONFIG_DEFAULT_REPORTER
  2736. std::vector<std::string> testsOrTags;
  2737. std::vector<std::string> sectionsToRun;
  2738. };
  2739. class Config : public IConfig {
  2740. public:
  2741. Config() = default;
  2742. Config( ConfigData const& data );
  2743. virtual ~Config() = default;
  2744. std::string const& getFilename() const;
  2745. bool listTests() const;
  2746. bool listTestNamesOnly() const;
  2747. bool listTags() const;
  2748. bool listReporters() const;
  2749. std::string getProcessName() const;
  2750. std::string const& getReporterName() const;
  2751. std::vector<std::string> const& getTestsOrTags() const;
  2752. std::vector<std::string> const& getSectionsToRun() const override;
  2753. virtual TestSpec const& testSpec() const override;
  2754. bool hasTestFilters() const override;
  2755. bool showHelp() const;
  2756. // IConfig interface
  2757. bool allowThrows() const override;
  2758. std::ostream& stream() const override;
  2759. std::string name() const override;
  2760. bool includeSuccessfulResults() const override;
  2761. bool warnAboutMissingAssertions() const override;
  2762. bool warnAboutNoTests() const override;
  2763. ShowDurations::OrNot showDurations() const override;
  2764. RunTests::InWhatOrder runOrder() const override;
  2765. unsigned int rngSeed() const override;
  2766. int benchmarkResolutionMultiple() const override;
  2767. UseColour::YesOrNo useColour() const override;
  2768. bool shouldDebugBreak() const override;
  2769. int abortAfter() const override;
  2770. bool showInvisibles() const override;
  2771. Verbosity verbosity() const override;
  2772. private:
  2773. IStream const* openStream();
  2774. ConfigData m_data;
  2775. std::unique_ptr<IStream const> m_stream;
  2776. TestSpec m_testSpec;
  2777. bool m_hasTestFilters = false;
  2778. };
  2779. } // end namespace Catch
  2780. // end catch_config.hpp
  2781. // start catch_assertionresult.h
  2782. #include <string>
  2783. namespace Catch {
  2784. struct AssertionResultData
  2785. {
  2786. AssertionResultData() = delete;
  2787. AssertionResultData( ResultWas::OfType _resultType, LazyExpression const& _lazyExpression );
  2788. std::string message;
  2789. mutable std::string reconstructedExpression;
  2790. LazyExpression lazyExpression;
  2791. ResultWas::OfType resultType;
  2792. std::string reconstructExpression() const;
  2793. };
  2794. class AssertionResult {
  2795. public:
  2796. AssertionResult() = delete;
  2797. AssertionResult( AssertionInfo const& info, AssertionResultData const& data );
  2798. bool isOk() const;
  2799. bool succeeded() const;
  2800. ResultWas::OfType getResultType() const;
  2801. bool hasExpression() const;
  2802. bool hasMessage() const;
  2803. std::string getExpression() const;
  2804. std::string getExpressionInMacro() const;
  2805. bool hasExpandedExpression() const;
  2806. std::string getExpandedExpression() const;
  2807. std::string getMessage() const;
  2808. SourceLineInfo getSourceInfo() const;
  2809. StringRef getTestMacroName() const;
  2810. //protected:
  2811. AssertionInfo m_info;
  2812. AssertionResultData m_resultData;
  2813. };
  2814. } // end namespace Catch
  2815. // end catch_assertionresult.h
  2816. // start catch_option.hpp
  2817. namespace Catch {
  2818. // An optional type
  2819. template<typename T>
  2820. class Option {
  2821. public:
  2822. Option() : nullableValue( nullptr ) {}
  2823. Option( T const& _value )
  2824. : nullableValue( new( storage ) T( _value ) )
  2825. {}
  2826. Option( Option const& _other )
  2827. : nullableValue( _other ? new( storage ) T( *_other ) : nullptr )
  2828. {}
  2829. ~Option() {
  2830. reset();
  2831. }
  2832. Option& operator= ( Option const& _other ) {
  2833. if( &_other != this ) {
  2834. reset();
  2835. if( _other )
  2836. nullableValue = new( storage ) T( *_other );
  2837. }
  2838. return *this;
  2839. }
  2840. Option& operator = ( T const& _value ) {
  2841. reset();
  2842. nullableValue = new( storage ) T( _value );
  2843. return *this;
  2844. }
  2845. void reset() {
  2846. if( nullableValue )
  2847. nullableValue->~T();
  2848. nullableValue = nullptr;
  2849. }
  2850. T& operator*() { return *nullableValue; }
  2851. T const& operator*() const { return *nullableValue; }
  2852. T* operator->() { return nullableValue; }
  2853. const T* operator->() const { return nullableValue; }
  2854. T valueOr( T const& defaultValue ) const {
  2855. return nullableValue ? *nullableValue : defaultValue;
  2856. }
  2857. bool some() const { return nullableValue != nullptr; }
  2858. bool none() const { return nullableValue == nullptr; }
  2859. bool operator !() const { return nullableValue == nullptr; }
  2860. explicit operator bool() const {
  2861. return some();
  2862. }
  2863. private:
  2864. T *nullableValue;
  2865. alignas(alignof(T)) char storage[sizeof(T)];
  2866. };
  2867. } // end namespace Catch
  2868. // end catch_option.hpp
  2869. #include <string>
  2870. #include <iosfwd>
  2871. #include <map>
  2872. #include <set>
  2873. #include <memory>
  2874. namespace Catch {
  2875. struct ReporterConfig {
  2876. explicit ReporterConfig( IConfigPtr const& _fullConfig );
  2877. ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream );
  2878. std::ostream& stream() const;
  2879. IConfigPtr fullConfig() const;
  2880. private:
  2881. std::ostream* m_stream;
  2882. IConfigPtr m_fullConfig;
  2883. };
  2884. struct ReporterPreferences {
  2885. bool shouldRedirectStdOut = false;
  2886. };
  2887. template<typename T>
  2888. struct LazyStat : Option<T> {
  2889. LazyStat& operator=( T const& _value ) {
  2890. Option<T>::operator=( _value );
  2891. used = false;
  2892. return *this;
  2893. }
  2894. void reset() {
  2895. Option<T>::reset();
  2896. used = false;
  2897. }
  2898. bool used = false;
  2899. };
  2900. struct TestRunInfo {
  2901. TestRunInfo( std::string const& _name );
  2902. std::string name;
  2903. };
  2904. struct GroupInfo {
  2905. GroupInfo( std::string const& _name,
  2906. std::size_t _groupIndex,
  2907. std::size_t _groupsCount );
  2908. std::string name;
  2909. std::size_t groupIndex;
  2910. std::size_t groupsCounts;
  2911. };
  2912. struct AssertionStats {
  2913. AssertionStats( AssertionResult const& _assertionResult,
  2914. std::vector<MessageInfo> const& _infoMessages,
  2915. Totals const& _totals );
  2916. AssertionStats( AssertionStats const& ) = default;
  2917. AssertionStats( AssertionStats && ) = default;
  2918. AssertionStats& operator = ( AssertionStats const& ) = default;
  2919. AssertionStats& operator = ( AssertionStats && ) = default;
  2920. virtual ~AssertionStats();
  2921. AssertionResult assertionResult;
  2922. std::vector<MessageInfo> infoMessages;
  2923. Totals totals;
  2924. };
  2925. struct SectionStats {
  2926. SectionStats( SectionInfo const& _sectionInfo,
  2927. Counts const& _assertions,
  2928. double _durationInSeconds,
  2929. bool _missingAssertions );
  2930. SectionStats( SectionStats const& ) = default;
  2931. SectionStats( SectionStats && ) = default;
  2932. SectionStats& operator = ( SectionStats const& ) = default;
  2933. SectionStats& operator = ( SectionStats && ) = default;
  2934. virtual ~SectionStats();
  2935. SectionInfo sectionInfo;
  2936. Counts assertions;
  2937. double durationInSeconds;
  2938. bool missingAssertions;
  2939. };
  2940. struct TestCaseStats {
  2941. TestCaseStats( TestCaseInfo const& _testInfo,
  2942. Totals const& _totals,
  2943. std::string const& _stdOut,
  2944. std::string const& _stdErr,
  2945. bool _aborting );
  2946. TestCaseStats( TestCaseStats const& ) = default;
  2947. TestCaseStats( TestCaseStats && ) = default;
  2948. TestCaseStats& operator = ( TestCaseStats const& ) = default;
  2949. TestCaseStats& operator = ( TestCaseStats && ) = default;
  2950. virtual ~TestCaseStats();
  2951. TestCaseInfo testInfo;
  2952. Totals totals;
  2953. std::string stdOut;
  2954. std::string stdErr;
  2955. bool aborting;
  2956. };
  2957. struct TestGroupStats {
  2958. TestGroupStats( GroupInfo const& _groupInfo,
  2959. Totals const& _totals,
  2960. bool _aborting );
  2961. TestGroupStats( GroupInfo const& _groupInfo );
  2962. TestGroupStats( TestGroupStats const& ) = default;
  2963. TestGroupStats( TestGroupStats && ) = default;
  2964. TestGroupStats& operator = ( TestGroupStats const& ) = default;
  2965. TestGroupStats& operator = ( TestGroupStats && ) = default;
  2966. virtual ~TestGroupStats();
  2967. GroupInfo groupInfo;
  2968. Totals totals;
  2969. bool aborting;
  2970. };
  2971. struct TestRunStats {
  2972. TestRunStats( TestRunInfo const& _runInfo,
  2973. Totals const& _totals,
  2974. bool _aborting );
  2975. TestRunStats( TestRunStats const& ) = default;
  2976. TestRunStats( TestRunStats && ) = default;
  2977. TestRunStats& operator = ( TestRunStats const& ) = default;
  2978. TestRunStats& operator = ( TestRunStats && ) = default;
  2979. virtual ~TestRunStats();
  2980. TestRunInfo runInfo;
  2981. Totals totals;
  2982. bool aborting;
  2983. };
  2984. struct BenchmarkInfo {
  2985. std::string name;
  2986. };
  2987. struct BenchmarkStats {
  2988. BenchmarkInfo info;
  2989. std::size_t iterations;
  2990. uint64_t elapsedTimeInNanoseconds;
  2991. };
  2992. struct IStreamingReporter {
  2993. virtual ~IStreamingReporter() = default;
  2994. // Implementing class must also provide the following static methods:
  2995. // static std::string getDescription();
  2996. // static std::set<Verbosity> getSupportedVerbosities()
  2997. virtual ReporterPreferences getPreferences() const = 0;
  2998. virtual void noMatchingTestCases( std::string const& spec ) = 0;
  2999. virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0;
  3000. virtual void testGroupStarting( GroupInfo const& groupInfo ) = 0;
  3001. virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0;
  3002. virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0;
  3003. // *** experimental ***
  3004. virtual void benchmarkStarting( BenchmarkInfo const& ) {}
  3005. virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0;
  3006. // The return value indicates if the messages buffer should be cleared:
  3007. virtual bool assertionEnded( AssertionStats const& assertionStats ) = 0;
  3008. // *** experimental ***
  3009. virtual void benchmarkEnded( BenchmarkStats const& ) {}
  3010. virtual void sectionEnded( SectionStats const& sectionStats ) = 0;
  3011. virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0;
  3012. virtual void testGroupEnded( TestGroupStats const& testGroupStats ) = 0;
  3013. virtual void testRunEnded( TestRunStats const& testRunStats ) = 0;
  3014. virtual void skipTest( TestCaseInfo const& testInfo ) = 0;
  3015. // Default empty implementation provided
  3016. virtual void fatalErrorEncountered( StringRef name );
  3017. virtual bool isMulti() const;
  3018. };
  3019. using IStreamingReporterPtr = std::unique_ptr<IStreamingReporter>;
  3020. struct IReporterFactory {
  3021. virtual ~IReporterFactory();
  3022. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const = 0;
  3023. virtual std::string getDescription() const = 0;
  3024. };
  3025. using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
  3026. struct IReporterRegistry {
  3027. using FactoryMap = std::map<std::string, IReporterFactoryPtr>;
  3028. using Listeners = std::vector<IReporterFactoryPtr>;
  3029. virtual ~IReporterRegistry();
  3030. virtual IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const = 0;
  3031. virtual FactoryMap const& getFactories() const = 0;
  3032. virtual Listeners const& getListeners() const = 0;
  3033. };
  3034. } // end namespace Catch
  3035. // end catch_interfaces_reporter.h
  3036. #include <algorithm>
  3037. #include <cstring>
  3038. #include <cfloat>
  3039. #include <cstdio>
  3040. #include <cassert>
  3041. #include <memory>
  3042. #include <ostream>
  3043. namespace Catch {
  3044. void prepareExpandedExpression(AssertionResult& result);
  3045. // Returns double formatted as %.3f (format expected on output)
  3046. std::string getFormattedDuration( double duration );
  3047. template<typename DerivedT>
  3048. struct StreamingReporterBase : IStreamingReporter {
  3049. StreamingReporterBase( ReporterConfig const& _config )
  3050. : m_config( _config.fullConfig() ),
  3051. stream( _config.stream() )
  3052. {
  3053. m_reporterPrefs.shouldRedirectStdOut = false;
  3054. if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
  3055. throw std::domain_error( "Verbosity level not supported by this reporter" );
  3056. }
  3057. ReporterPreferences getPreferences() const override {
  3058. return m_reporterPrefs;
  3059. }
  3060. static std::set<Verbosity> getSupportedVerbosities() {
  3061. return { Verbosity::Normal };
  3062. }
  3063. ~StreamingReporterBase() override = default;
  3064. void noMatchingTestCases(std::string const&) override {}
  3065. void testRunStarting(TestRunInfo const& _testRunInfo) override {
  3066. currentTestRunInfo = _testRunInfo;
  3067. }
  3068. void testGroupStarting(GroupInfo const& _groupInfo) override {
  3069. currentGroupInfo = _groupInfo;
  3070. }
  3071. void testCaseStarting(TestCaseInfo const& _testInfo) override {
  3072. currentTestCaseInfo = _testInfo;
  3073. }
  3074. void sectionStarting(SectionInfo const& _sectionInfo) override {
  3075. m_sectionStack.push_back(_sectionInfo);
  3076. }
  3077. void sectionEnded(SectionStats const& /* _sectionStats */) override {
  3078. m_sectionStack.pop_back();
  3079. }
  3080. void testCaseEnded(TestCaseStats const& /* _testCaseStats */) override {
  3081. currentTestCaseInfo.reset();
  3082. }
  3083. void testGroupEnded(TestGroupStats const& /* _testGroupStats */) override {
  3084. currentGroupInfo.reset();
  3085. }
  3086. void testRunEnded(TestRunStats const& /* _testRunStats */) override {
  3087. currentTestCaseInfo.reset();
  3088. currentGroupInfo.reset();
  3089. currentTestRunInfo.reset();
  3090. }
  3091. void skipTest(TestCaseInfo const&) override {
  3092. // Don't do anything with this by default.
  3093. // It can optionally be overridden in the derived class.
  3094. }
  3095. IConfigPtr m_config;
  3096. std::ostream& stream;
  3097. LazyStat<TestRunInfo> currentTestRunInfo;
  3098. LazyStat<GroupInfo> currentGroupInfo;
  3099. LazyStat<TestCaseInfo> currentTestCaseInfo;
  3100. std::vector<SectionInfo> m_sectionStack;
  3101. ReporterPreferences m_reporterPrefs;
  3102. };
  3103. template<typename DerivedT>
  3104. struct CumulativeReporterBase : IStreamingReporter {
  3105. template<typename T, typename ChildNodeT>
  3106. struct Node {
  3107. explicit Node( T const& _value ) : value( _value ) {}
  3108. virtual ~Node() {}
  3109. using ChildNodes = std::vector<std::shared_ptr<ChildNodeT>>;
  3110. T value;
  3111. ChildNodes children;
  3112. };
  3113. struct SectionNode {
  3114. explicit SectionNode(SectionStats const& _stats) : stats(_stats) {}
  3115. virtual ~SectionNode() = default;
  3116. bool operator == (SectionNode const& other) const {
  3117. return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;
  3118. }
  3119. bool operator == (std::shared_ptr<SectionNode> const& other) const {
  3120. return operator==(*other);
  3121. }
  3122. SectionStats stats;
  3123. using ChildSections = std::vector<std::shared_ptr<SectionNode>>;
  3124. using Assertions = std::vector<AssertionStats>;
  3125. ChildSections childSections;
  3126. Assertions assertions;
  3127. std::string stdOut;
  3128. std::string stdErr;
  3129. };
  3130. struct BySectionInfo {
  3131. BySectionInfo( SectionInfo const& other ) : m_other( other ) {}
  3132. BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {}
  3133. bool operator() (std::shared_ptr<SectionNode> const& node) const {
  3134. return ((node->stats.sectionInfo.name == m_other.name) &&
  3135. (node->stats.sectionInfo.lineInfo == m_other.lineInfo));
  3136. }
  3137. void operator=(BySectionInfo const&) = delete;
  3138. private:
  3139. SectionInfo const& m_other;
  3140. };
  3141. using TestCaseNode = Node<TestCaseStats, SectionNode>;
  3142. using TestGroupNode = Node<TestGroupStats, TestCaseNode>;
  3143. using TestRunNode = Node<TestRunStats, TestGroupNode>;
  3144. CumulativeReporterBase( ReporterConfig const& _config )
  3145. : m_config( _config.fullConfig() ),
  3146. stream( _config.stream() )
  3147. {
  3148. m_reporterPrefs.shouldRedirectStdOut = false;
  3149. if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
  3150. throw std::domain_error( "Verbosity level not supported by this reporter" );
  3151. }
  3152. ~CumulativeReporterBase() override = default;
  3153. ReporterPreferences getPreferences() const override {
  3154. return m_reporterPrefs;
  3155. }
  3156. static std::set<Verbosity> getSupportedVerbosities() {
  3157. return { Verbosity::Normal };
  3158. }
  3159. void testRunStarting( TestRunInfo const& ) override {}
  3160. void testGroupStarting( GroupInfo const& ) override {}
  3161. void testCaseStarting( TestCaseInfo const& ) override {}
  3162. void sectionStarting( SectionInfo const& sectionInfo ) override {
  3163. SectionStats incompleteStats( sectionInfo, Counts(), 0, false );
  3164. std::shared_ptr<SectionNode> node;
  3165. if( m_sectionStack.empty() ) {
  3166. if( !m_rootSection )
  3167. m_rootSection = std::make_shared<SectionNode>( incompleteStats );
  3168. node = m_rootSection;
  3169. }
  3170. else {
  3171. SectionNode& parentNode = *m_sectionStack.back();
  3172. auto it =
  3173. std::find_if( parentNode.childSections.begin(),
  3174. parentNode.childSections.end(),
  3175. BySectionInfo( sectionInfo ) );
  3176. if( it == parentNode.childSections.end() ) {
  3177. node = std::make_shared<SectionNode>( incompleteStats );
  3178. parentNode.childSections.push_back( node );
  3179. }
  3180. else
  3181. node = *it;
  3182. }
  3183. m_sectionStack.push_back( node );
  3184. m_deepestSection = std::move(node);
  3185. }
  3186. void assertionStarting(AssertionInfo const&) override {}
  3187. bool assertionEnded(AssertionStats const& assertionStats) override {
  3188. assert(!m_sectionStack.empty());
  3189. // AssertionResult holds a pointer to a temporary DecomposedExpression,
  3190. // which getExpandedExpression() calls to build the expression string.
  3191. // Our section stack copy of the assertionResult will likely outlive the
  3192. // temporary, so it must be expanded or discarded now to avoid calling
  3193. // a destroyed object later.
  3194. prepareExpandedExpression(const_cast<AssertionResult&>( assertionStats.assertionResult ) );
  3195. SectionNode& sectionNode = *m_sectionStack.back();
  3196. sectionNode.assertions.push_back(assertionStats);
  3197. return true;
  3198. }
  3199. void sectionEnded(SectionStats const& sectionStats) override {
  3200. assert(!m_sectionStack.empty());
  3201. SectionNode& node = *m_sectionStack.back();
  3202. node.stats = sectionStats;
  3203. m_sectionStack.pop_back();
  3204. }
  3205. void testCaseEnded(TestCaseStats const& testCaseStats) override {
  3206. auto node = std::make_shared<TestCaseNode>(testCaseStats);
  3207. assert(m_sectionStack.size() == 0);
  3208. node->children.push_back(m_rootSection);
  3209. m_testCases.push_back(node);
  3210. m_rootSection.reset();
  3211. assert(m_deepestSection);
  3212. m_deepestSection->stdOut = testCaseStats.stdOut;
  3213. m_deepestSection->stdErr = testCaseStats.stdErr;
  3214. }
  3215. void testGroupEnded(TestGroupStats const& testGroupStats) override {
  3216. auto node = std::make_shared<TestGroupNode>(testGroupStats);
  3217. node->children.swap(m_testCases);
  3218. m_testGroups.push_back(node);
  3219. }
  3220. void testRunEnded(TestRunStats const& testRunStats) override {
  3221. auto node = std::make_shared<TestRunNode>(testRunStats);
  3222. node->children.swap(m_testGroups);
  3223. m_testRuns.push_back(node);
  3224. testRunEndedCumulative();
  3225. }
  3226. virtual void testRunEndedCumulative() = 0;
  3227. void skipTest(TestCaseInfo const&) override {}
  3228. IConfigPtr m_config;
  3229. std::ostream& stream;
  3230. std::vector<AssertionStats> m_assertions;
  3231. std::vector<std::vector<std::shared_ptr<SectionNode>>> m_sections;
  3232. std::vector<std::shared_ptr<TestCaseNode>> m_testCases;
  3233. std::vector<std::shared_ptr<TestGroupNode>> m_testGroups;
  3234. std::vector<std::shared_ptr<TestRunNode>> m_testRuns;
  3235. std::shared_ptr<SectionNode> m_rootSection;
  3236. std::shared_ptr<SectionNode> m_deepestSection;
  3237. std::vector<std::shared_ptr<SectionNode>> m_sectionStack;
  3238. ReporterPreferences m_reporterPrefs;
  3239. };
  3240. template<char C>
  3241. char const* getLineOfChars() {
  3242. static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
  3243. if( !*line ) {
  3244. std::memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 );
  3245. line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0;
  3246. }
  3247. return line;
  3248. }
  3249. struct TestEventListenerBase : StreamingReporterBase<TestEventListenerBase> {
  3250. TestEventListenerBase( ReporterConfig const& _config );
  3251. void assertionStarting(AssertionInfo const&) override;
  3252. bool assertionEnded(AssertionStats const&) override;
  3253. };
  3254. } // end namespace Catch
  3255. // end catch_reporter_bases.hpp
  3256. // start catch_console_colour.h
  3257. namespace Catch {
  3258. struct Colour {
  3259. enum Code {
  3260. None = 0,
  3261. White,
  3262. Red,
  3263. Green,
  3264. Blue,
  3265. Cyan,
  3266. Yellow,
  3267. Grey,
  3268. Bright = 0x10,
  3269. BrightRed = Bright | Red,
  3270. BrightGreen = Bright | Green,
  3271. LightGrey = Bright | Grey,
  3272. BrightWhite = Bright | White,
  3273. BrightYellow = Bright | Yellow,
  3274. // By intention
  3275. FileName = LightGrey,
  3276. Warning = BrightYellow,
  3277. ResultError = BrightRed,
  3278. ResultSuccess = BrightGreen,
  3279. ResultExpectedFailure = Warning,
  3280. Error = BrightRed,
  3281. Success = Green,
  3282. OriginalExpression = Cyan,
  3283. ReconstructedExpression = BrightYellow,
  3284. SecondaryText = LightGrey,
  3285. Headers = White
  3286. };
  3287. // Use constructed object for RAII guard
  3288. Colour( Code _colourCode );
  3289. Colour( Colour&& other ) noexcept;
  3290. Colour& operator=( Colour&& other ) noexcept;
  3291. ~Colour();
  3292. // Use static method for one-shot changes
  3293. static void use( Code _colourCode );
  3294. private:
  3295. bool m_moved = false;
  3296. };
  3297. std::ostream& operator << ( std::ostream& os, Colour const& );
  3298. } // end namespace Catch
  3299. // end catch_console_colour.h
  3300. // start catch_reporter_registrars.hpp
  3301. namespace Catch {
  3302. template<typename T>
  3303. class ReporterRegistrar {
  3304. class ReporterFactory : public IReporterFactory {
  3305. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const override {
  3306. return std::unique_ptr<T>( new T( config ) );
  3307. }
  3308. virtual std::string getDescription() const override {
  3309. return T::getDescription();
  3310. }
  3311. };
  3312. public:
  3313. explicit ReporterRegistrar( std::string const& name ) {
  3314. getMutableRegistryHub().registerReporter( name, std::make_shared<ReporterFactory>() );
  3315. }
  3316. };
  3317. template<typename T>
  3318. class ListenerRegistrar {
  3319. class ListenerFactory : public IReporterFactory {
  3320. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const override {
  3321. return std::unique_ptr<T>( new T( config ) );
  3322. }
  3323. virtual std::string getDescription() const override {
  3324. return std::string();
  3325. }
  3326. };
  3327. public:
  3328. ListenerRegistrar() {
  3329. getMutableRegistryHub().registerListener( std::make_shared<ListenerFactory>() );
  3330. }
  3331. };
  3332. }
  3333. #if !defined(CATCH_CONFIG_DISABLE)
  3334. #define CATCH_REGISTER_REPORTER( name, reporterType ) \
  3335. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  3336. namespace{ Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); } \
  3337. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  3338. #define CATCH_REGISTER_LISTENER( listenerType ) \
  3339. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  3340. namespace{ Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; } \
  3341. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  3342. #else // CATCH_CONFIG_DISABLE
  3343. #define CATCH_REGISTER_REPORTER(name, reporterType)
  3344. #define CATCH_REGISTER_LISTENER(listenerType)
  3345. #endif // CATCH_CONFIG_DISABLE
  3346. // end catch_reporter_registrars.hpp
  3347. // Allow users to base their work off existing reporters
  3348. // start catch_reporter_compact.h
  3349. namespace Catch {
  3350. struct CompactReporter : StreamingReporterBase<CompactReporter> {
  3351. using StreamingReporterBase::StreamingReporterBase;
  3352. ~CompactReporter() override;
  3353. static std::string getDescription();
  3354. ReporterPreferences getPreferences() const override;
  3355. void noMatchingTestCases(std::string const& spec) override;
  3356. void assertionStarting(AssertionInfo const&) override;
  3357. bool assertionEnded(AssertionStats const& _assertionStats) override;
  3358. void sectionEnded(SectionStats const& _sectionStats) override;
  3359. void testRunEnded(TestRunStats const& _testRunStats) override;
  3360. };
  3361. } // end namespace Catch
  3362. // end catch_reporter_compact.h
  3363. // start catch_reporter_console.h
  3364. #if defined(_MSC_VER)
  3365. #pragma warning(push)
  3366. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  3367. // Note that 4062 (not all labels are handled
  3368. // and default is missing) is enabled
  3369. #endif
  3370. namespace Catch {
  3371. // Fwd decls
  3372. struct SummaryColumn;
  3373. class TablePrinter;
  3374. struct ConsoleReporter : StreamingReporterBase<ConsoleReporter> {
  3375. std::unique_ptr<TablePrinter> m_tablePrinter;
  3376. ConsoleReporter(ReporterConfig const& config);
  3377. ~ConsoleReporter() override;
  3378. static std::string getDescription();
  3379. void noMatchingTestCases(std::string const& spec) override;
  3380. void assertionStarting(AssertionInfo const&) override;
  3381. bool assertionEnded(AssertionStats const& _assertionStats) override;
  3382. void sectionStarting(SectionInfo const& _sectionInfo) override;
  3383. void sectionEnded(SectionStats const& _sectionStats) override;
  3384. void benchmarkStarting(BenchmarkInfo const& info) override;
  3385. void benchmarkEnded(BenchmarkStats const& stats) override;
  3386. void testCaseEnded(TestCaseStats const& _testCaseStats) override;
  3387. void testGroupEnded(TestGroupStats const& _testGroupStats) override;
  3388. void testRunEnded(TestRunStats const& _testRunStats) override;
  3389. private:
  3390. void lazyPrint();
  3391. void lazyPrintWithoutClosingBenchmarkTable();
  3392. void lazyPrintRunInfo();
  3393. void lazyPrintGroupInfo();
  3394. void printTestCaseAndSectionHeader();
  3395. void printClosedHeader(std::string const& _name);
  3396. void printOpenHeader(std::string const& _name);
  3397. // if string has a : in first line will set indent to follow it on
  3398. // subsequent lines
  3399. void printHeaderString(std::string const& _string, std::size_t indent = 0);
  3400. void printTotals(Totals const& totals);
  3401. void printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row);
  3402. void printTotalsDivider(Totals const& totals);
  3403. void printSummaryDivider();
  3404. private:
  3405. bool m_headerPrinted = false;
  3406. };
  3407. } // end namespace Catch
  3408. #if defined(_MSC_VER)
  3409. #pragma warning(pop)
  3410. #endif
  3411. // end catch_reporter_console.h
  3412. // start catch_reporter_junit.h
  3413. // start catch_xmlwriter.h
  3414. #include <vector>
  3415. namespace Catch {
  3416. class XmlEncode {
  3417. public:
  3418. enum ForWhat { ForTextNodes, ForAttributes };
  3419. XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes );
  3420. void encodeTo( std::ostream& os ) const;
  3421. friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode );
  3422. private:
  3423. std::string m_str;
  3424. ForWhat m_forWhat;
  3425. };
  3426. class XmlWriter {
  3427. public:
  3428. class ScopedElement {
  3429. public:
  3430. ScopedElement( XmlWriter* writer );
  3431. ScopedElement( ScopedElement&& other ) noexcept;
  3432. ScopedElement& operator=( ScopedElement&& other ) noexcept;
  3433. ~ScopedElement();
  3434. ScopedElement& writeText( std::string const& text, bool indent = true );
  3435. template<typename T>
  3436. ScopedElement& writeAttribute( std::string const& name, T const& attribute ) {
  3437. m_writer->writeAttribute( name, attribute );
  3438. return *this;
  3439. }
  3440. private:
  3441. mutable XmlWriter* m_writer = nullptr;
  3442. };
  3443. XmlWriter( std::ostream& os = Catch::cout() );
  3444. ~XmlWriter();
  3445. XmlWriter( XmlWriter const& ) = delete;
  3446. XmlWriter& operator=( XmlWriter const& ) = delete;
  3447. XmlWriter& startElement( std::string const& name );
  3448. ScopedElement scopedElement( std::string const& name );
  3449. XmlWriter& endElement();
  3450. XmlWriter& writeAttribute( std::string const& name, std::string const& attribute );
  3451. XmlWriter& writeAttribute( std::string const& name, bool attribute );
  3452. template<typename T>
  3453. XmlWriter& writeAttribute( std::string const& name, T const& attribute ) {
  3454. ReusableStringStream rss;
  3455. rss << attribute;
  3456. return writeAttribute( name, rss.str() );
  3457. }
  3458. XmlWriter& writeText( std::string const& text, bool indent = true );
  3459. XmlWriter& writeComment( std::string const& text );
  3460. void writeStylesheetRef( std::string const& url );
  3461. XmlWriter& writeBlankLine();
  3462. void ensureTagClosed();
  3463. private:
  3464. void writeDeclaration();
  3465. void newlineIfNecessary();
  3466. bool m_tagIsOpen = false;
  3467. bool m_needsNewline = false;
  3468. std::vector<std::string> m_tags;
  3469. std::string m_indent;
  3470. std::ostream& m_os;
  3471. };
  3472. }
  3473. // end catch_xmlwriter.h
  3474. namespace Catch {
  3475. class JunitReporter : public CumulativeReporterBase<JunitReporter> {
  3476. public:
  3477. JunitReporter(ReporterConfig const& _config);
  3478. ~JunitReporter() override;
  3479. static std::string getDescription();
  3480. void noMatchingTestCases(std::string const& /*spec*/) override;
  3481. void testRunStarting(TestRunInfo const& runInfo) override;
  3482. void testGroupStarting(GroupInfo const& groupInfo) override;
  3483. void testCaseStarting(TestCaseInfo const& testCaseInfo) override;
  3484. bool assertionEnded(AssertionStats const& assertionStats) override;
  3485. void testCaseEnded(TestCaseStats const& testCaseStats) override;
  3486. void testGroupEnded(TestGroupStats const& testGroupStats) override;
  3487. void testRunEndedCumulative() override;
  3488. void writeGroup(TestGroupNode const& groupNode, double suiteTime);
  3489. void writeTestCase(TestCaseNode const& testCaseNode);
  3490. void writeSection(std::string const& className,
  3491. std::string const& rootName,
  3492. SectionNode const& sectionNode);
  3493. void writeAssertions(SectionNode const& sectionNode);
  3494. void writeAssertion(AssertionStats const& stats);
  3495. XmlWriter xml;
  3496. Timer suiteTimer;
  3497. std::string stdOutForSuite;
  3498. std::string stdErrForSuite;
  3499. unsigned int unexpectedExceptions = 0;
  3500. bool m_okToFail = false;
  3501. };
  3502. } // end namespace Catch
  3503. // end catch_reporter_junit.h
  3504. // start catch_reporter_xml.h
  3505. namespace Catch {
  3506. class XmlReporter : public StreamingReporterBase<XmlReporter> {
  3507. public:
  3508. XmlReporter(ReporterConfig const& _config);
  3509. ~XmlReporter() override;
  3510. static std::string getDescription();
  3511. virtual std::string getStylesheetRef() const;
  3512. void writeSourceInfo(SourceLineInfo const& sourceInfo);
  3513. public: // StreamingReporterBase
  3514. void noMatchingTestCases(std::string const& s) override;
  3515. void testRunStarting(TestRunInfo const& testInfo) override;
  3516. void testGroupStarting(GroupInfo const& groupInfo) override;
  3517. void testCaseStarting(TestCaseInfo const& testInfo) override;
  3518. void sectionStarting(SectionInfo const& sectionInfo) override;
  3519. void assertionStarting(AssertionInfo const&) override;
  3520. bool assertionEnded(AssertionStats const& assertionStats) override;
  3521. void sectionEnded(SectionStats const& sectionStats) override;
  3522. void testCaseEnded(TestCaseStats const& testCaseStats) override;
  3523. void testGroupEnded(TestGroupStats const& testGroupStats) override;
  3524. void testRunEnded(TestRunStats const& testRunStats) override;
  3525. private:
  3526. Timer m_testCaseTimer;
  3527. XmlWriter m_xml;
  3528. int m_sectionDepth = 0;
  3529. };
  3530. } // end namespace Catch
  3531. // end catch_reporter_xml.h
  3532. // end catch_external_interfaces.h
  3533. #endif
  3534. #endif // ! CATCH_CONFIG_IMPL_ONLY
  3535. #ifdef CATCH_IMPL
  3536. // start catch_impl.hpp
  3537. #ifdef __clang__
  3538. #pragma clang diagnostic push
  3539. #pragma clang diagnostic ignored "-Wweak-vtables"
  3540. #endif
  3541. // Keep these here for external reporters
  3542. // start catch_test_case_tracker.h
  3543. #include <string>
  3544. #include <vector>
  3545. #include <memory>
  3546. namespace Catch {
  3547. namespace TestCaseTracking {
  3548. struct NameAndLocation {
  3549. std::string name;
  3550. SourceLineInfo location;
  3551. NameAndLocation( std::string const& _name, SourceLineInfo const& _location );
  3552. };
  3553. struct ITracker;
  3554. using ITrackerPtr = std::shared_ptr<ITracker>;
  3555. struct ITracker {
  3556. virtual ~ITracker();
  3557. // static queries
  3558. virtual NameAndLocation const& nameAndLocation() const = 0;
  3559. // dynamic queries
  3560. virtual bool isComplete() const = 0; // Successfully completed or failed
  3561. virtual bool isSuccessfullyCompleted() const = 0;
  3562. virtual bool isOpen() const = 0; // Started but not complete
  3563. virtual bool hasChildren() const = 0;
  3564. virtual ITracker& parent() = 0;
  3565. // actions
  3566. virtual void close() = 0; // Successfully complete
  3567. virtual void fail() = 0;
  3568. virtual void markAsNeedingAnotherRun() = 0;
  3569. virtual void addChild( ITrackerPtr const& child ) = 0;
  3570. virtual ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) = 0;
  3571. virtual void openChild() = 0;
  3572. // Debug/ checking
  3573. virtual bool isSectionTracker() const = 0;
  3574. virtual bool isIndexTracker() const = 0;
  3575. };
  3576. class TrackerContext {
  3577. enum RunState {
  3578. NotStarted,
  3579. Executing,
  3580. CompletedCycle
  3581. };
  3582. ITrackerPtr m_rootTracker;
  3583. ITracker* m_currentTracker = nullptr;
  3584. RunState m_runState = NotStarted;
  3585. public:
  3586. static TrackerContext& instance();
  3587. ITracker& startRun();
  3588. void endRun();
  3589. void startCycle();
  3590. void completeCycle();
  3591. bool completedCycle() const;
  3592. ITracker& currentTracker();
  3593. void setCurrentTracker( ITracker* tracker );
  3594. };
  3595. class TrackerBase : public ITracker {
  3596. protected:
  3597. enum CycleState {
  3598. NotStarted,
  3599. Executing,
  3600. ExecutingChildren,
  3601. NeedsAnotherRun,
  3602. CompletedSuccessfully,
  3603. Failed
  3604. };
  3605. class TrackerHasName {
  3606. NameAndLocation m_nameAndLocation;
  3607. public:
  3608. TrackerHasName( NameAndLocation const& nameAndLocation );
  3609. bool operator ()( ITrackerPtr const& tracker ) const;
  3610. };
  3611. using Children = std::vector<ITrackerPtr>;
  3612. NameAndLocation m_nameAndLocation;
  3613. TrackerContext& m_ctx;
  3614. ITracker* m_parent;
  3615. Children m_children;
  3616. CycleState m_runState = NotStarted;
  3617. public:
  3618. TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  3619. NameAndLocation const& nameAndLocation() const override;
  3620. bool isComplete() const override;
  3621. bool isSuccessfullyCompleted() const override;
  3622. bool isOpen() const override;
  3623. bool hasChildren() const override;
  3624. void addChild( ITrackerPtr const& child ) override;
  3625. ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) override;
  3626. ITracker& parent() override;
  3627. void openChild() override;
  3628. bool isSectionTracker() const override;
  3629. bool isIndexTracker() const override;
  3630. void open();
  3631. void close() override;
  3632. void fail() override;
  3633. void markAsNeedingAnotherRun() override;
  3634. private:
  3635. void moveToParent();
  3636. void moveToThis();
  3637. };
  3638. class SectionTracker : public TrackerBase {
  3639. std::vector<std::string> m_filters;
  3640. public:
  3641. SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  3642. bool isSectionTracker() const override;
  3643. static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation );
  3644. void tryOpen();
  3645. void addInitialFilters( std::vector<std::string> const& filters );
  3646. void addNextFilters( std::vector<std::string> const& filters );
  3647. };
  3648. class IndexTracker : public TrackerBase {
  3649. int m_size;
  3650. int m_index = -1;
  3651. public:
  3652. IndexTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent, int size );
  3653. bool isIndexTracker() const override;
  3654. void close() override;
  3655. static IndexTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation, int size );
  3656. int index() const;
  3657. void moveNext();
  3658. };
  3659. } // namespace TestCaseTracking
  3660. using TestCaseTracking::ITracker;
  3661. using TestCaseTracking::TrackerContext;
  3662. using TestCaseTracking::SectionTracker;
  3663. using TestCaseTracking::IndexTracker;
  3664. } // namespace Catch
  3665. // end catch_test_case_tracker.h
  3666. // start catch_leak_detector.h
  3667. namespace Catch {
  3668. struct LeakDetector {
  3669. LeakDetector();
  3670. };
  3671. }
  3672. // end catch_leak_detector.h
  3673. // Cpp files will be included in the single-header file here
  3674. // start catch_approx.cpp
  3675. #include <cmath>
  3676. #include <limits>
  3677. namespace {
  3678. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  3679. // But without the subtraction to allow for INFINITY in comparison
  3680. bool marginComparison(double lhs, double rhs, double margin) {
  3681. return (lhs + margin >= rhs) && (rhs + margin >= lhs);
  3682. }
  3683. }
  3684. namespace Catch {
  3685. namespace Detail {
  3686. Approx::Approx ( double value )
  3687. : m_epsilon( std::numeric_limits<float>::epsilon()*100 ),
  3688. m_margin( 0.0 ),
  3689. m_scale( 0.0 ),
  3690. m_value( value )
  3691. {}
  3692. Approx Approx::custom() {
  3693. return Approx( 0 );
  3694. }
  3695. std::string Approx::toString() const {
  3696. ReusableStringStream rss;
  3697. rss << "Approx( " << ::Catch::Detail::stringify( m_value ) << " )";
  3698. return rss.str();
  3699. }
  3700. bool Approx::equalityComparisonImpl(const double other) const {
  3701. // First try with fixed margin, then compute margin based on epsilon, scale and Approx's value
  3702. // Thanks to Richard Harris for his help refining the scaled margin value
  3703. return marginComparison(m_value, other, m_margin) || marginComparison(m_value, other, m_epsilon * (m_scale + std::fabs(m_value)));
  3704. }
  3705. } // end namespace Detail
  3706. std::string StringMaker<Catch::Detail::Approx>::convert(Catch::Detail::Approx const& value) {
  3707. return value.toString();
  3708. }
  3709. } // end namespace Catch
  3710. // end catch_approx.cpp
  3711. // start catch_assertionhandler.cpp
  3712. // start catch_context.h
  3713. #include <memory>
  3714. namespace Catch {
  3715. struct IResultCapture;
  3716. struct IRunner;
  3717. struct IConfig;
  3718. struct IMutableContext;
  3719. using IConfigPtr = std::shared_ptr<IConfig const>;
  3720. struct IContext
  3721. {
  3722. virtual ~IContext();
  3723. virtual IResultCapture* getResultCapture() = 0;
  3724. virtual IRunner* getRunner() = 0;
  3725. virtual IConfigPtr const& getConfig() const = 0;
  3726. };
  3727. struct IMutableContext : IContext
  3728. {
  3729. virtual ~IMutableContext();
  3730. virtual void setResultCapture( IResultCapture* resultCapture ) = 0;
  3731. virtual void setRunner( IRunner* runner ) = 0;
  3732. virtual void setConfig( IConfigPtr const& config ) = 0;
  3733. private:
  3734. static IMutableContext *currentContext;
  3735. friend IMutableContext& getCurrentMutableContext();
  3736. friend void cleanUpContext();
  3737. static void createContext();
  3738. };
  3739. inline IMutableContext& getCurrentMutableContext()
  3740. {
  3741. if( !IMutableContext::currentContext )
  3742. IMutableContext::createContext();
  3743. return *IMutableContext::currentContext;
  3744. }
  3745. inline IContext& getCurrentContext()
  3746. {
  3747. return getCurrentMutableContext();
  3748. }
  3749. void cleanUpContext();
  3750. }
  3751. // end catch_context.h
  3752. // start catch_debugger.h
  3753. namespace Catch {
  3754. bool isDebuggerActive();
  3755. }
  3756. #ifdef CATCH_PLATFORM_MAC
  3757. #define CATCH_TRAP() __asm__("int $3\n" : : ) /* NOLINT */
  3758. #elif defined(CATCH_PLATFORM_LINUX)
  3759. // If we can use inline assembler, do it because this allows us to break
  3760. // directly at the location of the failing check instead of breaking inside
  3761. // raise() called from it, i.e. one stack frame below.
  3762. #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64))
  3763. #define CATCH_TRAP() asm volatile ("int $3") /* NOLINT */
  3764. #else // Fall back to the generic way.
  3765. #include <signal.h>
  3766. #define CATCH_TRAP() raise(SIGTRAP)
  3767. #endif
  3768. #elif defined(_MSC_VER)
  3769. #define CATCH_TRAP() __debugbreak()
  3770. #elif defined(__MINGW32__)
  3771. extern "C" __declspec(dllimport) void __stdcall DebugBreak();
  3772. #define CATCH_TRAP() DebugBreak()
  3773. #endif
  3774. #ifdef CATCH_TRAP
  3775. #define CATCH_BREAK_INTO_DEBUGGER() if( Catch::isDebuggerActive() ) { CATCH_TRAP(); }
  3776. #else
  3777. namespace Catch {
  3778. inline void doNothing() {}
  3779. }
  3780. #define CATCH_BREAK_INTO_DEBUGGER() Catch::doNothing()
  3781. #endif
  3782. // end catch_debugger.h
  3783. // start catch_run_context.h
  3784. // start catch_fatal_condition.h
  3785. // start catch_windows_h_proxy.h
  3786. #if defined(CATCH_PLATFORM_WINDOWS)
  3787. #if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX)
  3788. # define CATCH_DEFINED_NOMINMAX
  3789. # define NOMINMAX
  3790. #endif
  3791. #if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN)
  3792. # define CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  3793. # define WIN32_LEAN_AND_MEAN
  3794. #endif
  3795. #ifdef __AFXDLL
  3796. #include <AfxWin.h>
  3797. #else
  3798. #include <windows.h>
  3799. #endif
  3800. #ifdef CATCH_DEFINED_NOMINMAX
  3801. # undef NOMINMAX
  3802. #endif
  3803. #ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  3804. # undef WIN32_LEAN_AND_MEAN
  3805. #endif
  3806. #endif // defined(CATCH_PLATFORM_WINDOWS)
  3807. // end catch_windows_h_proxy.h
  3808. #if defined( CATCH_CONFIG_WINDOWS_SEH )
  3809. namespace Catch {
  3810. struct FatalConditionHandler {
  3811. static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo);
  3812. FatalConditionHandler();
  3813. static void reset();
  3814. ~FatalConditionHandler();
  3815. private:
  3816. static bool isSet;
  3817. static ULONG guaranteeSize;
  3818. static PVOID exceptionHandlerHandle;
  3819. };
  3820. } // namespace Catch
  3821. #elif defined ( CATCH_CONFIG_POSIX_SIGNALS )
  3822. #include <signal.h>
  3823. namespace Catch {
  3824. struct FatalConditionHandler {
  3825. static bool isSet;
  3826. static struct sigaction oldSigActions[];
  3827. static stack_t oldSigStack;
  3828. static char altStackMem[];
  3829. static void handleSignal( int sig );
  3830. FatalConditionHandler();
  3831. ~FatalConditionHandler();
  3832. static void reset();
  3833. };
  3834. } // namespace Catch
  3835. #else
  3836. namespace Catch {
  3837. struct FatalConditionHandler {
  3838. void reset();
  3839. };
  3840. }
  3841. #endif
  3842. // end catch_fatal_condition.h
  3843. #include <string>
  3844. namespace Catch {
  3845. struct IMutableContext;
  3846. ///////////////////////////////////////////////////////////////////////////
  3847. class RunContext : public IResultCapture, public IRunner {
  3848. public:
  3849. RunContext( RunContext const& ) = delete;
  3850. RunContext& operator =( RunContext const& ) = delete;
  3851. explicit RunContext( IConfigPtr const& _config, IStreamingReporterPtr&& reporter );
  3852. ~RunContext() override;
  3853. void testGroupStarting( std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount );
  3854. void testGroupEnded( std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount );
  3855. Totals runTest(TestCase const& testCase);
  3856. IConfigPtr config() const;
  3857. IStreamingReporter& reporter() const;
  3858. public: // IResultCapture
  3859. // Assertion handlers
  3860. void handleExpr
  3861. ( AssertionInfo const& info,
  3862. ITransientExpression const& expr,
  3863. AssertionReaction& reaction ) override;
  3864. void handleMessage
  3865. ( AssertionInfo const& info,
  3866. ResultWas::OfType resultType,
  3867. StringRef const& message,
  3868. AssertionReaction& reaction ) override;
  3869. void handleUnexpectedExceptionNotThrown
  3870. ( AssertionInfo const& info,
  3871. AssertionReaction& reaction ) override;
  3872. void handleUnexpectedInflightException
  3873. ( AssertionInfo const& info,
  3874. std::string const& message,
  3875. AssertionReaction& reaction ) override;
  3876. void handleIncomplete
  3877. ( AssertionInfo const& info ) override;
  3878. void handleNonExpr
  3879. ( AssertionInfo const &info,
  3880. ResultWas::OfType resultType,
  3881. AssertionReaction &reaction ) override;
  3882. bool sectionStarted( SectionInfo const& sectionInfo, Counts& assertions ) override;
  3883. void sectionEnded( SectionEndInfo const& endInfo ) override;
  3884. void sectionEndedEarly( SectionEndInfo const& endInfo ) override;
  3885. void benchmarkStarting( BenchmarkInfo const& info ) override;
  3886. void benchmarkEnded( BenchmarkStats const& stats ) override;
  3887. void pushScopedMessage( MessageInfo const& message ) override;
  3888. void popScopedMessage( MessageInfo const& message ) override;
  3889. std::string getCurrentTestName() const override;
  3890. const AssertionResult* getLastResult() const override;
  3891. void exceptionEarlyReported() override;
  3892. void handleFatalErrorCondition( StringRef message ) override;
  3893. bool lastAssertionPassed() override;
  3894. void assertionPassed() override;
  3895. public:
  3896. // !TBD We need to do this another way!
  3897. bool aborting() const final;
  3898. private:
  3899. void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr );
  3900. void invokeActiveTestCase();
  3901. void resetAssertionInfo();
  3902. bool testForMissingAssertions( Counts& assertions );
  3903. void assertionEnded( AssertionResult const& result );
  3904. void reportExpr
  3905. ( AssertionInfo const &info,
  3906. ResultWas::OfType resultType,
  3907. ITransientExpression const *expr,
  3908. bool negated );
  3909. void populateReaction( AssertionReaction& reaction );
  3910. private:
  3911. void handleUnfinishedSections();
  3912. TestRunInfo m_runInfo;
  3913. IMutableContext& m_context;
  3914. TestCase const* m_activeTestCase = nullptr;
  3915. ITracker* m_testCaseTracker;
  3916. Option<AssertionResult> m_lastResult;
  3917. IConfigPtr m_config;
  3918. Totals m_totals;
  3919. IStreamingReporterPtr m_reporter;
  3920. std::vector<MessageInfo> m_messages;
  3921. AssertionInfo m_lastAssertionInfo;
  3922. std::vector<SectionEndInfo> m_unfinishedSections;
  3923. std::vector<ITracker*> m_activeSections;
  3924. TrackerContext m_trackerContext;
  3925. bool m_lastAssertionPassed = false;
  3926. bool m_shouldReportUnexpected = true;
  3927. bool m_includeSuccessfulResults;
  3928. };
  3929. } // end namespace Catch
  3930. // end catch_run_context.h
  3931. namespace Catch {
  3932. auto operator <<( std::ostream& os, ITransientExpression const& expr ) -> std::ostream& {
  3933. expr.streamReconstructedExpression( os );
  3934. return os;
  3935. }
  3936. LazyExpression::LazyExpression( bool isNegated )
  3937. : m_isNegated( isNegated )
  3938. {}
  3939. LazyExpression::LazyExpression( LazyExpression const& other ) : m_isNegated( other.m_isNegated ) {}
  3940. LazyExpression::operator bool() const {
  3941. return m_transientExpression != nullptr;
  3942. }
  3943. auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream& {
  3944. if( lazyExpr.m_isNegated )
  3945. os << "!";
  3946. if( lazyExpr ) {
  3947. if( lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression() )
  3948. os << "(" << *lazyExpr.m_transientExpression << ")";
  3949. else
  3950. os << *lazyExpr.m_transientExpression;
  3951. }
  3952. else {
  3953. os << "{** error - unchecked empty expression requested **}";
  3954. }
  3955. return os;
  3956. }
  3957. AssertionHandler::AssertionHandler
  3958. ( StringRef macroName,
  3959. SourceLineInfo const& lineInfo,
  3960. StringRef capturedExpression,
  3961. ResultDisposition::Flags resultDisposition )
  3962. : m_assertionInfo{ macroName, lineInfo, capturedExpression, resultDisposition },
  3963. m_resultCapture( getResultCapture() )
  3964. {}
  3965. void AssertionHandler::handleExpr( ITransientExpression const& expr ) {
  3966. m_resultCapture.handleExpr( m_assertionInfo, expr, m_reaction );
  3967. }
  3968. void AssertionHandler::handleMessage(ResultWas::OfType resultType, StringRef const& message) {
  3969. m_resultCapture.handleMessage( m_assertionInfo, resultType, message, m_reaction );
  3970. }
  3971. auto AssertionHandler::allowThrows() const -> bool {
  3972. return getCurrentContext().getConfig()->allowThrows();
  3973. }
  3974. void AssertionHandler::complete() {
  3975. setCompleted();
  3976. if( m_reaction.shouldDebugBreak ) {
  3977. // If you find your debugger stopping you here then go one level up on the
  3978. // call-stack for the code that caused it (typically a failed assertion)
  3979. // (To go back to the test and change execution, jump over the throw, next)
  3980. CATCH_BREAK_INTO_DEBUGGER();
  3981. }
  3982. if( m_reaction.shouldThrow )
  3983. throw Catch::TestFailureException();
  3984. }
  3985. void AssertionHandler::setCompleted() {
  3986. m_completed = true;
  3987. }
  3988. void AssertionHandler::handleUnexpectedInflightException() {
  3989. m_resultCapture.handleUnexpectedInflightException( m_assertionInfo, Catch::translateActiveException(), m_reaction );
  3990. }
  3991. void AssertionHandler::handleExceptionThrownAsExpected() {
  3992. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  3993. }
  3994. void AssertionHandler::handleExceptionNotThrownAsExpected() {
  3995. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  3996. }
  3997. void AssertionHandler::handleUnexpectedExceptionNotThrown() {
  3998. m_resultCapture.handleUnexpectedExceptionNotThrown( m_assertionInfo, m_reaction );
  3999. }
  4000. void AssertionHandler::handleThrowingCallSkipped() {
  4001. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  4002. }
  4003. // This is the overload that takes a string and infers the Equals matcher from it
  4004. // The more general overload, that takes any string matcher, is in catch_capture_matchers.cpp
  4005. void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef matcherString ) {
  4006. handleExceptionMatchExpr( handler, Matchers::Equals( str ), matcherString );
  4007. }
  4008. } // namespace Catch
  4009. // end catch_assertionhandler.cpp
  4010. // start catch_assertionresult.cpp
  4011. namespace Catch {
  4012. AssertionResultData::AssertionResultData(ResultWas::OfType _resultType, LazyExpression const & _lazyExpression):
  4013. lazyExpression(_lazyExpression),
  4014. resultType(_resultType) {}
  4015. std::string AssertionResultData::reconstructExpression() const {
  4016. if( reconstructedExpression.empty() ) {
  4017. if( lazyExpression ) {
  4018. ReusableStringStream rss;
  4019. rss << lazyExpression;
  4020. reconstructedExpression = rss.str();
  4021. }
  4022. }
  4023. return reconstructedExpression;
  4024. }
  4025. AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data )
  4026. : m_info( info ),
  4027. m_resultData( data )
  4028. {}
  4029. // Result was a success
  4030. bool AssertionResult::succeeded() const {
  4031. return Catch::isOk( m_resultData.resultType );
  4032. }
  4033. // Result was a success, or failure is suppressed
  4034. bool AssertionResult::isOk() const {
  4035. return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition );
  4036. }
  4037. ResultWas::OfType AssertionResult::getResultType() const {
  4038. return m_resultData.resultType;
  4039. }
  4040. bool AssertionResult::hasExpression() const {
  4041. return m_info.capturedExpression[0] != 0;
  4042. }
  4043. bool AssertionResult::hasMessage() const {
  4044. return !m_resultData.message.empty();
  4045. }
  4046. std::string AssertionResult::getExpression() const {
  4047. if( isFalseTest( m_info.resultDisposition ) )
  4048. return "!(" + m_info.capturedExpression + ")";
  4049. else
  4050. return m_info.capturedExpression;
  4051. }
  4052. std::string AssertionResult::getExpressionInMacro() const {
  4053. std::string expr;
  4054. if( m_info.macroName[0] == 0 )
  4055. expr = m_info.capturedExpression;
  4056. else {
  4057. expr.reserve( m_info.macroName.size() + m_info.capturedExpression.size() + 4 );
  4058. expr += m_info.macroName;
  4059. expr += "( ";
  4060. expr += m_info.capturedExpression;
  4061. expr += " )";
  4062. }
  4063. return expr;
  4064. }
  4065. bool AssertionResult::hasExpandedExpression() const {
  4066. return hasExpression() && getExpandedExpression() != getExpression();
  4067. }
  4068. std::string AssertionResult::getExpandedExpression() const {
  4069. std::string expr = m_resultData.reconstructExpression();
  4070. return expr.empty()
  4071. ? getExpression()
  4072. : expr;
  4073. }
  4074. std::string AssertionResult::getMessage() const {
  4075. return m_resultData.message;
  4076. }
  4077. SourceLineInfo AssertionResult::getSourceInfo() const {
  4078. return m_info.lineInfo;
  4079. }
  4080. StringRef AssertionResult::getTestMacroName() const {
  4081. return m_info.macroName;
  4082. }
  4083. } // end namespace Catch
  4084. // end catch_assertionresult.cpp
  4085. // start catch_benchmark.cpp
  4086. namespace Catch {
  4087. auto BenchmarkLooper::getResolution() -> uint64_t {
  4088. return getEstimatedClockResolution() * getCurrentContext().getConfig()->benchmarkResolutionMultiple();
  4089. }
  4090. void BenchmarkLooper::reportStart() {
  4091. getResultCapture().benchmarkStarting( { m_name } );
  4092. }
  4093. auto BenchmarkLooper::needsMoreIterations() -> bool {
  4094. auto elapsed = m_timer.getElapsedNanoseconds();
  4095. // Exponentially increasing iterations until we're confident in our timer resolution
  4096. if( elapsed < m_resolution ) {
  4097. m_iterationsToRun *= 10;
  4098. return true;
  4099. }
  4100. getResultCapture().benchmarkEnded( { { m_name }, m_count, elapsed } );
  4101. return false;
  4102. }
  4103. } // end namespace Catch
  4104. // end catch_benchmark.cpp
  4105. // start catch_capture_matchers.cpp
  4106. namespace Catch {
  4107. using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
  4108. // This is the general overload that takes a any string matcher
  4109. // There is another overload, in catch_assertionhandler.h/.cpp, that only takes a string and infers
  4110. // the Equals matcher (so the header does not mention matchers)
  4111. void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef matcherString ) {
  4112. std::string exceptionMessage = Catch::translateActiveException();
  4113. MatchExpr<std::string, StringMatcher const&> expr( exceptionMessage, matcher, matcherString );
  4114. handler.handleExpr( expr );
  4115. }
  4116. } // namespace Catch
  4117. // end catch_capture_matchers.cpp
  4118. // start catch_commandline.cpp
  4119. // start catch_commandline.h
  4120. // start catch_clara.h
  4121. // Use Catch's value for console width (store Clara's off to the side, if present)
  4122. #ifdef CLARA_CONFIG_CONSOLE_WIDTH
  4123. #define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  4124. #undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  4125. #endif
  4126. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH-1
  4127. #ifdef __clang__
  4128. #pragma clang diagnostic push
  4129. #pragma clang diagnostic ignored "-Wweak-vtables"
  4130. #pragma clang diagnostic ignored "-Wexit-time-destructors"
  4131. #pragma clang diagnostic ignored "-Wshadow"
  4132. #endif
  4133. // start clara.hpp
  4134. // Copyright 2017 Two Blue Cubes Ltd. All rights reserved.
  4135. //
  4136. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  4137. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  4138. //
  4139. // See https://github.com/philsquared/Clara for more details
  4140. // Clara v1.1.4
  4141. #ifndef CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  4142. #define CATCH_CLARA_CONFIG_CONSOLE_WIDTH 80
  4143. #endif
  4144. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  4145. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  4146. #endif
  4147. #ifndef CLARA_CONFIG_OPTIONAL_TYPE
  4148. #ifdef __has_include
  4149. #if __has_include(<optional>) && __cplusplus >= 201703L
  4150. #include <optional>
  4151. #define CLARA_CONFIG_OPTIONAL_TYPE std::optional
  4152. #endif
  4153. #endif
  4154. #endif
  4155. // ----------- #included from clara_textflow.hpp -----------
  4156. // TextFlowCpp
  4157. //
  4158. // A single-header library for wrapping and laying out basic text, by Phil Nash
  4159. //
  4160. // This work is licensed under the BSD 2-Clause license.
  4161. // See the accompanying LICENSE file, or the one at https://opensource.org/licenses/BSD-2-Clause
  4162. //
  4163. // This project is hosted at https://github.com/philsquared/textflowcpp
  4164. #include <cassert>
  4165. #include <ostream>
  4166. #include <sstream>
  4167. #include <vector>
  4168. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  4169. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80
  4170. #endif
  4171. namespace Catch { namespace clara { namespace TextFlow {
  4172. inline auto isWhitespace( char c ) -> bool {
  4173. static std::string chars = " \t\n\r";
  4174. return chars.find( c ) != std::string::npos;
  4175. }
  4176. inline auto isBreakableBefore( char c ) -> bool {
  4177. static std::string chars = "[({<|";
  4178. return chars.find( c ) != std::string::npos;
  4179. }
  4180. inline auto isBreakableAfter( char c ) -> bool {
  4181. static std::string chars = "])}>.,:;*+-=&/\\";
  4182. return chars.find( c ) != std::string::npos;
  4183. }
  4184. class Columns;
  4185. class Column {
  4186. std::vector<std::string> m_strings;
  4187. size_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH;
  4188. size_t m_indent = 0;
  4189. size_t m_initialIndent = std::string::npos;
  4190. public:
  4191. class iterator {
  4192. friend Column;
  4193. Column const& m_column;
  4194. size_t m_stringIndex = 0;
  4195. size_t m_pos = 0;
  4196. size_t m_len = 0;
  4197. size_t m_end = 0;
  4198. bool m_suffix = false;
  4199. iterator( Column const& column, size_t stringIndex )
  4200. : m_column( column ),
  4201. m_stringIndex( stringIndex )
  4202. {}
  4203. auto line() const -> std::string const& { return m_column.m_strings[m_stringIndex]; }
  4204. auto isBoundary( size_t at ) const -> bool {
  4205. assert( at > 0 );
  4206. assert( at <= line().size() );
  4207. return at == line().size() ||
  4208. ( isWhitespace( line()[at] ) && !isWhitespace( line()[at-1] ) ) ||
  4209. isBreakableBefore( line()[at] ) ||
  4210. isBreakableAfter( line()[at-1] );
  4211. }
  4212. void calcLength() {
  4213. assert( m_stringIndex < m_column.m_strings.size() );
  4214. m_suffix = false;
  4215. auto width = m_column.m_width-indent();
  4216. m_end = m_pos;
  4217. while( m_end < line().size() && line()[m_end] != '\n' )
  4218. ++m_end;
  4219. if( m_end < m_pos + width ) {
  4220. m_len = m_end - m_pos;
  4221. }
  4222. else {
  4223. size_t len = width;
  4224. while (len > 0 && !isBoundary(m_pos + len))
  4225. --len;
  4226. while (len > 0 && isWhitespace( line()[m_pos + len - 1] ))
  4227. --len;
  4228. if (len > 0) {
  4229. m_len = len;
  4230. } else {
  4231. m_suffix = true;
  4232. m_len = width - 1;
  4233. }
  4234. }
  4235. }
  4236. auto indent() const -> size_t {
  4237. auto initial = m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos;
  4238. return initial == std::string::npos ? m_column.m_indent : initial;
  4239. }
  4240. auto addIndentAndSuffix(std::string const &plain) const -> std::string {
  4241. return std::string( indent(), ' ' ) + (m_suffix ? plain + "-" : plain);
  4242. }
  4243. public:
  4244. explicit iterator( Column const& column ) : m_column( column ) {
  4245. assert( m_column.m_width > m_column.m_indent );
  4246. assert( m_column.m_initialIndent == std::string::npos || m_column.m_width > m_column.m_initialIndent );
  4247. calcLength();
  4248. if( m_len == 0 )
  4249. m_stringIndex++; // Empty string
  4250. }
  4251. auto operator *() const -> std::string {
  4252. assert( m_stringIndex < m_column.m_strings.size() );
  4253. assert( m_pos <= m_end );
  4254. if( m_pos + m_column.m_width < m_end )
  4255. return addIndentAndSuffix(line().substr(m_pos, m_len));
  4256. else
  4257. return addIndentAndSuffix(line().substr(m_pos, m_end - m_pos));
  4258. }
  4259. auto operator ++() -> iterator& {
  4260. m_pos += m_len;
  4261. if( m_pos < line().size() && line()[m_pos] == '\n' )
  4262. m_pos += 1;
  4263. else
  4264. while( m_pos < line().size() && isWhitespace( line()[m_pos] ) )
  4265. ++m_pos;
  4266. if( m_pos == line().size() ) {
  4267. m_pos = 0;
  4268. ++m_stringIndex;
  4269. }
  4270. if( m_stringIndex < m_column.m_strings.size() )
  4271. calcLength();
  4272. return *this;
  4273. }
  4274. auto operator ++(int) -> iterator {
  4275. iterator prev( *this );
  4276. operator++();
  4277. return prev;
  4278. }
  4279. auto operator ==( iterator const& other ) const -> bool {
  4280. return
  4281. m_pos == other.m_pos &&
  4282. m_stringIndex == other.m_stringIndex &&
  4283. &m_column == &other.m_column;
  4284. }
  4285. auto operator !=( iterator const& other ) const -> bool {
  4286. return !operator==( other );
  4287. }
  4288. };
  4289. using const_iterator = iterator;
  4290. explicit Column( std::string const& text ) { m_strings.push_back( text ); }
  4291. auto width( size_t newWidth ) -> Column& {
  4292. assert( newWidth > 0 );
  4293. m_width = newWidth;
  4294. return *this;
  4295. }
  4296. auto indent( size_t newIndent ) -> Column& {
  4297. m_indent = newIndent;
  4298. return *this;
  4299. }
  4300. auto initialIndent( size_t newIndent ) -> Column& {
  4301. m_initialIndent = newIndent;
  4302. return *this;
  4303. }
  4304. auto width() const -> size_t { return m_width; }
  4305. auto begin() const -> iterator { return iterator( *this ); }
  4306. auto end() const -> iterator { return { *this, m_strings.size() }; }
  4307. inline friend std::ostream& operator << ( std::ostream& os, Column const& col ) {
  4308. bool first = true;
  4309. for( auto line : col ) {
  4310. if( first )
  4311. first = false;
  4312. else
  4313. os << "\n";
  4314. os << line;
  4315. }
  4316. return os;
  4317. }
  4318. auto operator + ( Column const& other ) -> Columns;
  4319. auto toString() const -> std::string {
  4320. std::ostringstream oss;
  4321. oss << *this;
  4322. return oss.str();
  4323. }
  4324. };
  4325. class Spacer : public Column {
  4326. public:
  4327. explicit Spacer( size_t spaceWidth ) : Column( "" ) {
  4328. width( spaceWidth );
  4329. }
  4330. };
  4331. class Columns {
  4332. std::vector<Column> m_columns;
  4333. public:
  4334. class iterator {
  4335. friend Columns;
  4336. struct EndTag {};
  4337. std::vector<Column> const& m_columns;
  4338. std::vector<Column::iterator> m_iterators;
  4339. size_t m_activeIterators;
  4340. iterator( Columns const& columns, EndTag )
  4341. : m_columns( columns.m_columns ),
  4342. m_activeIterators( 0 )
  4343. {
  4344. m_iterators.reserve( m_columns.size() );
  4345. for( auto const& col : m_columns )
  4346. m_iterators.push_back( col.end() );
  4347. }
  4348. public:
  4349. explicit iterator( Columns const& columns )
  4350. : m_columns( columns.m_columns ),
  4351. m_activeIterators( m_columns.size() )
  4352. {
  4353. m_iterators.reserve( m_columns.size() );
  4354. for( auto const& col : m_columns )
  4355. m_iterators.push_back( col.begin() );
  4356. }
  4357. auto operator ==( iterator const& other ) const -> bool {
  4358. return m_iterators == other.m_iterators;
  4359. }
  4360. auto operator !=( iterator const& other ) const -> bool {
  4361. return m_iterators != other.m_iterators;
  4362. }
  4363. auto operator *() const -> std::string {
  4364. std::string row, padding;
  4365. for( size_t i = 0; i < m_columns.size(); ++i ) {
  4366. auto width = m_columns[i].width();
  4367. if( m_iterators[i] != m_columns[i].end() ) {
  4368. std::string col = *m_iterators[i];
  4369. row += padding + col;
  4370. if( col.size() < width )
  4371. padding = std::string( width - col.size(), ' ' );
  4372. else
  4373. padding = "";
  4374. }
  4375. else {
  4376. padding += std::string( width, ' ' );
  4377. }
  4378. }
  4379. return row;
  4380. }
  4381. auto operator ++() -> iterator& {
  4382. for( size_t i = 0; i < m_columns.size(); ++i ) {
  4383. if (m_iterators[i] != m_columns[i].end())
  4384. ++m_iterators[i];
  4385. }
  4386. return *this;
  4387. }
  4388. auto operator ++(int) -> iterator {
  4389. iterator prev( *this );
  4390. operator++();
  4391. return prev;
  4392. }
  4393. };
  4394. using const_iterator = iterator;
  4395. auto begin() const -> iterator { return iterator( *this ); }
  4396. auto end() const -> iterator { return { *this, iterator::EndTag() }; }
  4397. auto operator += ( Column const& col ) -> Columns& {
  4398. m_columns.push_back( col );
  4399. return *this;
  4400. }
  4401. auto operator + ( Column const& col ) -> Columns {
  4402. Columns combined = *this;
  4403. combined += col;
  4404. return combined;
  4405. }
  4406. inline friend std::ostream& operator << ( std::ostream& os, Columns const& cols ) {
  4407. bool first = true;
  4408. for( auto line : cols ) {
  4409. if( first )
  4410. first = false;
  4411. else
  4412. os << "\n";
  4413. os << line;
  4414. }
  4415. return os;
  4416. }
  4417. auto toString() const -> std::string {
  4418. std::ostringstream oss;
  4419. oss << *this;
  4420. return oss.str();
  4421. }
  4422. };
  4423. inline auto Column::operator + ( Column const& other ) -> Columns {
  4424. Columns cols;
  4425. cols += *this;
  4426. cols += other;
  4427. return cols;
  4428. }
  4429. }}} // namespace Catch::clara::TextFlow
  4430. // ----------- end of #include from clara_textflow.hpp -----------
  4431. // ........... back in clara.hpp
  4432. #include <memory>
  4433. #include <set>
  4434. #include <algorithm>
  4435. #if !defined(CATCH_PLATFORM_WINDOWS) && ( defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) )
  4436. #define CATCH_PLATFORM_WINDOWS
  4437. #endif
  4438. namespace Catch { namespace clara {
  4439. namespace detail {
  4440. // Traits for extracting arg and return type of lambdas (for single argument lambdas)
  4441. template<typename L>
  4442. struct UnaryLambdaTraits : UnaryLambdaTraits<decltype( &L::operator() )> {};
  4443. template<typename ClassT, typename ReturnT, typename... Args>
  4444. struct UnaryLambdaTraits<ReturnT( ClassT::* )( Args... ) const> {
  4445. static const bool isValid = false;
  4446. };
  4447. template<typename ClassT, typename ReturnT, typename ArgT>
  4448. struct UnaryLambdaTraits<ReturnT( ClassT::* )( ArgT ) const> {
  4449. static const bool isValid = true;
  4450. using ArgType = typename std::remove_const<typename std::remove_reference<ArgT>::type>::type;
  4451. using ReturnType = ReturnT;
  4452. };
  4453. class TokenStream;
  4454. // Transport for raw args (copied from main args, or supplied via init list for testing)
  4455. class Args {
  4456. friend TokenStream;
  4457. std::string m_exeName;
  4458. std::vector<std::string> m_args;
  4459. public:
  4460. Args( int argc, char const* const* argv )
  4461. : m_exeName(argv[0]),
  4462. m_args(argv + 1, argv + argc) {}
  4463. Args( std::initializer_list<std::string> args )
  4464. : m_exeName( *args.begin() ),
  4465. m_args( args.begin()+1, args.end() )
  4466. {}
  4467. auto exeName() const -> std::string {
  4468. return m_exeName;
  4469. }
  4470. };
  4471. // Wraps a token coming from a token stream. These may not directly correspond to strings as a single string
  4472. // may encode an option + its argument if the : or = form is used
  4473. enum class TokenType {
  4474. Option, Argument
  4475. };
  4476. struct Token {
  4477. TokenType type;
  4478. std::string token;
  4479. };
  4480. inline auto isOptPrefix( char c ) -> bool {
  4481. return c == '-'
  4482. #ifdef CATCH_PLATFORM_WINDOWS
  4483. || c == '/'
  4484. #endif
  4485. ;
  4486. }
  4487. // Abstracts iterators into args as a stream of tokens, with option arguments uniformly handled
  4488. class TokenStream {
  4489. using Iterator = std::vector<std::string>::const_iterator;
  4490. Iterator it;
  4491. Iterator itEnd;
  4492. std::vector<Token> m_tokenBuffer;
  4493. void loadBuffer() {
  4494. m_tokenBuffer.resize( 0 );
  4495. // Skip any empty strings
  4496. while( it != itEnd && it->empty() )
  4497. ++it;
  4498. if( it != itEnd ) {
  4499. auto const &next = *it;
  4500. if( isOptPrefix( next[0] ) ) {
  4501. auto delimiterPos = next.find_first_of( " :=" );
  4502. if( delimiterPos != std::string::npos ) {
  4503. m_tokenBuffer.push_back( { TokenType::Option, next.substr( 0, delimiterPos ) } );
  4504. m_tokenBuffer.push_back( { TokenType::Argument, next.substr( delimiterPos + 1 ) } );
  4505. } else {
  4506. if( next[1] != '-' && next.size() > 2 ) {
  4507. std::string opt = "- ";
  4508. for( size_t i = 1; i < next.size(); ++i ) {
  4509. opt[1] = next[i];
  4510. m_tokenBuffer.push_back( { TokenType::Option, opt } );
  4511. }
  4512. } else {
  4513. m_tokenBuffer.push_back( { TokenType::Option, next } );
  4514. }
  4515. }
  4516. } else {
  4517. m_tokenBuffer.push_back( { TokenType::Argument, next } );
  4518. }
  4519. }
  4520. }
  4521. public:
  4522. explicit TokenStream( Args const &args ) : TokenStream( args.m_args.begin(), args.m_args.end() ) {}
  4523. TokenStream( Iterator it, Iterator itEnd ) : it( it ), itEnd( itEnd ) {
  4524. loadBuffer();
  4525. }
  4526. explicit operator bool() const {
  4527. return !m_tokenBuffer.empty() || it != itEnd;
  4528. }
  4529. auto count() const -> size_t { return m_tokenBuffer.size() + (itEnd - it); }
  4530. auto operator*() const -> Token {
  4531. assert( !m_tokenBuffer.empty() );
  4532. return m_tokenBuffer.front();
  4533. }
  4534. auto operator->() const -> Token const * {
  4535. assert( !m_tokenBuffer.empty() );
  4536. return &m_tokenBuffer.front();
  4537. }
  4538. auto operator++() -> TokenStream & {
  4539. if( m_tokenBuffer.size() >= 2 ) {
  4540. m_tokenBuffer.erase( m_tokenBuffer.begin() );
  4541. } else {
  4542. if( it != itEnd )
  4543. ++it;
  4544. loadBuffer();
  4545. }
  4546. return *this;
  4547. }
  4548. };
  4549. class ResultBase {
  4550. public:
  4551. enum Type {
  4552. Ok, LogicError, RuntimeError
  4553. };
  4554. protected:
  4555. ResultBase( Type type ) : m_type( type ) {}
  4556. virtual ~ResultBase() = default;
  4557. virtual void enforceOk() const = 0;
  4558. Type m_type;
  4559. };
  4560. template<typename T>
  4561. class ResultValueBase : public ResultBase {
  4562. public:
  4563. auto value() const -> T const & {
  4564. enforceOk();
  4565. return m_value;
  4566. }
  4567. protected:
  4568. ResultValueBase( Type type ) : ResultBase( type ) {}
  4569. ResultValueBase( ResultValueBase const &other ) : ResultBase( other ) {
  4570. if( m_type == ResultBase::Ok )
  4571. new( &m_value ) T( other.m_value );
  4572. }
  4573. ResultValueBase( Type, T const &value ) : ResultBase( Ok ) {
  4574. new( &m_value ) T( value );
  4575. }
  4576. auto operator=( ResultValueBase const &other ) -> ResultValueBase & {
  4577. if( m_type == ResultBase::Ok )
  4578. m_value.~T();
  4579. ResultBase::operator=(other);
  4580. if( m_type == ResultBase::Ok )
  4581. new( &m_value ) T( other.m_value );
  4582. return *this;
  4583. }
  4584. ~ResultValueBase() override {
  4585. if( m_type == Ok )
  4586. m_value.~T();
  4587. }
  4588. union {
  4589. T m_value;
  4590. };
  4591. };
  4592. template<>
  4593. class ResultValueBase<void> : public ResultBase {
  4594. protected:
  4595. using ResultBase::ResultBase;
  4596. };
  4597. template<typename T = void>
  4598. class BasicResult : public ResultValueBase<T> {
  4599. public:
  4600. template<typename U>
  4601. explicit BasicResult( BasicResult<U> const &other )
  4602. : ResultValueBase<T>( other.type() ),
  4603. m_errorMessage( other.errorMessage() )
  4604. {
  4605. assert( type() != ResultBase::Ok );
  4606. }
  4607. template<typename U>
  4608. static auto ok( U const &value ) -> BasicResult { return { ResultBase::Ok, value }; }
  4609. static auto ok() -> BasicResult { return { ResultBase::Ok }; }
  4610. static auto logicError( std::string const &message ) -> BasicResult { return { ResultBase::LogicError, message }; }
  4611. static auto runtimeError( std::string const &message ) -> BasicResult { return { ResultBase::RuntimeError, message }; }
  4612. explicit operator bool() const { return m_type == ResultBase::Ok; }
  4613. auto type() const -> ResultBase::Type { return m_type; }
  4614. auto errorMessage() const -> std::string { return m_errorMessage; }
  4615. protected:
  4616. void enforceOk() const override {
  4617. // Errors shouldn't reach this point, but if they do
  4618. // the actual error message will be in m_errorMessage
  4619. assert( m_type != ResultBase::LogicError );
  4620. assert( m_type != ResultBase::RuntimeError );
  4621. if( m_type != ResultBase::Ok )
  4622. std::abort();
  4623. }
  4624. std::string m_errorMessage; // Only populated if resultType is an error
  4625. BasicResult( ResultBase::Type type, std::string const &message )
  4626. : ResultValueBase<T>(type),
  4627. m_errorMessage(message)
  4628. {
  4629. assert( m_type != ResultBase::Ok );
  4630. }
  4631. using ResultValueBase<T>::ResultValueBase;
  4632. using ResultBase::m_type;
  4633. };
  4634. enum class ParseResultType {
  4635. Matched, NoMatch, ShortCircuitAll, ShortCircuitSame
  4636. };
  4637. class ParseState {
  4638. public:
  4639. ParseState( ParseResultType type, TokenStream const &remainingTokens )
  4640. : m_type(type),
  4641. m_remainingTokens( remainingTokens )
  4642. {}
  4643. auto type() const -> ParseResultType { return m_type; }
  4644. auto remainingTokens() const -> TokenStream { return m_remainingTokens; }
  4645. private:
  4646. ParseResultType m_type;
  4647. TokenStream m_remainingTokens;
  4648. };
  4649. using Result = BasicResult<void>;
  4650. using ParserResult = BasicResult<ParseResultType>;
  4651. using InternalParseResult = BasicResult<ParseState>;
  4652. struct HelpColumns {
  4653. std::string left;
  4654. std::string right;
  4655. };
  4656. template<typename T>
  4657. inline auto convertInto( std::string const &source, T& target ) -> ParserResult {
  4658. std::stringstream ss;
  4659. ss << source;
  4660. ss >> target;
  4661. if( ss.fail() )
  4662. return ParserResult::runtimeError( "Unable to convert '" + source + "' to destination type" );
  4663. else
  4664. return ParserResult::ok( ParseResultType::Matched );
  4665. }
  4666. inline auto convertInto( std::string const &source, std::string& target ) -> ParserResult {
  4667. target = source;
  4668. return ParserResult::ok( ParseResultType::Matched );
  4669. }
  4670. inline auto convertInto( std::string const &source, bool &target ) -> ParserResult {
  4671. std::string srcLC = source;
  4672. std::transform( srcLC.begin(), srcLC.end(), srcLC.begin(), []( char c ) { return static_cast<char>( ::tolower(c) ); } );
  4673. if (srcLC == "y" || srcLC == "1" || srcLC == "true" || srcLC == "yes" || srcLC == "on")
  4674. target = true;
  4675. else if (srcLC == "n" || srcLC == "0" || srcLC == "false" || srcLC == "no" || srcLC == "off")
  4676. target = false;
  4677. else
  4678. return ParserResult::runtimeError( "Expected a boolean value but did not recognise: '" + source + "'" );
  4679. return ParserResult::ok( ParseResultType::Matched );
  4680. }
  4681. #ifdef CLARA_CONFIG_OPTIONAL_TYPE
  4682. template<typename T>
  4683. inline auto convertInto( std::string const &source, CLARA_CONFIG_OPTIONAL_TYPE<T>& target ) -> ParserResult {
  4684. T temp;
  4685. auto result = convertInto( source, temp );
  4686. if( result )
  4687. target = std::move(temp);
  4688. return result;
  4689. }
  4690. #endif // CLARA_CONFIG_OPTIONAL_TYPE
  4691. struct NonCopyable {
  4692. NonCopyable() = default;
  4693. NonCopyable( NonCopyable const & ) = delete;
  4694. NonCopyable( NonCopyable && ) = delete;
  4695. NonCopyable &operator=( NonCopyable const & ) = delete;
  4696. NonCopyable &operator=( NonCopyable && ) = delete;
  4697. };
  4698. struct BoundRef : NonCopyable {
  4699. virtual ~BoundRef() = default;
  4700. virtual auto isContainer() const -> bool { return false; }
  4701. virtual auto isFlag() const -> bool { return false; }
  4702. };
  4703. struct BoundValueRefBase : BoundRef {
  4704. virtual auto setValue( std::string const &arg ) -> ParserResult = 0;
  4705. };
  4706. struct BoundFlagRefBase : BoundRef {
  4707. virtual auto setFlag( bool flag ) -> ParserResult = 0;
  4708. virtual auto isFlag() const -> bool { return true; }
  4709. };
  4710. template<typename T>
  4711. struct BoundValueRef : BoundValueRefBase {
  4712. T &m_ref;
  4713. explicit BoundValueRef( T &ref ) : m_ref( ref ) {}
  4714. auto setValue( std::string const &arg ) -> ParserResult override {
  4715. return convertInto( arg, m_ref );
  4716. }
  4717. };
  4718. template<typename T>
  4719. struct BoundValueRef<std::vector<T>> : BoundValueRefBase {
  4720. std::vector<T> &m_ref;
  4721. explicit BoundValueRef( std::vector<T> &ref ) : m_ref( ref ) {}
  4722. auto isContainer() const -> bool override { return true; }
  4723. auto setValue( std::string const &arg ) -> ParserResult override {
  4724. T temp;
  4725. auto result = convertInto( arg, temp );
  4726. if( result )
  4727. m_ref.push_back( temp );
  4728. return result;
  4729. }
  4730. };
  4731. struct BoundFlagRef : BoundFlagRefBase {
  4732. bool &m_ref;
  4733. explicit BoundFlagRef( bool &ref ) : m_ref( ref ) {}
  4734. auto setFlag( bool flag ) -> ParserResult override {
  4735. m_ref = flag;
  4736. return ParserResult::ok( ParseResultType::Matched );
  4737. }
  4738. };
  4739. template<typename ReturnType>
  4740. struct LambdaInvoker {
  4741. static_assert( std::is_same<ReturnType, ParserResult>::value, "Lambda must return void or clara::ParserResult" );
  4742. template<typename L, typename ArgType>
  4743. static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
  4744. return lambda( arg );
  4745. }
  4746. };
  4747. template<>
  4748. struct LambdaInvoker<void> {
  4749. template<typename L, typename ArgType>
  4750. static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
  4751. lambda( arg );
  4752. return ParserResult::ok( ParseResultType::Matched );
  4753. }
  4754. };
  4755. template<typename ArgType, typename L>
  4756. inline auto invokeLambda( L const &lambda, std::string const &arg ) -> ParserResult {
  4757. ArgType temp{};
  4758. auto result = convertInto( arg, temp );
  4759. return !result
  4760. ? result
  4761. : LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( lambda, temp );
  4762. }
  4763. template<typename L>
  4764. struct BoundLambda : BoundValueRefBase {
  4765. L m_lambda;
  4766. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  4767. explicit BoundLambda( L const &lambda ) : m_lambda( lambda ) {}
  4768. auto setValue( std::string const &arg ) -> ParserResult override {
  4769. return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>( m_lambda, arg );
  4770. }
  4771. };
  4772. template<typename L>
  4773. struct BoundFlagLambda : BoundFlagRefBase {
  4774. L m_lambda;
  4775. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  4776. static_assert( std::is_same<typename UnaryLambdaTraits<L>::ArgType, bool>::value, "flags must be boolean" );
  4777. explicit BoundFlagLambda( L const &lambda ) : m_lambda( lambda ) {}
  4778. auto setFlag( bool flag ) -> ParserResult override {
  4779. return LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( m_lambda, flag );
  4780. }
  4781. };
  4782. enum class Optionality { Optional, Required };
  4783. struct Parser;
  4784. class ParserBase {
  4785. public:
  4786. virtual ~ParserBase() = default;
  4787. virtual auto validate() const -> Result { return Result::ok(); }
  4788. virtual auto parse( std::string const& exeName, TokenStream const &tokens) const -> InternalParseResult = 0;
  4789. virtual auto cardinality() const -> size_t { return 1; }
  4790. auto parse( Args const &args ) const -> InternalParseResult {
  4791. return parse( args.exeName(), TokenStream( args ) );
  4792. }
  4793. };
  4794. template<typename DerivedT>
  4795. class ComposableParserImpl : public ParserBase {
  4796. public:
  4797. template<typename T>
  4798. auto operator|( T const &other ) const -> Parser;
  4799. template<typename T>
  4800. auto operator+( T const &other ) const -> Parser;
  4801. };
  4802. // Common code and state for Args and Opts
  4803. template<typename DerivedT>
  4804. class ParserRefImpl : public ComposableParserImpl<DerivedT> {
  4805. protected:
  4806. Optionality m_optionality = Optionality::Optional;
  4807. std::shared_ptr<BoundRef> m_ref;
  4808. std::string m_hint;
  4809. std::string m_description;
  4810. explicit ParserRefImpl( std::shared_ptr<BoundRef> const &ref ) : m_ref( ref ) {}
  4811. public:
  4812. template<typename T>
  4813. ParserRefImpl( T &ref, std::string const &hint )
  4814. : m_ref( std::make_shared<BoundValueRef<T>>( ref ) ),
  4815. m_hint( hint )
  4816. {}
  4817. template<typename LambdaT>
  4818. ParserRefImpl( LambdaT const &ref, std::string const &hint )
  4819. : m_ref( std::make_shared<BoundLambda<LambdaT>>( ref ) ),
  4820. m_hint(hint)
  4821. {}
  4822. auto operator()( std::string const &description ) -> DerivedT & {
  4823. m_description = description;
  4824. return static_cast<DerivedT &>( *this );
  4825. }
  4826. auto optional() -> DerivedT & {
  4827. m_optionality = Optionality::Optional;
  4828. return static_cast<DerivedT &>( *this );
  4829. };
  4830. auto required() -> DerivedT & {
  4831. m_optionality = Optionality::Required;
  4832. return static_cast<DerivedT &>( *this );
  4833. };
  4834. auto isOptional() const -> bool {
  4835. return m_optionality == Optionality::Optional;
  4836. }
  4837. auto cardinality() const -> size_t override {
  4838. if( m_ref->isContainer() )
  4839. return 0;
  4840. else
  4841. return 1;
  4842. }
  4843. auto hint() const -> std::string { return m_hint; }
  4844. };
  4845. class ExeName : public ComposableParserImpl<ExeName> {
  4846. std::shared_ptr<std::string> m_name;
  4847. std::shared_ptr<BoundValueRefBase> m_ref;
  4848. template<typename LambdaT>
  4849. static auto makeRef(LambdaT const &lambda) -> std::shared_ptr<BoundValueRefBase> {
  4850. return std::make_shared<BoundLambda<LambdaT>>( lambda) ;
  4851. }
  4852. public:
  4853. ExeName() : m_name( std::make_shared<std::string>( "<executable>" ) ) {}
  4854. explicit ExeName( std::string &ref ) : ExeName() {
  4855. m_ref = std::make_shared<BoundValueRef<std::string>>( ref );
  4856. }
  4857. template<typename LambdaT>
  4858. explicit ExeName( LambdaT const& lambda ) : ExeName() {
  4859. m_ref = std::make_shared<BoundLambda<LambdaT>>( lambda );
  4860. }
  4861. // The exe name is not parsed out of the normal tokens, but is handled specially
  4862. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  4863. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
  4864. }
  4865. auto name() const -> std::string { return *m_name; }
  4866. auto set( std::string const& newName ) -> ParserResult {
  4867. auto lastSlash = newName.find_last_of( "\\/" );
  4868. auto filename = ( lastSlash == std::string::npos )
  4869. ? newName
  4870. : newName.substr( lastSlash+1 );
  4871. *m_name = filename;
  4872. if( m_ref )
  4873. return m_ref->setValue( filename );
  4874. else
  4875. return ParserResult::ok( ParseResultType::Matched );
  4876. }
  4877. };
  4878. class Arg : public ParserRefImpl<Arg> {
  4879. public:
  4880. using ParserRefImpl::ParserRefImpl;
  4881. auto parse( std::string const &, TokenStream const &tokens ) const -> InternalParseResult override {
  4882. auto validationResult = validate();
  4883. if( !validationResult )
  4884. return InternalParseResult( validationResult );
  4885. auto remainingTokens = tokens;
  4886. auto const &token = *remainingTokens;
  4887. if( token.type != TokenType::Argument )
  4888. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
  4889. assert( !m_ref->isFlag() );
  4890. auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
  4891. auto result = valueRef->setValue( remainingTokens->token );
  4892. if( !result )
  4893. return InternalParseResult( result );
  4894. else
  4895. return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
  4896. }
  4897. };
  4898. inline auto normaliseOpt( std::string const &optName ) -> std::string {
  4899. #ifdef CATCH_PLATFORM_WINDOWS
  4900. if( optName[0] == '/' )
  4901. return "-" + optName.substr( 1 );
  4902. else
  4903. #endif
  4904. return optName;
  4905. }
  4906. class Opt : public ParserRefImpl<Opt> {
  4907. protected:
  4908. std::vector<std::string> m_optNames;
  4909. public:
  4910. template<typename LambdaT>
  4911. explicit Opt( LambdaT const &ref ) : ParserRefImpl( std::make_shared<BoundFlagLambda<LambdaT>>( ref ) ) {}
  4912. explicit Opt( bool &ref ) : ParserRefImpl( std::make_shared<BoundFlagRef>( ref ) ) {}
  4913. template<typename LambdaT>
  4914. Opt( LambdaT const &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  4915. template<typename T>
  4916. Opt( T &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  4917. auto operator[]( std::string const &optName ) -> Opt & {
  4918. m_optNames.push_back( optName );
  4919. return *this;
  4920. }
  4921. auto getHelpColumns() const -> std::vector<HelpColumns> {
  4922. std::ostringstream oss;
  4923. bool first = true;
  4924. for( auto const &opt : m_optNames ) {
  4925. if (first)
  4926. first = false;
  4927. else
  4928. oss << ", ";
  4929. oss << opt;
  4930. }
  4931. if( !m_hint.empty() )
  4932. oss << " <" << m_hint << ">";
  4933. return { { oss.str(), m_description } };
  4934. }
  4935. auto isMatch( std::string const &optToken ) const -> bool {
  4936. auto normalisedToken = normaliseOpt( optToken );
  4937. for( auto const &name : m_optNames ) {
  4938. if( normaliseOpt( name ) == normalisedToken )
  4939. return true;
  4940. }
  4941. return false;
  4942. }
  4943. using ParserBase::parse;
  4944. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  4945. auto validationResult = validate();
  4946. if( !validationResult )
  4947. return InternalParseResult( validationResult );
  4948. auto remainingTokens = tokens;
  4949. if( remainingTokens && remainingTokens->type == TokenType::Option ) {
  4950. auto const &token = *remainingTokens;
  4951. if( isMatch(token.token ) ) {
  4952. if( m_ref->isFlag() ) {
  4953. auto flagRef = static_cast<detail::BoundFlagRefBase*>( m_ref.get() );
  4954. auto result = flagRef->setFlag( true );
  4955. if( !result )
  4956. return InternalParseResult( result );
  4957. if( result.value() == ParseResultType::ShortCircuitAll )
  4958. return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
  4959. } else {
  4960. auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
  4961. ++remainingTokens;
  4962. if( !remainingTokens )
  4963. return InternalParseResult::runtimeError( "Expected argument following " + token.token );
  4964. auto const &argToken = *remainingTokens;
  4965. if( argToken.type != TokenType::Argument )
  4966. return InternalParseResult::runtimeError( "Expected argument following " + token.token );
  4967. auto result = valueRef->setValue( argToken.token );
  4968. if( !result )
  4969. return InternalParseResult( result );
  4970. if( result.value() == ParseResultType::ShortCircuitAll )
  4971. return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
  4972. }
  4973. return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
  4974. }
  4975. }
  4976. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
  4977. }
  4978. auto validate() const -> Result override {
  4979. if( m_optNames.empty() )
  4980. return Result::logicError( "No options supplied to Opt" );
  4981. for( auto const &name : m_optNames ) {
  4982. if( name.empty() )
  4983. return Result::logicError( "Option name cannot be empty" );
  4984. #ifdef CATCH_PLATFORM_WINDOWS
  4985. if( name[0] != '-' && name[0] != '/' )
  4986. return Result::logicError( "Option name must begin with '-' or '/'" );
  4987. #else
  4988. if( name[0] != '-' )
  4989. return Result::logicError( "Option name must begin with '-'" );
  4990. #endif
  4991. }
  4992. return ParserRefImpl::validate();
  4993. }
  4994. };
  4995. struct Help : Opt {
  4996. Help( bool &showHelpFlag )
  4997. : Opt([&]( bool flag ) {
  4998. showHelpFlag = flag;
  4999. return ParserResult::ok( ParseResultType::ShortCircuitAll );
  5000. })
  5001. {
  5002. static_cast<Opt &>( *this )
  5003. ("display usage information")
  5004. ["-?"]["-h"]["--help"]
  5005. .optional();
  5006. }
  5007. };
  5008. struct Parser : ParserBase {
  5009. mutable ExeName m_exeName;
  5010. std::vector<Opt> m_options;
  5011. std::vector<Arg> m_args;
  5012. auto operator|=( ExeName const &exeName ) -> Parser & {
  5013. m_exeName = exeName;
  5014. return *this;
  5015. }
  5016. auto operator|=( Arg const &arg ) -> Parser & {
  5017. m_args.push_back(arg);
  5018. return *this;
  5019. }
  5020. auto operator|=( Opt const &opt ) -> Parser & {
  5021. m_options.push_back(opt);
  5022. return *this;
  5023. }
  5024. auto operator|=( Parser const &other ) -> Parser & {
  5025. m_options.insert(m_options.end(), other.m_options.begin(), other.m_options.end());
  5026. m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end());
  5027. return *this;
  5028. }
  5029. template<typename T>
  5030. auto operator|( T const &other ) const -> Parser {
  5031. return Parser( *this ) |= other;
  5032. }
  5033. // Forward deprecated interface with '+' instead of '|'
  5034. template<typename T>
  5035. auto operator+=( T const &other ) -> Parser & { return operator|=( other ); }
  5036. template<typename T>
  5037. auto operator+( T const &other ) const -> Parser { return operator|( other ); }
  5038. auto getHelpColumns() const -> std::vector<HelpColumns> {
  5039. std::vector<HelpColumns> cols;
  5040. for (auto const &o : m_options) {
  5041. auto childCols = o.getHelpColumns();
  5042. cols.insert( cols.end(), childCols.begin(), childCols.end() );
  5043. }
  5044. return cols;
  5045. }
  5046. void writeToStream( std::ostream &os ) const {
  5047. if (!m_exeName.name().empty()) {
  5048. os << "usage:\n" << " " << m_exeName.name() << " ";
  5049. bool required = true, first = true;
  5050. for( auto const &arg : m_args ) {
  5051. if (first)
  5052. first = false;
  5053. else
  5054. os << " ";
  5055. if( arg.isOptional() && required ) {
  5056. os << "[";
  5057. required = false;
  5058. }
  5059. os << "<" << arg.hint() << ">";
  5060. if( arg.cardinality() == 0 )
  5061. os << " ... ";
  5062. }
  5063. if( !required )
  5064. os << "]";
  5065. if( !m_options.empty() )
  5066. os << " options";
  5067. os << "\n\nwhere options are:" << std::endl;
  5068. }
  5069. auto rows = getHelpColumns();
  5070. size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH;
  5071. size_t optWidth = 0;
  5072. for( auto const &cols : rows )
  5073. optWidth = (std::max)(optWidth, cols.left.size() + 2);
  5074. optWidth = (std::min)(optWidth, consoleWidth/2);
  5075. for( auto const &cols : rows ) {
  5076. auto row =
  5077. TextFlow::Column( cols.left ).width( optWidth ).indent( 2 ) +
  5078. TextFlow::Spacer(4) +
  5079. TextFlow::Column( cols.right ).width( consoleWidth - 7 - optWidth );
  5080. os << row << std::endl;
  5081. }
  5082. }
  5083. friend auto operator<<( std::ostream &os, Parser const &parser ) -> std::ostream& {
  5084. parser.writeToStream( os );
  5085. return os;
  5086. }
  5087. auto validate() const -> Result override {
  5088. for( auto const &opt : m_options ) {
  5089. auto result = opt.validate();
  5090. if( !result )
  5091. return result;
  5092. }
  5093. for( auto const &arg : m_args ) {
  5094. auto result = arg.validate();
  5095. if( !result )
  5096. return result;
  5097. }
  5098. return Result::ok();
  5099. }
  5100. using ParserBase::parse;
  5101. auto parse( std::string const& exeName, TokenStream const &tokens ) const -> InternalParseResult override {
  5102. struct ParserInfo {
  5103. ParserBase const* parser = nullptr;
  5104. size_t count = 0;
  5105. };
  5106. const size_t totalParsers = m_options.size() + m_args.size();
  5107. assert( totalParsers < 512 );
  5108. // ParserInfo parseInfos[totalParsers]; // <-- this is what we really want to do
  5109. ParserInfo parseInfos[512];
  5110. {
  5111. size_t i = 0;
  5112. for (auto const &opt : m_options) parseInfos[i++].parser = &opt;
  5113. for (auto const &arg : m_args) parseInfos[i++].parser = &arg;
  5114. }
  5115. m_exeName.set( exeName );
  5116. auto result = InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
  5117. while( result.value().remainingTokens() ) {
  5118. bool tokenParsed = false;
  5119. for( size_t i = 0; i < totalParsers; ++i ) {
  5120. auto& parseInfo = parseInfos[i];
  5121. if( parseInfo.parser->cardinality() == 0 || parseInfo.count < parseInfo.parser->cardinality() ) {
  5122. result = parseInfo.parser->parse(exeName, result.value().remainingTokens());
  5123. if (!result)
  5124. return result;
  5125. if (result.value().type() != ParseResultType::NoMatch) {
  5126. tokenParsed = true;
  5127. ++parseInfo.count;
  5128. break;
  5129. }
  5130. }
  5131. }
  5132. if( result.value().type() == ParseResultType::ShortCircuitAll )
  5133. return result;
  5134. if( !tokenParsed )
  5135. return InternalParseResult::runtimeError( "Unrecognised token: " + result.value().remainingTokens()->token );
  5136. }
  5137. // !TBD Check missing required options
  5138. return result;
  5139. }
  5140. };
  5141. template<typename DerivedT>
  5142. template<typename T>
  5143. auto ComposableParserImpl<DerivedT>::operator|( T const &other ) const -> Parser {
  5144. return Parser() | static_cast<DerivedT const &>( *this ) | other;
  5145. }
  5146. } // namespace detail
  5147. // A Combined parser
  5148. using detail::Parser;
  5149. // A parser for options
  5150. using detail::Opt;
  5151. // A parser for arguments
  5152. using detail::Arg;
  5153. // Wrapper for argc, argv from main()
  5154. using detail::Args;
  5155. // Specifies the name of the executable
  5156. using detail::ExeName;
  5157. // Convenience wrapper for option parser that specifies the help option
  5158. using detail::Help;
  5159. // enum of result types from a parse
  5160. using detail::ParseResultType;
  5161. // Result type for parser operation
  5162. using detail::ParserResult;
  5163. }} // namespace Catch::clara
  5164. // end clara.hpp
  5165. #ifdef __clang__
  5166. #pragma clang diagnostic pop
  5167. #endif
  5168. // Restore Clara's value for console width, if present
  5169. #ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  5170. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  5171. #undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  5172. #endif
  5173. // end catch_clara.h
  5174. namespace Catch {
  5175. clara::Parser makeCommandLineParser( ConfigData& config );
  5176. } // end namespace Catch
  5177. // end catch_commandline.h
  5178. #include <fstream>
  5179. #include <ctime>
  5180. namespace Catch {
  5181. clara::Parser makeCommandLineParser( ConfigData& config ) {
  5182. using namespace clara;
  5183. auto const setWarning = [&]( std::string const& warning ) {
  5184. auto warningSet = [&]() {
  5185. if( warning == "NoAssertions" )
  5186. return WarnAbout::NoAssertions;
  5187. if ( warning == "NoTests" )
  5188. return WarnAbout::NoTests;
  5189. return WarnAbout::Nothing;
  5190. }();
  5191. if (warningSet == WarnAbout::Nothing)
  5192. return ParserResult::runtimeError( "Unrecognised warning: '" + warning + "'" );
  5193. config.warnings = static_cast<WarnAbout::What>( config.warnings | warningSet );
  5194. return ParserResult::ok( ParseResultType::Matched );
  5195. };
  5196. auto const loadTestNamesFromFile = [&]( std::string const& filename ) {
  5197. std::ifstream f( filename.c_str() );
  5198. if( !f.is_open() )
  5199. return ParserResult::runtimeError( "Unable to load input file: '" + filename + "'" );
  5200. std::string line;
  5201. while( std::getline( f, line ) ) {
  5202. line = trim(line);
  5203. if( !line.empty() && !startsWith( line, '#' ) ) {
  5204. if( !startsWith( line, '"' ) )
  5205. line = '"' + line + '"';
  5206. config.testsOrTags.push_back( line + ',' );
  5207. }
  5208. }
  5209. return ParserResult::ok( ParseResultType::Matched );
  5210. };
  5211. auto const setTestOrder = [&]( std::string const& order ) {
  5212. if( startsWith( "declared", order ) )
  5213. config.runOrder = RunTests::InDeclarationOrder;
  5214. else if( startsWith( "lexical", order ) )
  5215. config.runOrder = RunTests::InLexicographicalOrder;
  5216. else if( startsWith( "random", order ) )
  5217. config.runOrder = RunTests::InRandomOrder;
  5218. else
  5219. return clara::ParserResult::runtimeError( "Unrecognised ordering: '" + order + "'" );
  5220. return ParserResult::ok( ParseResultType::Matched );
  5221. };
  5222. auto const setRngSeed = [&]( std::string const& seed ) {
  5223. if( seed != "time" )
  5224. return clara::detail::convertInto( seed, config.rngSeed );
  5225. config.rngSeed = static_cast<unsigned int>( std::time(nullptr) );
  5226. return ParserResult::ok( ParseResultType::Matched );
  5227. };
  5228. auto const setColourUsage = [&]( std::string const& useColour ) {
  5229. auto mode = toLower( useColour );
  5230. if( mode == "yes" )
  5231. config.useColour = UseColour::Yes;
  5232. else if( mode == "no" )
  5233. config.useColour = UseColour::No;
  5234. else if( mode == "auto" )
  5235. config.useColour = UseColour::Auto;
  5236. else
  5237. return ParserResult::runtimeError( "colour mode must be one of: auto, yes or no. '" + useColour + "' not recognised" );
  5238. return ParserResult::ok( ParseResultType::Matched );
  5239. };
  5240. auto const setWaitForKeypress = [&]( std::string const& keypress ) {
  5241. auto keypressLc = toLower( keypress );
  5242. if( keypressLc == "start" )
  5243. config.waitForKeypress = WaitForKeypress::BeforeStart;
  5244. else if( keypressLc == "exit" )
  5245. config.waitForKeypress = WaitForKeypress::BeforeExit;
  5246. else if( keypressLc == "both" )
  5247. config.waitForKeypress = WaitForKeypress::BeforeStartAndExit;
  5248. else
  5249. return ParserResult::runtimeError( "keypress argument must be one of: start, exit or both. '" + keypress + "' not recognised" );
  5250. return ParserResult::ok( ParseResultType::Matched );
  5251. };
  5252. auto const setVerbosity = [&]( std::string const& verbosity ) {
  5253. auto lcVerbosity = toLower( verbosity );
  5254. if( lcVerbosity == "quiet" )
  5255. config.verbosity = Verbosity::Quiet;
  5256. else if( lcVerbosity == "normal" )
  5257. config.verbosity = Verbosity::Normal;
  5258. else if( lcVerbosity == "high" )
  5259. config.verbosity = Verbosity::High;
  5260. else
  5261. return ParserResult::runtimeError( "Unrecognised verbosity, '" + verbosity + "'" );
  5262. return ParserResult::ok( ParseResultType::Matched );
  5263. };
  5264. auto cli
  5265. = ExeName( config.processName )
  5266. | Help( config.showHelp )
  5267. | Opt( config.listTests )
  5268. ["-l"]["--list-tests"]
  5269. ( "list all/matching test cases" )
  5270. | Opt( config.listTags )
  5271. ["-t"]["--list-tags"]
  5272. ( "list all/matching tags" )
  5273. | Opt( config.showSuccessfulTests )
  5274. ["-s"]["--success"]
  5275. ( "include successful tests in output" )
  5276. | Opt( config.shouldDebugBreak )
  5277. ["-b"]["--break"]
  5278. ( "break into debugger on failure" )
  5279. | Opt( config.noThrow )
  5280. ["-e"]["--nothrow"]
  5281. ( "skip exception tests" )
  5282. | Opt( config.showInvisibles )
  5283. ["-i"]["--invisibles"]
  5284. ( "show invisibles (tabs, newlines)" )
  5285. | Opt( config.outputFilename, "filename" )
  5286. ["-o"]["--out"]
  5287. ( "output filename" )
  5288. | Opt( config.reporterName, "name" )
  5289. ["-r"]["--reporter"]
  5290. ( "reporter to use (defaults to console)" )
  5291. | Opt( config.name, "name" )
  5292. ["-n"]["--name"]
  5293. ( "suite name" )
  5294. | Opt( [&]( bool ){ config.abortAfter = 1; } )
  5295. ["-a"]["--abort"]
  5296. ( "abort at first failure" )
  5297. | Opt( [&]( int x ){ config.abortAfter = x; }, "no. failures" )
  5298. ["-x"]["--abortx"]
  5299. ( "abort after x failures" )
  5300. | Opt( setWarning, "warning name" )
  5301. ["-w"]["--warn"]
  5302. ( "enable warnings" )
  5303. | Opt( [&]( bool flag ) { config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never; }, "yes|no" )
  5304. ["-d"]["--durations"]
  5305. ( "show test durations" )
  5306. | Opt( loadTestNamesFromFile, "filename" )
  5307. ["-f"]["--input-file"]
  5308. ( "load test names to run from a file" )
  5309. | Opt( config.filenamesAsTags )
  5310. ["-#"]["--filenames-as-tags"]
  5311. ( "adds a tag for the filename" )
  5312. | Opt( config.sectionsToRun, "section name" )
  5313. ["-c"]["--section"]
  5314. ( "specify section to run" )
  5315. | Opt( setVerbosity, "quiet|normal|high" )
  5316. ["-v"]["--verbosity"]
  5317. ( "set output verbosity" )
  5318. | Opt( config.listTestNamesOnly )
  5319. ["--list-test-names-only"]
  5320. ( "list all/matching test cases names only" )
  5321. | Opt( config.listReporters )
  5322. ["--list-reporters"]
  5323. ( "list all reporters" )
  5324. | Opt( setTestOrder, "decl|lex|rand" )
  5325. ["--order"]
  5326. ( "test case order (defaults to decl)" )
  5327. | Opt( setRngSeed, "'time'|number" )
  5328. ["--rng-seed"]
  5329. ( "set a specific seed for random numbers" )
  5330. | Opt( setColourUsage, "yes|no" )
  5331. ["--use-colour"]
  5332. ( "should output be colourised" )
  5333. | Opt( config.libIdentify )
  5334. ["--libidentify"]
  5335. ( "report name and version according to libidentify standard" )
  5336. | Opt( setWaitForKeypress, "start|exit|both" )
  5337. ["--wait-for-keypress"]
  5338. ( "waits for a keypress before exiting" )
  5339. | Opt( config.benchmarkResolutionMultiple, "multiplier" )
  5340. ["--benchmark-resolution-multiple"]
  5341. ( "multiple of clock resolution to run benchmarks" )
  5342. | Arg( config.testsOrTags, "test name|pattern|tags" )
  5343. ( "which test or tests to use" );
  5344. return cli;
  5345. }
  5346. } // end namespace Catch
  5347. // end catch_commandline.cpp
  5348. // start catch_common.cpp
  5349. #include <cstring>
  5350. #include <ostream>
  5351. namespace Catch {
  5352. bool SourceLineInfo::empty() const noexcept {
  5353. return file[0] == '\0';
  5354. }
  5355. bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const noexcept {
  5356. return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0);
  5357. }
  5358. bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const noexcept {
  5359. return line < other.line || ( line == other.line && (std::strcmp(file, other.file) < 0));
  5360. }
  5361. std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) {
  5362. #ifndef __GNUG__
  5363. os << info.file << '(' << info.line << ')';
  5364. #else
  5365. os << info.file << ':' << info.line;
  5366. #endif
  5367. return os;
  5368. }
  5369. std::string StreamEndStop::operator+() const {
  5370. return std::string();
  5371. }
  5372. NonCopyable::NonCopyable() = default;
  5373. NonCopyable::~NonCopyable() = default;
  5374. }
  5375. // end catch_common.cpp
  5376. // start catch_config.cpp
  5377. // start catch_enforce.h
  5378. #include <stdexcept>
  5379. #define CATCH_PREPARE_EXCEPTION( type, msg ) \
  5380. type( ( Catch::ReusableStringStream() << msg ).str() )
  5381. #define CATCH_INTERNAL_ERROR( msg ) \
  5382. throw CATCH_PREPARE_EXCEPTION( std::logic_error, CATCH_INTERNAL_LINEINFO << ": Internal Catch error: " << msg);
  5383. #define CATCH_ERROR( msg ) \
  5384. throw CATCH_PREPARE_EXCEPTION( std::domain_error, msg )
  5385. #define CATCH_ENFORCE( condition, msg ) \
  5386. do{ if( !(condition) ) CATCH_ERROR( msg ); } while(false)
  5387. // end catch_enforce.h
  5388. namespace Catch {
  5389. Config::Config( ConfigData const& data )
  5390. : m_data( data ),
  5391. m_stream( openStream() )
  5392. {
  5393. TestSpecParser parser(ITagAliasRegistry::get());
  5394. if (data.testsOrTags.empty()) {
  5395. parser.parse("~[.]"); // All not hidden tests
  5396. }
  5397. else {
  5398. m_hasTestFilters = true;
  5399. for( auto const& testOrTags : data.testsOrTags )
  5400. parser.parse( testOrTags );
  5401. }
  5402. m_testSpec = parser.testSpec();
  5403. }
  5404. std::string const& Config::getFilename() const {
  5405. return m_data.outputFilename ;
  5406. }
  5407. bool Config::listTests() const { return m_data.listTests; }
  5408. bool Config::listTestNamesOnly() const { return m_data.listTestNamesOnly; }
  5409. bool Config::listTags() const { return m_data.listTags; }
  5410. bool Config::listReporters() const { return m_data.listReporters; }
  5411. std::string Config::getProcessName() const { return m_data.processName; }
  5412. std::string const& Config::getReporterName() const { return m_data.reporterName; }
  5413. std::vector<std::string> const& Config::getTestsOrTags() const { return m_data.testsOrTags; }
  5414. std::vector<std::string> const& Config::getSectionsToRun() const { return m_data.sectionsToRun; }
  5415. TestSpec const& Config::testSpec() const { return m_testSpec; }
  5416. bool Config::hasTestFilters() const { return m_hasTestFilters; }
  5417. bool Config::showHelp() const { return m_data.showHelp; }
  5418. // IConfig interface
  5419. bool Config::allowThrows() const { return !m_data.noThrow; }
  5420. std::ostream& Config::stream() const { return m_stream->stream(); }
  5421. std::string Config::name() const { return m_data.name.empty() ? m_data.processName : m_data.name; }
  5422. bool Config::includeSuccessfulResults() const { return m_data.showSuccessfulTests; }
  5423. bool Config::warnAboutMissingAssertions() const { return !!(m_data.warnings & WarnAbout::NoAssertions); }
  5424. bool Config::warnAboutNoTests() const { return !!(m_data.warnings & WarnAbout::NoTests); }
  5425. ShowDurations::OrNot Config::showDurations() const { return m_data.showDurations; }
  5426. RunTests::InWhatOrder Config::runOrder() const { return m_data.runOrder; }
  5427. unsigned int Config::rngSeed() const { return m_data.rngSeed; }
  5428. int Config::benchmarkResolutionMultiple() const { return m_data.benchmarkResolutionMultiple; }
  5429. UseColour::YesOrNo Config::useColour() const { return m_data.useColour; }
  5430. bool Config::shouldDebugBreak() const { return m_data.shouldDebugBreak; }
  5431. int Config::abortAfter() const { return m_data.abortAfter; }
  5432. bool Config::showInvisibles() const { return m_data.showInvisibles; }
  5433. Verbosity Config::verbosity() const { return m_data.verbosity; }
  5434. IStream const* Config::openStream() {
  5435. return Catch::makeStream(m_data.outputFilename);
  5436. }
  5437. } // end namespace Catch
  5438. // end catch_config.cpp
  5439. // start catch_console_colour.cpp
  5440. #if defined(__clang__)
  5441. # pragma clang diagnostic push
  5442. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  5443. #endif
  5444. // start catch_errno_guard.h
  5445. namespace Catch {
  5446. class ErrnoGuard {
  5447. public:
  5448. ErrnoGuard();
  5449. ~ErrnoGuard();
  5450. private:
  5451. int m_oldErrno;
  5452. };
  5453. }
  5454. // end catch_errno_guard.h
  5455. #include <sstream>
  5456. namespace Catch {
  5457. namespace {
  5458. struct IColourImpl {
  5459. virtual ~IColourImpl() = default;
  5460. virtual void use( Colour::Code _colourCode ) = 0;
  5461. };
  5462. struct NoColourImpl : IColourImpl {
  5463. void use( Colour::Code ) {}
  5464. static IColourImpl* instance() {
  5465. static NoColourImpl s_instance;
  5466. return &s_instance;
  5467. }
  5468. };
  5469. } // anon namespace
  5470. } // namespace Catch
  5471. #if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI )
  5472. # ifdef CATCH_PLATFORM_WINDOWS
  5473. # define CATCH_CONFIG_COLOUR_WINDOWS
  5474. # else
  5475. # define CATCH_CONFIG_COLOUR_ANSI
  5476. # endif
  5477. #endif
  5478. #if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) /////////////////////////////////////////
  5479. namespace Catch {
  5480. namespace {
  5481. class Win32ColourImpl : public IColourImpl {
  5482. public:
  5483. Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) )
  5484. {
  5485. CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
  5486. GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo );
  5487. originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY );
  5488. originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY );
  5489. }
  5490. virtual void use( Colour::Code _colourCode ) override {
  5491. switch( _colourCode ) {
  5492. case Colour::None: return setTextAttribute( originalForegroundAttributes );
  5493. case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  5494. case Colour::Red: return setTextAttribute( FOREGROUND_RED );
  5495. case Colour::Green: return setTextAttribute( FOREGROUND_GREEN );
  5496. case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE );
  5497. case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN );
  5498. case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN );
  5499. case Colour::Grey: return setTextAttribute( 0 );
  5500. case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY );
  5501. case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED );
  5502. case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN );
  5503. case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  5504. case Colour::BrightYellow: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN );
  5505. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  5506. default:
  5507. CATCH_ERROR( "Unknown colour requested" );
  5508. }
  5509. }
  5510. private:
  5511. void setTextAttribute( WORD _textAttribute ) {
  5512. SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes );
  5513. }
  5514. HANDLE stdoutHandle;
  5515. WORD originalForegroundAttributes;
  5516. WORD originalBackgroundAttributes;
  5517. };
  5518. IColourImpl* platformColourInstance() {
  5519. static Win32ColourImpl s_instance;
  5520. IConfigPtr config = getCurrentContext().getConfig();
  5521. UseColour::YesOrNo colourMode = config
  5522. ? config->useColour()
  5523. : UseColour::Auto;
  5524. if( colourMode == UseColour::Auto )
  5525. colourMode = UseColour::Yes;
  5526. return colourMode == UseColour::Yes
  5527. ? &s_instance
  5528. : NoColourImpl::instance();
  5529. }
  5530. } // end anon namespace
  5531. } // end namespace Catch
  5532. #elif defined( CATCH_CONFIG_COLOUR_ANSI ) //////////////////////////////////////
  5533. #include <unistd.h>
  5534. namespace Catch {
  5535. namespace {
  5536. // use POSIX/ ANSI console terminal codes
  5537. // Thanks to Adam Strzelecki for original contribution
  5538. // (http://github.com/nanoant)
  5539. // https://github.com/philsquared/Catch/pull/131
  5540. class PosixColourImpl : public IColourImpl {
  5541. public:
  5542. virtual void use( Colour::Code _colourCode ) override {
  5543. switch( _colourCode ) {
  5544. case Colour::None:
  5545. case Colour::White: return setColour( "[0m" );
  5546. case Colour::Red: return setColour( "[0;31m" );
  5547. case Colour::Green: return setColour( "[0;32m" );
  5548. case Colour::Blue: return setColour( "[0;34m" );
  5549. case Colour::Cyan: return setColour( "[0;36m" );
  5550. case Colour::Yellow: return setColour( "[0;33m" );
  5551. case Colour::Grey: return setColour( "[1;30m" );
  5552. case Colour::LightGrey: return setColour( "[0;37m" );
  5553. case Colour::BrightRed: return setColour( "[1;31m" );
  5554. case Colour::BrightGreen: return setColour( "[1;32m" );
  5555. case Colour::BrightWhite: return setColour( "[1;37m" );
  5556. case Colour::BrightYellow: return setColour( "[1;33m" );
  5557. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  5558. default: CATCH_INTERNAL_ERROR( "Unknown colour requested" );
  5559. }
  5560. }
  5561. static IColourImpl* instance() {
  5562. static PosixColourImpl s_instance;
  5563. return &s_instance;
  5564. }
  5565. private:
  5566. void setColour( const char* _escapeCode ) {
  5567. Catch::cout() << '\033' << _escapeCode;
  5568. }
  5569. };
  5570. bool useColourOnPlatform() {
  5571. return
  5572. #ifdef CATCH_PLATFORM_MAC
  5573. !isDebuggerActive() &&
  5574. #endif
  5575. #if !(defined(__DJGPP__) && defined(__STRICT_ANSI__))
  5576. isatty(STDOUT_FILENO)
  5577. #else
  5578. false
  5579. #endif
  5580. ;
  5581. }
  5582. IColourImpl* platformColourInstance() {
  5583. ErrnoGuard guard;
  5584. IConfigPtr config = getCurrentContext().getConfig();
  5585. UseColour::YesOrNo colourMode = config
  5586. ? config->useColour()
  5587. : UseColour::Auto;
  5588. if( colourMode == UseColour::Auto )
  5589. colourMode = useColourOnPlatform()
  5590. ? UseColour::Yes
  5591. : UseColour::No;
  5592. return colourMode == UseColour::Yes
  5593. ? PosixColourImpl::instance()
  5594. : NoColourImpl::instance();
  5595. }
  5596. } // end anon namespace
  5597. } // end namespace Catch
  5598. #else // not Windows or ANSI ///////////////////////////////////////////////
  5599. namespace Catch {
  5600. static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); }
  5601. } // end namespace Catch
  5602. #endif // Windows/ ANSI/ None
  5603. namespace Catch {
  5604. Colour::Colour( Code _colourCode ) { use( _colourCode ); }
  5605. Colour::Colour( Colour&& rhs ) noexcept {
  5606. m_moved = rhs.m_moved;
  5607. rhs.m_moved = true;
  5608. }
  5609. Colour& Colour::operator=( Colour&& rhs ) noexcept {
  5610. m_moved = rhs.m_moved;
  5611. rhs.m_moved = true;
  5612. return *this;
  5613. }
  5614. Colour::~Colour(){ if( !m_moved ) use( None ); }
  5615. void Colour::use( Code _colourCode ) {
  5616. static IColourImpl* impl = platformColourInstance();
  5617. impl->use( _colourCode );
  5618. }
  5619. std::ostream& operator << ( std::ostream& os, Colour const& ) {
  5620. return os;
  5621. }
  5622. } // end namespace Catch
  5623. #if defined(__clang__)
  5624. # pragma clang diagnostic pop
  5625. #endif
  5626. // end catch_console_colour.cpp
  5627. // start catch_context.cpp
  5628. namespace Catch {
  5629. class Context : public IMutableContext, NonCopyable {
  5630. public: // IContext
  5631. virtual IResultCapture* getResultCapture() override {
  5632. return m_resultCapture;
  5633. }
  5634. virtual IRunner* getRunner() override {
  5635. return m_runner;
  5636. }
  5637. virtual IConfigPtr const& getConfig() const override {
  5638. return m_config;
  5639. }
  5640. virtual ~Context() override;
  5641. public: // IMutableContext
  5642. virtual void setResultCapture( IResultCapture* resultCapture ) override {
  5643. m_resultCapture = resultCapture;
  5644. }
  5645. virtual void setRunner( IRunner* runner ) override {
  5646. m_runner = runner;
  5647. }
  5648. virtual void setConfig( IConfigPtr const& config ) override {
  5649. m_config = config;
  5650. }
  5651. friend IMutableContext& getCurrentMutableContext();
  5652. private:
  5653. IConfigPtr m_config;
  5654. IRunner* m_runner = nullptr;
  5655. IResultCapture* m_resultCapture = nullptr;
  5656. };
  5657. IMutableContext *IMutableContext::currentContext = nullptr;
  5658. void IMutableContext::createContext()
  5659. {
  5660. currentContext = new Context();
  5661. }
  5662. void cleanUpContext() {
  5663. delete IMutableContext::currentContext;
  5664. IMutableContext::currentContext = nullptr;
  5665. }
  5666. IContext::~IContext() = default;
  5667. IMutableContext::~IMutableContext() = default;
  5668. Context::~Context() = default;
  5669. }
  5670. // end catch_context.cpp
  5671. // start catch_debug_console.cpp
  5672. // start catch_debug_console.h
  5673. #include <string>
  5674. namespace Catch {
  5675. void writeToDebugConsole( std::string const& text );
  5676. }
  5677. // end catch_debug_console.h
  5678. #ifdef CATCH_PLATFORM_WINDOWS
  5679. namespace Catch {
  5680. void writeToDebugConsole( std::string const& text ) {
  5681. ::OutputDebugStringA( text.c_str() );
  5682. }
  5683. }
  5684. #else
  5685. namespace Catch {
  5686. void writeToDebugConsole( std::string const& text ) {
  5687. // !TBD: Need a version for Mac/ XCode and other IDEs
  5688. Catch::cout() << text;
  5689. }
  5690. }
  5691. #endif // Platform
  5692. // end catch_debug_console.cpp
  5693. // start catch_debugger.cpp
  5694. #ifdef CATCH_PLATFORM_MAC
  5695. # include <assert.h>
  5696. # include <stdbool.h>
  5697. # include <sys/types.h>
  5698. # include <unistd.h>
  5699. # include <sys/sysctl.h>
  5700. # include <cstddef>
  5701. # include <ostream>
  5702. namespace Catch {
  5703. // The following function is taken directly from the following technical note:
  5704. // http://developer.apple.com/library/mac/#qa/qa2004/qa1361.html
  5705. // Returns true if the current process is being debugged (either
  5706. // running under the debugger or has a debugger attached post facto).
  5707. bool isDebuggerActive(){
  5708. int mib[4];
  5709. struct kinfo_proc info;
  5710. std::size_t size;
  5711. // Initialize the flags so that, if sysctl fails for some bizarre
  5712. // reason, we get a predictable result.
  5713. info.kp_proc.p_flag = 0;
  5714. // Initialize mib, which tells sysctl the info we want, in this case
  5715. // we're looking for information about a specific process ID.
  5716. mib[0] = CTL_KERN;
  5717. mib[1] = KERN_PROC;
  5718. mib[2] = KERN_PROC_PID;
  5719. mib[3] = getpid();
  5720. // Call sysctl.
  5721. size = sizeof(info);
  5722. if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0) != 0 ) {
  5723. Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl;
  5724. return false;
  5725. }
  5726. // We're being debugged if the P_TRACED flag is set.
  5727. return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
  5728. }
  5729. } // namespace Catch
  5730. #elif defined(CATCH_PLATFORM_LINUX)
  5731. #include <fstream>
  5732. #include <string>
  5733. namespace Catch{
  5734. // The standard POSIX way of detecting a debugger is to attempt to
  5735. // ptrace() the process, but this needs to be done from a child and not
  5736. // this process itself to still allow attaching to this process later
  5737. // if wanted, so is rather heavy. Under Linux we have the PID of the
  5738. // "debugger" (which doesn't need to be gdb, of course, it could also
  5739. // be strace, for example) in /proc/$PID/status, so just get it from
  5740. // there instead.
  5741. bool isDebuggerActive(){
  5742. // Libstdc++ has a bug, where std::ifstream sets errno to 0
  5743. // This way our users can properly assert over errno values
  5744. ErrnoGuard guard;
  5745. std::ifstream in("/proc/self/status");
  5746. for( std::string line; std::getline(in, line); ) {
  5747. static const int PREFIX_LEN = 11;
  5748. if( line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0 ) {
  5749. // We're traced if the PID is not 0 and no other PID starts
  5750. // with 0 digit, so it's enough to check for just a single
  5751. // character.
  5752. return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0';
  5753. }
  5754. }
  5755. return false;
  5756. }
  5757. } // namespace Catch
  5758. #elif defined(_MSC_VER)
  5759. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  5760. namespace Catch {
  5761. bool isDebuggerActive() {
  5762. return IsDebuggerPresent() != 0;
  5763. }
  5764. }
  5765. #elif defined(__MINGW32__)
  5766. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  5767. namespace Catch {
  5768. bool isDebuggerActive() {
  5769. return IsDebuggerPresent() != 0;
  5770. }
  5771. }
  5772. #else
  5773. namespace Catch {
  5774. bool isDebuggerActive() { return false; }
  5775. }
  5776. #endif // Platform
  5777. // end catch_debugger.cpp
  5778. // start catch_decomposer.cpp
  5779. namespace Catch {
  5780. ITransientExpression::~ITransientExpression() = default;
  5781. void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs ) {
  5782. if( lhs.size() + rhs.size() < 40 &&
  5783. lhs.find('\n') == std::string::npos &&
  5784. rhs.find('\n') == std::string::npos )
  5785. os << lhs << " " << op << " " << rhs;
  5786. else
  5787. os << lhs << "\n" << op << "\n" << rhs;
  5788. }
  5789. }
  5790. // end catch_decomposer.cpp
  5791. // start catch_errno_guard.cpp
  5792. #include <cerrno>
  5793. namespace Catch {
  5794. ErrnoGuard::ErrnoGuard():m_oldErrno(errno){}
  5795. ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; }
  5796. }
  5797. // end catch_errno_guard.cpp
  5798. // start catch_exception_translator_registry.cpp
  5799. // start catch_exception_translator_registry.h
  5800. #include <vector>
  5801. #include <string>
  5802. #include <memory>
  5803. namespace Catch {
  5804. class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry {
  5805. public:
  5806. ~ExceptionTranslatorRegistry();
  5807. virtual void registerTranslator( const IExceptionTranslator* translator );
  5808. virtual std::string translateActiveException() const override;
  5809. std::string tryTranslators() const;
  5810. private:
  5811. std::vector<std::unique_ptr<IExceptionTranslator const>> m_translators;
  5812. };
  5813. }
  5814. // end catch_exception_translator_registry.h
  5815. #ifdef __OBJC__
  5816. #import "Foundation/Foundation.h"
  5817. #endif
  5818. namespace Catch {
  5819. ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {
  5820. }
  5821. void ExceptionTranslatorRegistry::registerTranslator( const IExceptionTranslator* translator ) {
  5822. m_translators.push_back( std::unique_ptr<const IExceptionTranslator>( translator ) );
  5823. }
  5824. std::string ExceptionTranslatorRegistry::translateActiveException() const {
  5825. try {
  5826. #ifdef __OBJC__
  5827. // In Objective-C try objective-c exceptions first
  5828. @try {
  5829. return tryTranslators();
  5830. }
  5831. @catch (NSException *exception) {
  5832. return Catch::Detail::stringify( [exception description] );
  5833. }
  5834. #else
  5835. // Compiling a mixed mode project with MSVC means that CLR
  5836. // exceptions will be caught in (...) as well. However, these
  5837. // do not fill-in std::current_exception and thus lead to crash
  5838. // when attempting rethrow.
  5839. // /EHa switch also causes structured exceptions to be caught
  5840. // here, but they fill-in current_exception properly, so
  5841. // at worst the output should be a little weird, instead of
  5842. // causing a crash.
  5843. if (std::current_exception() == nullptr) {
  5844. return "Non C++ exception. Possibly a CLR exception.";
  5845. }
  5846. return tryTranslators();
  5847. #endif
  5848. }
  5849. catch( TestFailureException& ) {
  5850. std::rethrow_exception(std::current_exception());
  5851. }
  5852. catch( std::exception& ex ) {
  5853. return ex.what();
  5854. }
  5855. catch( std::string& msg ) {
  5856. return msg;
  5857. }
  5858. catch( const char* msg ) {
  5859. return msg;
  5860. }
  5861. catch(...) {
  5862. return "Unknown exception";
  5863. }
  5864. }
  5865. std::string ExceptionTranslatorRegistry::tryTranslators() const {
  5866. if( m_translators.empty() )
  5867. std::rethrow_exception(std::current_exception());
  5868. else
  5869. return m_translators[0]->translate( m_translators.begin()+1, m_translators.end() );
  5870. }
  5871. }
  5872. // end catch_exception_translator_registry.cpp
  5873. // start catch_fatal_condition.cpp
  5874. #if defined(__GNUC__)
  5875. # pragma GCC diagnostic push
  5876. # pragma GCC diagnostic ignored "-Wmissing-field-initializers"
  5877. #endif
  5878. #if defined( CATCH_CONFIG_WINDOWS_SEH ) || defined( CATCH_CONFIG_POSIX_SIGNALS )
  5879. namespace {
  5880. // Report the error condition
  5881. void reportFatal( char const * const message ) {
  5882. Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition( message );
  5883. }
  5884. }
  5885. #endif // signals/SEH handling
  5886. #if defined( CATCH_CONFIG_WINDOWS_SEH )
  5887. namespace Catch {
  5888. struct SignalDefs { DWORD id; const char* name; };
  5889. // There is no 1-1 mapping between signals and windows exceptions.
  5890. // Windows can easily distinguish between SO and SigSegV,
  5891. // but SigInt, SigTerm, etc are handled differently.
  5892. static SignalDefs signalDefs[] = {
  5893. { EXCEPTION_ILLEGAL_INSTRUCTION, "SIGILL - Illegal instruction signal" },
  5894. { EXCEPTION_STACK_OVERFLOW, "SIGSEGV - Stack overflow" },
  5895. { EXCEPTION_ACCESS_VIOLATION, "SIGSEGV - Segmentation violation signal" },
  5896. { EXCEPTION_INT_DIVIDE_BY_ZERO, "Divide by zero error" },
  5897. };
  5898. LONG CALLBACK FatalConditionHandler::handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {
  5899. for (auto const& def : signalDefs) {
  5900. if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) {
  5901. reportFatal(def.name);
  5902. }
  5903. }
  5904. // If its not an exception we care about, pass it along.
  5905. // This stops us from eating debugger breaks etc.
  5906. return EXCEPTION_CONTINUE_SEARCH;
  5907. }
  5908. FatalConditionHandler::FatalConditionHandler() {
  5909. isSet = true;
  5910. // 32k seems enough for Catch to handle stack overflow,
  5911. // but the value was found experimentally, so there is no strong guarantee
  5912. guaranteeSize = 32 * 1024;
  5913. exceptionHandlerHandle = nullptr;
  5914. // Register as first handler in current chain
  5915. exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);
  5916. // Pass in guarantee size to be filled
  5917. SetThreadStackGuarantee(&guaranteeSize);
  5918. }
  5919. void FatalConditionHandler::reset() {
  5920. if (isSet) {
  5921. RemoveVectoredExceptionHandler(exceptionHandlerHandle);
  5922. SetThreadStackGuarantee(&guaranteeSize);
  5923. exceptionHandlerHandle = nullptr;
  5924. isSet = false;
  5925. }
  5926. }
  5927. FatalConditionHandler::~FatalConditionHandler() {
  5928. reset();
  5929. }
  5930. bool FatalConditionHandler::isSet = false;
  5931. ULONG FatalConditionHandler::guaranteeSize = 0;
  5932. PVOID FatalConditionHandler::exceptionHandlerHandle = nullptr;
  5933. } // namespace Catch
  5934. #elif defined( CATCH_CONFIG_POSIX_SIGNALS )
  5935. namespace Catch {
  5936. struct SignalDefs {
  5937. int id;
  5938. const char* name;
  5939. };
  5940. // 32kb for the alternate stack seems to be sufficient. However, this value
  5941. // is experimentally determined, so that's not guaranteed.
  5942. constexpr static std::size_t sigStackSize = 32768 >= MINSIGSTKSZ ? 32768 : MINSIGSTKSZ;
  5943. static SignalDefs signalDefs[] = {
  5944. { SIGINT, "SIGINT - Terminal interrupt signal" },
  5945. { SIGILL, "SIGILL - Illegal instruction signal" },
  5946. { SIGFPE, "SIGFPE - Floating point error signal" },
  5947. { SIGSEGV, "SIGSEGV - Segmentation violation signal" },
  5948. { SIGTERM, "SIGTERM - Termination request signal" },
  5949. { SIGABRT, "SIGABRT - Abort (abnormal termination) signal" }
  5950. };
  5951. void FatalConditionHandler::handleSignal( int sig ) {
  5952. char const * name = "<unknown signal>";
  5953. for (auto const& def : signalDefs) {
  5954. if (sig == def.id) {
  5955. name = def.name;
  5956. break;
  5957. }
  5958. }
  5959. reset();
  5960. reportFatal(name);
  5961. raise( sig );
  5962. }
  5963. FatalConditionHandler::FatalConditionHandler() {
  5964. isSet = true;
  5965. stack_t sigStack;
  5966. sigStack.ss_sp = altStackMem;
  5967. sigStack.ss_size = sigStackSize;
  5968. sigStack.ss_flags = 0;
  5969. sigaltstack(&sigStack, &oldSigStack);
  5970. struct sigaction sa = { };
  5971. sa.sa_handler = handleSignal;
  5972. sa.sa_flags = SA_ONSTACK;
  5973. for (std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i) {
  5974. sigaction(signalDefs[i].id, &sa, &oldSigActions[i]);
  5975. }
  5976. }
  5977. FatalConditionHandler::~FatalConditionHandler() {
  5978. reset();
  5979. }
  5980. void FatalConditionHandler::reset() {
  5981. if( isSet ) {
  5982. // Set signals back to previous values -- hopefully nobody overwrote them in the meantime
  5983. for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) {
  5984. sigaction(signalDefs[i].id, &oldSigActions[i], nullptr);
  5985. }
  5986. // Return the old stack
  5987. sigaltstack(&oldSigStack, nullptr);
  5988. isSet = false;
  5989. }
  5990. }
  5991. bool FatalConditionHandler::isSet = false;
  5992. struct sigaction FatalConditionHandler::oldSigActions[sizeof(signalDefs)/sizeof(SignalDefs)] = {};
  5993. stack_t FatalConditionHandler::oldSigStack = {};
  5994. char FatalConditionHandler::altStackMem[sigStackSize] = {};
  5995. } // namespace Catch
  5996. #else
  5997. namespace Catch {
  5998. void FatalConditionHandler::reset() {}
  5999. }
  6000. #endif // signals/SEH handling
  6001. #if defined(__GNUC__)
  6002. # pragma GCC diagnostic pop
  6003. #endif
  6004. // end catch_fatal_condition.cpp
  6005. // start catch_interfaces_capture.cpp
  6006. namespace Catch {
  6007. IResultCapture::~IResultCapture() = default;
  6008. }
  6009. // end catch_interfaces_capture.cpp
  6010. // start catch_interfaces_config.cpp
  6011. namespace Catch {
  6012. IConfig::~IConfig() = default;
  6013. }
  6014. // end catch_interfaces_config.cpp
  6015. // start catch_interfaces_exception.cpp
  6016. namespace Catch {
  6017. IExceptionTranslator::~IExceptionTranslator() = default;
  6018. IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() = default;
  6019. }
  6020. // end catch_interfaces_exception.cpp
  6021. // start catch_interfaces_registry_hub.cpp
  6022. namespace Catch {
  6023. IRegistryHub::~IRegistryHub() = default;
  6024. IMutableRegistryHub::~IMutableRegistryHub() = default;
  6025. }
  6026. // end catch_interfaces_registry_hub.cpp
  6027. // start catch_interfaces_reporter.cpp
  6028. // start catch_reporter_listening.h
  6029. namespace Catch {
  6030. class ListeningReporter : public IStreamingReporter {
  6031. using Reporters = std::vector<IStreamingReporterPtr>;
  6032. Reporters m_listeners;
  6033. IStreamingReporterPtr m_reporter = nullptr;
  6034. public:
  6035. void addListener( IStreamingReporterPtr&& listener );
  6036. void addReporter( IStreamingReporterPtr&& reporter );
  6037. public: // IStreamingReporter
  6038. ReporterPreferences getPreferences() const override;
  6039. void noMatchingTestCases( std::string const& spec ) override;
  6040. static std::set<Verbosity> getSupportedVerbosities();
  6041. void benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) override;
  6042. void benchmarkEnded( BenchmarkStats const& benchmarkStats ) override;
  6043. void testRunStarting( TestRunInfo const& testRunInfo ) override;
  6044. void testGroupStarting( GroupInfo const& groupInfo ) override;
  6045. void testCaseStarting( TestCaseInfo const& testInfo ) override;
  6046. void sectionStarting( SectionInfo const& sectionInfo ) override;
  6047. void assertionStarting( AssertionInfo const& assertionInfo ) override;
  6048. // The return value indicates if the messages buffer should be cleared:
  6049. bool assertionEnded( AssertionStats const& assertionStats ) override;
  6050. void sectionEnded( SectionStats const& sectionStats ) override;
  6051. void testCaseEnded( TestCaseStats const& testCaseStats ) override;
  6052. void testGroupEnded( TestGroupStats const& testGroupStats ) override;
  6053. void testRunEnded( TestRunStats const& testRunStats ) override;
  6054. void skipTest( TestCaseInfo const& testInfo ) override;
  6055. bool isMulti() const override;
  6056. };
  6057. } // end namespace Catch
  6058. // end catch_reporter_listening.h
  6059. namespace Catch {
  6060. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig )
  6061. : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {}
  6062. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream )
  6063. : m_stream( &_stream ), m_fullConfig( _fullConfig ) {}
  6064. std::ostream& ReporterConfig::stream() const { return *m_stream; }
  6065. IConfigPtr ReporterConfig::fullConfig() const { return m_fullConfig; }
  6066. TestRunInfo::TestRunInfo( std::string const& _name ) : name( _name ) {}
  6067. GroupInfo::GroupInfo( std::string const& _name,
  6068. std::size_t _groupIndex,
  6069. std::size_t _groupsCount )
  6070. : name( _name ),
  6071. groupIndex( _groupIndex ),
  6072. groupsCounts( _groupsCount )
  6073. {}
  6074. AssertionStats::AssertionStats( AssertionResult const& _assertionResult,
  6075. std::vector<MessageInfo> const& _infoMessages,
  6076. Totals const& _totals )
  6077. : assertionResult( _assertionResult ),
  6078. infoMessages( _infoMessages ),
  6079. totals( _totals )
  6080. {
  6081. assertionResult.m_resultData.lazyExpression.m_transientExpression = _assertionResult.m_resultData.lazyExpression.m_transientExpression;
  6082. if( assertionResult.hasMessage() ) {
  6083. // Copy message into messages list.
  6084. // !TBD This should have been done earlier, somewhere
  6085. MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() );
  6086. builder << assertionResult.getMessage();
  6087. builder.m_info.message = builder.m_stream.str();
  6088. infoMessages.push_back( builder.m_info );
  6089. }
  6090. }
  6091. AssertionStats::~AssertionStats() = default;
  6092. SectionStats::SectionStats( SectionInfo const& _sectionInfo,
  6093. Counts const& _assertions,
  6094. double _durationInSeconds,
  6095. bool _missingAssertions )
  6096. : sectionInfo( _sectionInfo ),
  6097. assertions( _assertions ),
  6098. durationInSeconds( _durationInSeconds ),
  6099. missingAssertions( _missingAssertions )
  6100. {}
  6101. SectionStats::~SectionStats() = default;
  6102. TestCaseStats::TestCaseStats( TestCaseInfo const& _testInfo,
  6103. Totals const& _totals,
  6104. std::string const& _stdOut,
  6105. std::string const& _stdErr,
  6106. bool _aborting )
  6107. : testInfo( _testInfo ),
  6108. totals( _totals ),
  6109. stdOut( _stdOut ),
  6110. stdErr( _stdErr ),
  6111. aborting( _aborting )
  6112. {}
  6113. TestCaseStats::~TestCaseStats() = default;
  6114. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo,
  6115. Totals const& _totals,
  6116. bool _aborting )
  6117. : groupInfo( _groupInfo ),
  6118. totals( _totals ),
  6119. aborting( _aborting )
  6120. {}
  6121. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo )
  6122. : groupInfo( _groupInfo ),
  6123. aborting( false )
  6124. {}
  6125. TestGroupStats::~TestGroupStats() = default;
  6126. TestRunStats::TestRunStats( TestRunInfo const& _runInfo,
  6127. Totals const& _totals,
  6128. bool _aborting )
  6129. : runInfo( _runInfo ),
  6130. totals( _totals ),
  6131. aborting( _aborting )
  6132. {}
  6133. TestRunStats::~TestRunStats() = default;
  6134. void IStreamingReporter::fatalErrorEncountered( StringRef ) {}
  6135. bool IStreamingReporter::isMulti() const { return false; }
  6136. IReporterFactory::~IReporterFactory() = default;
  6137. IReporterRegistry::~IReporterRegistry() = default;
  6138. } // end namespace Catch
  6139. // end catch_interfaces_reporter.cpp
  6140. // start catch_interfaces_runner.cpp
  6141. namespace Catch {
  6142. IRunner::~IRunner() = default;
  6143. }
  6144. // end catch_interfaces_runner.cpp
  6145. // start catch_interfaces_testcase.cpp
  6146. namespace Catch {
  6147. ITestInvoker::~ITestInvoker() = default;
  6148. ITestCaseRegistry::~ITestCaseRegistry() = default;
  6149. }
  6150. // end catch_interfaces_testcase.cpp
  6151. // start catch_leak_detector.cpp
  6152. #ifdef CATCH_CONFIG_WINDOWS_CRTDBG
  6153. #include <crtdbg.h>
  6154. namespace Catch {
  6155. LeakDetector::LeakDetector() {
  6156. int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
  6157. flag |= _CRTDBG_LEAK_CHECK_DF;
  6158. flag |= _CRTDBG_ALLOC_MEM_DF;
  6159. _CrtSetDbgFlag(flag);
  6160. _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
  6161. _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
  6162. // Change this to leaking allocation's number to break there
  6163. _CrtSetBreakAlloc(-1);
  6164. }
  6165. }
  6166. #else
  6167. Catch::LeakDetector::LeakDetector() {}
  6168. #endif
  6169. // end catch_leak_detector.cpp
  6170. // start catch_list.cpp
  6171. // start catch_list.h
  6172. #include <set>
  6173. namespace Catch {
  6174. std::size_t listTests( Config const& config );
  6175. std::size_t listTestsNamesOnly( Config const& config );
  6176. struct TagInfo {
  6177. void add( std::string const& spelling );
  6178. std::string all() const;
  6179. std::set<std::string> spellings;
  6180. std::size_t count = 0;
  6181. };
  6182. std::size_t listTags( Config const& config );
  6183. std::size_t listReporters( Config const& /*config*/ );
  6184. Option<std::size_t> list( Config const& config );
  6185. } // end namespace Catch
  6186. // end catch_list.h
  6187. // start catch_text.h
  6188. namespace Catch {
  6189. using namespace clara::TextFlow;
  6190. }
  6191. // end catch_text.h
  6192. #include <limits>
  6193. #include <algorithm>
  6194. #include <iomanip>
  6195. namespace Catch {
  6196. std::size_t listTests( Config const& config ) {
  6197. TestSpec testSpec = config.testSpec();
  6198. if( config.hasTestFilters() )
  6199. Catch::cout() << "Matching test cases:\n";
  6200. else {
  6201. Catch::cout() << "All available test cases:\n";
  6202. }
  6203. auto matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  6204. for( auto const& testCaseInfo : matchedTestCases ) {
  6205. Colour::Code colour = testCaseInfo.isHidden()
  6206. ? Colour::SecondaryText
  6207. : Colour::None;
  6208. Colour colourGuard( colour );
  6209. Catch::cout() << Column( testCaseInfo.name ).initialIndent( 2 ).indent( 4 ) << "\n";
  6210. if( config.verbosity() >= Verbosity::High ) {
  6211. Catch::cout() << Column( Catch::Detail::stringify( testCaseInfo.lineInfo ) ).indent(4) << std::endl;
  6212. std::string description = testCaseInfo.description;
  6213. if( description.empty() )
  6214. description = "(NO DESCRIPTION)";
  6215. Catch::cout() << Column( description ).indent(4) << std::endl;
  6216. }
  6217. if( !testCaseInfo.tags.empty() )
  6218. Catch::cout() << Column( testCaseInfo.tagsAsString() ).indent( 6 ) << "\n";
  6219. }
  6220. if( !config.hasTestFilters() )
  6221. Catch::cout() << pluralise( matchedTestCases.size(), "test case" ) << '\n' << std::endl;
  6222. else
  6223. Catch::cout() << pluralise( matchedTestCases.size(), "matching test case" ) << '\n' << std::endl;
  6224. return matchedTestCases.size();
  6225. }
  6226. std::size_t listTestsNamesOnly( Config const& config ) {
  6227. TestSpec testSpec = config.testSpec();
  6228. std::size_t matchedTests = 0;
  6229. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  6230. for( auto const& testCaseInfo : matchedTestCases ) {
  6231. matchedTests++;
  6232. if( startsWith( testCaseInfo.name, '#' ) )
  6233. Catch::cout() << '"' << testCaseInfo.name << '"';
  6234. else
  6235. Catch::cout() << testCaseInfo.name;
  6236. if ( config.verbosity() >= Verbosity::High )
  6237. Catch::cout() << "\t@" << testCaseInfo.lineInfo;
  6238. Catch::cout() << std::endl;
  6239. }
  6240. return matchedTests;
  6241. }
  6242. void TagInfo::add( std::string const& spelling ) {
  6243. ++count;
  6244. spellings.insert( spelling );
  6245. }
  6246. std::string TagInfo::all() const {
  6247. std::string out;
  6248. for( auto const& spelling : spellings )
  6249. out += "[" + spelling + "]";
  6250. return out;
  6251. }
  6252. std::size_t listTags( Config const& config ) {
  6253. TestSpec testSpec = config.testSpec();
  6254. if( config.hasTestFilters() )
  6255. Catch::cout() << "Tags for matching test cases:\n";
  6256. else {
  6257. Catch::cout() << "All available tags:\n";
  6258. }
  6259. std::map<std::string, TagInfo> tagCounts;
  6260. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  6261. for( auto const& testCase : matchedTestCases ) {
  6262. for( auto const& tagName : testCase.getTestCaseInfo().tags ) {
  6263. std::string lcaseTagName = toLower( tagName );
  6264. auto countIt = tagCounts.find( lcaseTagName );
  6265. if( countIt == tagCounts.end() )
  6266. countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first;
  6267. countIt->second.add( tagName );
  6268. }
  6269. }
  6270. for( auto const& tagCount : tagCounts ) {
  6271. ReusableStringStream rss;
  6272. rss << " " << std::setw(2) << tagCount.second.count << " ";
  6273. auto str = rss.str();
  6274. auto wrapper = Column( tagCount.second.all() )
  6275. .initialIndent( 0 )
  6276. .indent( str.size() )
  6277. .width( CATCH_CONFIG_CONSOLE_WIDTH-10 );
  6278. Catch::cout() << str << wrapper << '\n';
  6279. }
  6280. Catch::cout() << pluralise( tagCounts.size(), "tag" ) << '\n' << std::endl;
  6281. return tagCounts.size();
  6282. }
  6283. std::size_t listReporters( Config const& /*config*/ ) {
  6284. Catch::cout() << "Available reporters:\n";
  6285. IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
  6286. std::size_t maxNameLen = 0;
  6287. for( auto const& factoryKvp : factories )
  6288. maxNameLen = (std::max)( maxNameLen, factoryKvp.first.size() );
  6289. for( auto const& factoryKvp : factories ) {
  6290. Catch::cout()
  6291. << Column( factoryKvp.first + ":" )
  6292. .indent(2)
  6293. .width( 5+maxNameLen )
  6294. + Column( factoryKvp.second->getDescription() )
  6295. .initialIndent(0)
  6296. .indent(2)
  6297. .width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 )
  6298. << "\n";
  6299. }
  6300. Catch::cout() << std::endl;
  6301. return factories.size();
  6302. }
  6303. Option<std::size_t> list( Config const& config ) {
  6304. Option<std::size_t> listedCount;
  6305. if( config.listTests() )
  6306. listedCount = listedCount.valueOr(0) + listTests( config );
  6307. if( config.listTestNamesOnly() )
  6308. listedCount = listedCount.valueOr(0) + listTestsNamesOnly( config );
  6309. if( config.listTags() )
  6310. listedCount = listedCount.valueOr(0) + listTags( config );
  6311. if( config.listReporters() )
  6312. listedCount = listedCount.valueOr(0) + listReporters( config );
  6313. return listedCount;
  6314. }
  6315. } // end namespace Catch
  6316. // end catch_list.cpp
  6317. // start catch_matchers.cpp
  6318. namespace Catch {
  6319. namespace Matchers {
  6320. namespace Impl {
  6321. std::string MatcherUntypedBase::toString() const {
  6322. if( m_cachedToString.empty() )
  6323. m_cachedToString = describe();
  6324. return m_cachedToString;
  6325. }
  6326. MatcherUntypedBase::~MatcherUntypedBase() = default;
  6327. } // namespace Impl
  6328. } // namespace Matchers
  6329. using namespace Matchers;
  6330. using Matchers::Impl::MatcherBase;
  6331. } // namespace Catch
  6332. // end catch_matchers.cpp
  6333. // start catch_matchers_floating.cpp
  6334. // start catch_to_string.hpp
  6335. #include <string>
  6336. namespace Catch {
  6337. template <typename T>
  6338. std::string to_string(T const& t) {
  6339. #if defined(CATCH_CONFIG_CPP11_TO_STRING)
  6340. return std::to_string(t);
  6341. #else
  6342. ReusableStringStream rss;
  6343. rss << t;
  6344. return rss.str();
  6345. #endif
  6346. }
  6347. } // end namespace Catch
  6348. // end catch_to_string.hpp
  6349. #include <cstdlib>
  6350. #include <cstdint>
  6351. #include <cstring>
  6352. #include <stdexcept>
  6353. namespace Catch {
  6354. namespace Matchers {
  6355. namespace Floating {
  6356. enum class FloatingPointKind : uint8_t {
  6357. Float,
  6358. Double
  6359. };
  6360. }
  6361. }
  6362. }
  6363. namespace {
  6364. template <typename T>
  6365. struct Converter;
  6366. template <>
  6367. struct Converter<float> {
  6368. static_assert(sizeof(float) == sizeof(int32_t), "Important ULP matcher assumption violated");
  6369. Converter(float f) {
  6370. std::memcpy(&i, &f, sizeof(f));
  6371. }
  6372. int32_t i;
  6373. };
  6374. template <>
  6375. struct Converter<double> {
  6376. static_assert(sizeof(double) == sizeof(int64_t), "Important ULP matcher assumption violated");
  6377. Converter(double d) {
  6378. std::memcpy(&i, &d, sizeof(d));
  6379. }
  6380. int64_t i;
  6381. };
  6382. template <typename T>
  6383. auto convert(T t) -> Converter<T> {
  6384. return Converter<T>(t);
  6385. }
  6386. template <typename FP>
  6387. bool almostEqualUlps(FP lhs, FP rhs, int maxUlpDiff) {
  6388. // Comparison with NaN should always be false.
  6389. // This way we can rule it out before getting into the ugly details
  6390. if (std::isnan(lhs) || std::isnan(rhs)) {
  6391. return false;
  6392. }
  6393. auto lc = convert(lhs);
  6394. auto rc = convert(rhs);
  6395. if ((lc.i < 0) != (rc.i < 0)) {
  6396. // Potentially we can have +0 and -0
  6397. return lhs == rhs;
  6398. }
  6399. auto ulpDiff = std::abs(lc.i - rc.i);
  6400. return ulpDiff <= maxUlpDiff;
  6401. }
  6402. }
  6403. namespace Catch {
  6404. namespace Matchers {
  6405. namespace Floating {
  6406. WithinAbsMatcher::WithinAbsMatcher(double target, double margin)
  6407. :m_target{ target }, m_margin{ margin } {
  6408. if (m_margin < 0) {
  6409. throw std::domain_error("Allowed margin difference has to be >= 0");
  6410. }
  6411. }
  6412. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  6413. // But without the subtraction to allow for INFINITY in comparison
  6414. bool WithinAbsMatcher::match(double const& matchee) const {
  6415. return (matchee + m_margin >= m_target) && (m_target + m_margin >= matchee);
  6416. }
  6417. std::string WithinAbsMatcher::describe() const {
  6418. return "is within " + ::Catch::Detail::stringify(m_margin) + " of " + ::Catch::Detail::stringify(m_target);
  6419. }
  6420. WithinUlpsMatcher::WithinUlpsMatcher(double target, int ulps, FloatingPointKind baseType)
  6421. :m_target{ target }, m_ulps{ ulps }, m_type{ baseType } {
  6422. if (m_ulps < 0) {
  6423. throw std::domain_error("Allowed ulp difference has to be >= 0");
  6424. }
  6425. }
  6426. bool WithinUlpsMatcher::match(double const& matchee) const {
  6427. switch (m_type) {
  6428. case FloatingPointKind::Float:
  6429. return almostEqualUlps<float>(static_cast<float>(matchee), static_cast<float>(m_target), m_ulps);
  6430. case FloatingPointKind::Double:
  6431. return almostEqualUlps<double>(matchee, m_target, m_ulps);
  6432. default:
  6433. throw std::domain_error("Unknown FloatingPointKind value");
  6434. }
  6435. }
  6436. std::string WithinUlpsMatcher::describe() const {
  6437. return "is within " + Catch::to_string(m_ulps) + " ULPs of " + ::Catch::Detail::stringify(m_target) + ((m_type == FloatingPointKind::Float)? "f" : "");
  6438. }
  6439. }// namespace Floating
  6440. Floating::WithinUlpsMatcher WithinULP(double target, int maxUlpDiff) {
  6441. return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Double);
  6442. }
  6443. Floating::WithinUlpsMatcher WithinULP(float target, int maxUlpDiff) {
  6444. return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Float);
  6445. }
  6446. Floating::WithinAbsMatcher WithinAbs(double target, double margin) {
  6447. return Floating::WithinAbsMatcher(target, margin);
  6448. }
  6449. } // namespace Matchers
  6450. } // namespace Catch
  6451. // end catch_matchers_floating.cpp
  6452. // start catch_matchers_generic.cpp
  6453. std::string Catch::Matchers::Generic::Detail::finalizeDescription(const std::string& desc) {
  6454. if (desc.empty()) {
  6455. return "matches undescribed predicate";
  6456. } else {
  6457. return "matches predicate: \"" + desc + '"';
  6458. }
  6459. }
  6460. // end catch_matchers_generic.cpp
  6461. // start catch_matchers_string.cpp
  6462. #include <regex>
  6463. namespace Catch {
  6464. namespace Matchers {
  6465. namespace StdString {
  6466. CasedString::CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity )
  6467. : m_caseSensitivity( caseSensitivity ),
  6468. m_str( adjustString( str ) )
  6469. {}
  6470. std::string CasedString::adjustString( std::string const& str ) const {
  6471. return m_caseSensitivity == CaseSensitive::No
  6472. ? toLower( str )
  6473. : str;
  6474. }
  6475. std::string CasedString::caseSensitivitySuffix() const {
  6476. return m_caseSensitivity == CaseSensitive::No
  6477. ? " (case insensitive)"
  6478. : std::string();
  6479. }
  6480. StringMatcherBase::StringMatcherBase( std::string const& operation, CasedString const& comparator )
  6481. : m_comparator( comparator ),
  6482. m_operation( operation ) {
  6483. }
  6484. std::string StringMatcherBase::describe() const {
  6485. std::string description;
  6486. description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
  6487. m_comparator.caseSensitivitySuffix().size());
  6488. description += m_operation;
  6489. description += ": \"";
  6490. description += m_comparator.m_str;
  6491. description += "\"";
  6492. description += m_comparator.caseSensitivitySuffix();
  6493. return description;
  6494. }
  6495. EqualsMatcher::EqualsMatcher( CasedString const& comparator ) : StringMatcherBase( "equals", comparator ) {}
  6496. bool EqualsMatcher::match( std::string const& source ) const {
  6497. return m_comparator.adjustString( source ) == m_comparator.m_str;
  6498. }
  6499. ContainsMatcher::ContainsMatcher( CasedString const& comparator ) : StringMatcherBase( "contains", comparator ) {}
  6500. bool ContainsMatcher::match( std::string const& source ) const {
  6501. return contains( m_comparator.adjustString( source ), m_comparator.m_str );
  6502. }
  6503. StartsWithMatcher::StartsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "starts with", comparator ) {}
  6504. bool StartsWithMatcher::match( std::string const& source ) const {
  6505. return startsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  6506. }
  6507. EndsWithMatcher::EndsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "ends with", comparator ) {}
  6508. bool EndsWithMatcher::match( std::string const& source ) const {
  6509. return endsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  6510. }
  6511. RegexMatcher::RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity): m_regex(std::move(regex)), m_caseSensitivity(caseSensitivity) {}
  6512. bool RegexMatcher::match(std::string const& matchee) const {
  6513. auto flags = std::regex::ECMAScript; // ECMAScript is the default syntax option anyway
  6514. if (m_caseSensitivity == CaseSensitive::Choice::No) {
  6515. flags |= std::regex::icase;
  6516. }
  6517. auto reg = std::regex(m_regex, flags);
  6518. return std::regex_match(matchee, reg);
  6519. }
  6520. std::string RegexMatcher::describe() const {
  6521. return "matches " + ::Catch::Detail::stringify(m_regex) + ((m_caseSensitivity == CaseSensitive::Choice::Yes)? " case sensitively" : " case insensitively");
  6522. }
  6523. } // namespace StdString
  6524. StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  6525. return StdString::EqualsMatcher( StdString::CasedString( str, caseSensitivity) );
  6526. }
  6527. StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  6528. return StdString::ContainsMatcher( StdString::CasedString( str, caseSensitivity) );
  6529. }
  6530. StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  6531. return StdString::EndsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  6532. }
  6533. StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  6534. return StdString::StartsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  6535. }
  6536. StdString::RegexMatcher Matches(std::string const& regex, CaseSensitive::Choice caseSensitivity) {
  6537. return StdString::RegexMatcher(regex, caseSensitivity);
  6538. }
  6539. } // namespace Matchers
  6540. } // namespace Catch
  6541. // end catch_matchers_string.cpp
  6542. // start catch_message.cpp
  6543. // start catch_uncaught_exceptions.h
  6544. namespace Catch {
  6545. bool uncaught_exceptions();
  6546. } // end namespace Catch
  6547. // end catch_uncaught_exceptions.h
  6548. namespace Catch {
  6549. MessageInfo::MessageInfo( std::string const& _macroName,
  6550. SourceLineInfo const& _lineInfo,
  6551. ResultWas::OfType _type )
  6552. : macroName( _macroName ),
  6553. lineInfo( _lineInfo ),
  6554. type( _type ),
  6555. sequence( ++globalCount )
  6556. {}
  6557. bool MessageInfo::operator==( MessageInfo const& other ) const {
  6558. return sequence == other.sequence;
  6559. }
  6560. bool MessageInfo::operator<( MessageInfo const& other ) const {
  6561. return sequence < other.sequence;
  6562. }
  6563. // This may need protecting if threading support is added
  6564. unsigned int MessageInfo::globalCount = 0;
  6565. ////////////////////////////////////////////////////////////////////////////
  6566. Catch::MessageBuilder::MessageBuilder( std::string const& macroName,
  6567. SourceLineInfo const& lineInfo,
  6568. ResultWas::OfType type )
  6569. :m_info(macroName, lineInfo, type) {}
  6570. ////////////////////////////////////////////////////////////////////////////
  6571. ScopedMessage::ScopedMessage( MessageBuilder const& builder )
  6572. : m_info( builder.m_info )
  6573. {
  6574. m_info.message = builder.m_stream.str();
  6575. getResultCapture().pushScopedMessage( m_info );
  6576. }
  6577. ScopedMessage::~ScopedMessage() {
  6578. if ( !uncaught_exceptions() ){
  6579. getResultCapture().popScopedMessage(m_info);
  6580. }
  6581. }
  6582. } // end namespace Catch
  6583. // end catch_message.cpp
  6584. // start catch_output_redirect.cpp
  6585. // start catch_output_redirect.h
  6586. #ifndef TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  6587. #define TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  6588. #include <cstdio>
  6589. #include <iosfwd>
  6590. #include <string>
  6591. namespace Catch {
  6592. class RedirectedStream {
  6593. std::ostream& m_originalStream;
  6594. std::ostream& m_redirectionStream;
  6595. std::streambuf* m_prevBuf;
  6596. public:
  6597. RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream );
  6598. ~RedirectedStream();
  6599. };
  6600. class RedirectedStdOut {
  6601. ReusableStringStream m_rss;
  6602. RedirectedStream m_cout;
  6603. public:
  6604. RedirectedStdOut();
  6605. auto str() const -> std::string;
  6606. };
  6607. // StdErr has two constituent streams in C++, std::cerr and std::clog
  6608. // This means that we need to redirect 2 streams into 1 to keep proper
  6609. // order of writes
  6610. class RedirectedStdErr {
  6611. ReusableStringStream m_rss;
  6612. RedirectedStream m_cerr;
  6613. RedirectedStream m_clog;
  6614. public:
  6615. RedirectedStdErr();
  6616. auto str() const -> std::string;
  6617. };
  6618. // Windows's implementation of std::tmpfile is terrible (it tries
  6619. // to create a file inside system folder, thus requiring elevated
  6620. // privileges for the binary), so we have to use tmpnam(_s) and
  6621. // create the file ourselves there.
  6622. class TempFile {
  6623. public:
  6624. TempFile(TempFile const&) = delete;
  6625. TempFile& operator=(TempFile const&) = delete;
  6626. TempFile(TempFile&&) = delete;
  6627. TempFile& operator=(TempFile&&) = delete;
  6628. TempFile();
  6629. ~TempFile();
  6630. std::FILE* getFile();
  6631. std::string getContents();
  6632. private:
  6633. std::FILE* m_file = nullptr;
  6634. #if defined(_MSC_VER)
  6635. char m_buffer[L_tmpnam] = { 0 };
  6636. #endif
  6637. };
  6638. class OutputRedirect {
  6639. public:
  6640. OutputRedirect(OutputRedirect const&) = delete;
  6641. OutputRedirect& operator=(OutputRedirect const&) = delete;
  6642. OutputRedirect(OutputRedirect&&) = delete;
  6643. OutputRedirect& operator=(OutputRedirect&&) = delete;
  6644. OutputRedirect(std::string& stdout_dest, std::string& stderr_dest);
  6645. ~OutputRedirect();
  6646. private:
  6647. int m_originalStdout = -1;
  6648. int m_originalStderr = -1;
  6649. TempFile m_stdoutFile;
  6650. TempFile m_stderrFile;
  6651. std::string& m_stdoutDest;
  6652. std::string& m_stderrDest;
  6653. };
  6654. } // end namespace Catch
  6655. #endif // TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  6656. // end catch_output_redirect.h
  6657. #include <cstdio>
  6658. #include <cstring>
  6659. #include <fstream>
  6660. #include <sstream>
  6661. #include <stdexcept>
  6662. #if defined(_MSC_VER)
  6663. #include <io.h> //_dup and _dup2
  6664. #define dup _dup
  6665. #define dup2 _dup2
  6666. #define fileno _fileno
  6667. #else
  6668. #include <unistd.h> // dup and dup2
  6669. #endif
  6670. namespace Catch {
  6671. RedirectedStream::RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream )
  6672. : m_originalStream( originalStream ),
  6673. m_redirectionStream( redirectionStream ),
  6674. m_prevBuf( m_originalStream.rdbuf() )
  6675. {
  6676. m_originalStream.rdbuf( m_redirectionStream.rdbuf() );
  6677. }
  6678. RedirectedStream::~RedirectedStream() {
  6679. m_originalStream.rdbuf( m_prevBuf );
  6680. }
  6681. RedirectedStdOut::RedirectedStdOut() : m_cout( Catch::cout(), m_rss.get() ) {}
  6682. auto RedirectedStdOut::str() const -> std::string { return m_rss.str(); }
  6683. RedirectedStdErr::RedirectedStdErr()
  6684. : m_cerr( Catch::cerr(), m_rss.get() ),
  6685. m_clog( Catch::clog(), m_rss.get() )
  6686. {}
  6687. auto RedirectedStdErr::str() const -> std::string { return m_rss.str(); }
  6688. #if defined(_MSC_VER)
  6689. TempFile::TempFile() {
  6690. if (tmpnam_s(m_buffer)) {
  6691. throw std::runtime_error("Could not get a temp filename");
  6692. }
  6693. if (fopen_s(&m_file, m_buffer, "w")) {
  6694. char buffer[100];
  6695. if (strerror_s(buffer, errno)) {
  6696. throw std::runtime_error("Could not translate errno to string");
  6697. }
  6698. throw std::runtime_error("Could not open the temp file: " + std::string(m_buffer) + buffer);
  6699. }
  6700. }
  6701. #else
  6702. TempFile::TempFile() {
  6703. m_file = std::tmpfile();
  6704. if (!m_file) {
  6705. throw std::runtime_error("Could not create a temp file.");
  6706. }
  6707. }
  6708. #endif
  6709. TempFile::~TempFile() {
  6710. // TBD: What to do about errors here?
  6711. std::fclose(m_file);
  6712. // We manually create the file on Windows only, on Linux
  6713. // it will be autodeleted
  6714. #if defined(_MSC_VER)
  6715. std::remove(m_buffer);
  6716. #endif
  6717. }
  6718. FILE* TempFile::getFile() {
  6719. return m_file;
  6720. }
  6721. std::string TempFile::getContents() {
  6722. std::stringstream sstr;
  6723. char buffer[100] = {};
  6724. std::rewind(m_file);
  6725. while (std::fgets(buffer, sizeof(buffer), m_file)) {
  6726. sstr << buffer;
  6727. }
  6728. return sstr.str();
  6729. }
  6730. OutputRedirect::OutputRedirect(std::string& stdout_dest, std::string& stderr_dest) :
  6731. m_originalStdout(dup(1)),
  6732. m_originalStderr(dup(2)),
  6733. m_stdoutDest(stdout_dest),
  6734. m_stderrDest(stderr_dest) {
  6735. dup2(fileno(m_stdoutFile.getFile()), 1);
  6736. dup2(fileno(m_stderrFile.getFile()), 2);
  6737. }
  6738. OutputRedirect::~OutputRedirect() {
  6739. Catch::cout() << std::flush;
  6740. fflush(stdout);
  6741. // Since we support overriding these streams, we flush cerr
  6742. // even though std::cerr is unbuffered
  6743. Catch::cerr() << std::flush;
  6744. Catch::clog() << std::flush;
  6745. fflush(stderr);
  6746. dup2(m_originalStdout, 1);
  6747. dup2(m_originalStderr, 2);
  6748. m_stdoutDest += m_stdoutFile.getContents();
  6749. m_stderrDest += m_stderrFile.getContents();
  6750. }
  6751. } // namespace Catch
  6752. #if defined(_MSC_VER)
  6753. #undef dup
  6754. #undef dup2
  6755. #undef fileno
  6756. #endif
  6757. // end catch_output_redirect.cpp
  6758. // start catch_random_number_generator.cpp
  6759. // start catch_random_number_generator.h
  6760. #include <algorithm>
  6761. namespace Catch {
  6762. struct IConfig;
  6763. void seedRng( IConfig const& config );
  6764. unsigned int rngSeed();
  6765. struct RandomNumberGenerator {
  6766. using result_type = unsigned int;
  6767. static constexpr result_type (min)() { return 0; }
  6768. static constexpr result_type (max)() { return 1000000; }
  6769. result_type operator()( result_type n ) const;
  6770. result_type operator()() const;
  6771. template<typename V>
  6772. static void shuffle( V& vector ) {
  6773. RandomNumberGenerator rng;
  6774. std::shuffle( vector.begin(), vector.end(), rng );
  6775. }
  6776. };
  6777. }
  6778. // end catch_random_number_generator.h
  6779. #include <cstdlib>
  6780. namespace Catch {
  6781. void seedRng( IConfig const& config ) {
  6782. if( config.rngSeed() != 0 )
  6783. std::srand( config.rngSeed() );
  6784. }
  6785. unsigned int rngSeed() {
  6786. return getCurrentContext().getConfig()->rngSeed();
  6787. }
  6788. RandomNumberGenerator::result_type RandomNumberGenerator::operator()( result_type n ) const {
  6789. return std::rand() % n;
  6790. }
  6791. RandomNumberGenerator::result_type RandomNumberGenerator::operator()() const {
  6792. return std::rand() % (max)();
  6793. }
  6794. }
  6795. // end catch_random_number_generator.cpp
  6796. // start catch_registry_hub.cpp
  6797. // start catch_test_case_registry_impl.h
  6798. #include <vector>
  6799. #include <set>
  6800. #include <algorithm>
  6801. #include <ios>
  6802. namespace Catch {
  6803. class TestCase;
  6804. struct IConfig;
  6805. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases );
  6806. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
  6807. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions );
  6808. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
  6809. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
  6810. class TestRegistry : public ITestCaseRegistry {
  6811. public:
  6812. virtual ~TestRegistry() = default;
  6813. virtual void registerTest( TestCase const& testCase );
  6814. std::vector<TestCase> const& getAllTests() const override;
  6815. std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const override;
  6816. private:
  6817. std::vector<TestCase> m_functions;
  6818. mutable RunTests::InWhatOrder m_currentSortOrder = RunTests::InDeclarationOrder;
  6819. mutable std::vector<TestCase> m_sortedFunctions;
  6820. std::size_t m_unnamedCount = 0;
  6821. std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised
  6822. };
  6823. ///////////////////////////////////////////////////////////////////////////
  6824. class TestInvokerAsFunction : public ITestInvoker {
  6825. void(*m_testAsFunction)();
  6826. public:
  6827. TestInvokerAsFunction( void(*testAsFunction)() ) noexcept;
  6828. void invoke() const override;
  6829. };
  6830. std::string extractClassName( StringRef const& classOrQualifiedMethodName );
  6831. ///////////////////////////////////////////////////////////////////////////
  6832. } // end namespace Catch
  6833. // end catch_test_case_registry_impl.h
  6834. // start catch_reporter_registry.h
  6835. #include <map>
  6836. namespace Catch {
  6837. class ReporterRegistry : public IReporterRegistry {
  6838. public:
  6839. ~ReporterRegistry() override;
  6840. IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const override;
  6841. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory );
  6842. void registerListener( IReporterFactoryPtr const& factory );
  6843. FactoryMap const& getFactories() const override;
  6844. Listeners const& getListeners() const override;
  6845. private:
  6846. FactoryMap m_factories;
  6847. Listeners m_listeners;
  6848. };
  6849. }
  6850. // end catch_reporter_registry.h
  6851. // start catch_tag_alias_registry.h
  6852. // start catch_tag_alias.h
  6853. #include <string>
  6854. namespace Catch {
  6855. struct TagAlias {
  6856. TagAlias(std::string const& _tag, SourceLineInfo _lineInfo);
  6857. std::string tag;
  6858. SourceLineInfo lineInfo;
  6859. };
  6860. } // end namespace Catch
  6861. // end catch_tag_alias.h
  6862. #include <map>
  6863. namespace Catch {
  6864. class TagAliasRegistry : public ITagAliasRegistry {
  6865. public:
  6866. ~TagAliasRegistry() override;
  6867. TagAlias const* find( std::string const& alias ) const override;
  6868. std::string expandAliases( std::string const& unexpandedTestSpec ) const override;
  6869. void add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo );
  6870. private:
  6871. std::map<std::string, TagAlias> m_registry;
  6872. };
  6873. } // end namespace Catch
  6874. // end catch_tag_alias_registry.h
  6875. // start catch_startup_exception_registry.h
  6876. #include <vector>
  6877. #include <exception>
  6878. namespace Catch {
  6879. class StartupExceptionRegistry {
  6880. public:
  6881. void add(std::exception_ptr const& exception) noexcept;
  6882. std::vector<std::exception_ptr> const& getExceptions() const noexcept;
  6883. private:
  6884. std::vector<std::exception_ptr> m_exceptions;
  6885. };
  6886. } // end namespace Catch
  6887. // end catch_startup_exception_registry.h
  6888. namespace Catch {
  6889. namespace {
  6890. class RegistryHub : public IRegistryHub, public IMutableRegistryHub,
  6891. private NonCopyable {
  6892. public: // IRegistryHub
  6893. RegistryHub() = default;
  6894. IReporterRegistry const& getReporterRegistry() const override {
  6895. return m_reporterRegistry;
  6896. }
  6897. ITestCaseRegistry const& getTestCaseRegistry() const override {
  6898. return m_testCaseRegistry;
  6899. }
  6900. IExceptionTranslatorRegistry& getExceptionTranslatorRegistry() override {
  6901. return m_exceptionTranslatorRegistry;
  6902. }
  6903. ITagAliasRegistry const& getTagAliasRegistry() const override {
  6904. return m_tagAliasRegistry;
  6905. }
  6906. StartupExceptionRegistry const& getStartupExceptionRegistry() const override {
  6907. return m_exceptionRegistry;
  6908. }
  6909. public: // IMutableRegistryHub
  6910. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) override {
  6911. m_reporterRegistry.registerReporter( name, factory );
  6912. }
  6913. void registerListener( IReporterFactoryPtr const& factory ) override {
  6914. m_reporterRegistry.registerListener( factory );
  6915. }
  6916. void registerTest( TestCase const& testInfo ) override {
  6917. m_testCaseRegistry.registerTest( testInfo );
  6918. }
  6919. void registerTranslator( const IExceptionTranslator* translator ) override {
  6920. m_exceptionTranslatorRegistry.registerTranslator( translator );
  6921. }
  6922. void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) override {
  6923. m_tagAliasRegistry.add( alias, tag, lineInfo );
  6924. }
  6925. void registerStartupException() noexcept override {
  6926. m_exceptionRegistry.add(std::current_exception());
  6927. }
  6928. private:
  6929. TestRegistry m_testCaseRegistry;
  6930. ReporterRegistry m_reporterRegistry;
  6931. ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
  6932. TagAliasRegistry m_tagAliasRegistry;
  6933. StartupExceptionRegistry m_exceptionRegistry;
  6934. };
  6935. // Single, global, instance
  6936. RegistryHub*& getTheRegistryHub() {
  6937. static RegistryHub* theRegistryHub = nullptr;
  6938. if( !theRegistryHub )
  6939. theRegistryHub = new RegistryHub();
  6940. return theRegistryHub;
  6941. }
  6942. }
  6943. IRegistryHub& getRegistryHub() {
  6944. return *getTheRegistryHub();
  6945. }
  6946. IMutableRegistryHub& getMutableRegistryHub() {
  6947. return *getTheRegistryHub();
  6948. }
  6949. void cleanUp() {
  6950. delete getTheRegistryHub();
  6951. getTheRegistryHub() = nullptr;
  6952. cleanUpContext();
  6953. ReusableStringStream::cleanup();
  6954. }
  6955. std::string translateActiveException() {
  6956. return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException();
  6957. }
  6958. } // end namespace Catch
  6959. // end catch_registry_hub.cpp
  6960. // start catch_reporter_registry.cpp
  6961. namespace Catch {
  6962. ReporterRegistry::~ReporterRegistry() = default;
  6963. IStreamingReporterPtr ReporterRegistry::create( std::string const& name, IConfigPtr const& config ) const {
  6964. auto it = m_factories.find( name );
  6965. if( it == m_factories.end() )
  6966. return nullptr;
  6967. return it->second->create( ReporterConfig( config ) );
  6968. }
  6969. void ReporterRegistry::registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) {
  6970. m_factories.emplace(name, factory);
  6971. }
  6972. void ReporterRegistry::registerListener( IReporterFactoryPtr const& factory ) {
  6973. m_listeners.push_back( factory );
  6974. }
  6975. IReporterRegistry::FactoryMap const& ReporterRegistry::getFactories() const {
  6976. return m_factories;
  6977. }
  6978. IReporterRegistry::Listeners const& ReporterRegistry::getListeners() const {
  6979. return m_listeners;
  6980. }
  6981. }
  6982. // end catch_reporter_registry.cpp
  6983. // start catch_result_type.cpp
  6984. namespace Catch {
  6985. bool isOk( ResultWas::OfType resultType ) {
  6986. return ( resultType & ResultWas::FailureBit ) == 0;
  6987. }
  6988. bool isJustInfo( int flags ) {
  6989. return flags == ResultWas::Info;
  6990. }
  6991. ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) {
  6992. return static_cast<ResultDisposition::Flags>( static_cast<int>( lhs ) | static_cast<int>( rhs ) );
  6993. }
  6994. bool shouldContinueOnFailure( int flags ) { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; }
  6995. bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; }
  6996. } // end namespace Catch
  6997. // end catch_result_type.cpp
  6998. // start catch_run_context.cpp
  6999. #include <cassert>
  7000. #include <algorithm>
  7001. #include <sstream>
  7002. namespace Catch {
  7003. RunContext::RunContext(IConfigPtr const& _config, IStreamingReporterPtr&& reporter)
  7004. : m_runInfo(_config->name()),
  7005. m_context(getCurrentMutableContext()),
  7006. m_config(_config),
  7007. m_reporter(std::move(reporter)),
  7008. m_lastAssertionInfo{ StringRef(), SourceLineInfo("",0), StringRef(), ResultDisposition::Normal },
  7009. m_includeSuccessfulResults( m_config->includeSuccessfulResults() )
  7010. {
  7011. m_context.setRunner(this);
  7012. m_context.setConfig(m_config);
  7013. m_context.setResultCapture(this);
  7014. m_reporter->testRunStarting(m_runInfo);
  7015. }
  7016. RunContext::~RunContext() {
  7017. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting()));
  7018. }
  7019. void RunContext::testGroupStarting(std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount) {
  7020. m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount));
  7021. }
  7022. void RunContext::testGroupEnded(std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount) {
  7023. m_reporter->testGroupEnded(TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting()));
  7024. }
  7025. Totals RunContext::runTest(TestCase const& testCase) {
  7026. Totals prevTotals = m_totals;
  7027. std::string redirectedCout;
  7028. std::string redirectedCerr;
  7029. auto const& testInfo = testCase.getTestCaseInfo();
  7030. m_reporter->testCaseStarting(testInfo);
  7031. m_activeTestCase = &testCase;
  7032. ITracker& rootTracker = m_trackerContext.startRun();
  7033. assert(rootTracker.isSectionTracker());
  7034. static_cast<SectionTracker&>(rootTracker).addInitialFilters(m_config->getSectionsToRun());
  7035. do {
  7036. m_trackerContext.startCycle();
  7037. m_testCaseTracker = &SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo));
  7038. runCurrentTest(redirectedCout, redirectedCerr);
  7039. } while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting());
  7040. Totals deltaTotals = m_totals.delta(prevTotals);
  7041. if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) {
  7042. deltaTotals.assertions.failed++;
  7043. deltaTotals.testCases.passed--;
  7044. deltaTotals.testCases.failed++;
  7045. }
  7046. m_totals.testCases += deltaTotals.testCases;
  7047. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  7048. deltaTotals,
  7049. redirectedCout,
  7050. redirectedCerr,
  7051. aborting()));
  7052. m_activeTestCase = nullptr;
  7053. m_testCaseTracker = nullptr;
  7054. return deltaTotals;
  7055. }
  7056. IConfigPtr RunContext::config() const {
  7057. return m_config;
  7058. }
  7059. IStreamingReporter& RunContext::reporter() const {
  7060. return *m_reporter;
  7061. }
  7062. void RunContext::assertionEnded(AssertionResult const & result) {
  7063. if (result.getResultType() == ResultWas::Ok) {
  7064. m_totals.assertions.passed++;
  7065. m_lastAssertionPassed = true;
  7066. } else if (!result.isOk()) {
  7067. m_lastAssertionPassed = false;
  7068. if( m_activeTestCase->getTestCaseInfo().okToFail() )
  7069. m_totals.assertions.failedButOk++;
  7070. else
  7071. m_totals.assertions.failed++;
  7072. }
  7073. else {
  7074. m_lastAssertionPassed = true;
  7075. }
  7076. // We have no use for the return value (whether messages should be cleared), because messages were made scoped
  7077. // and should be let to clear themselves out.
  7078. static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals)));
  7079. // Reset working state
  7080. resetAssertionInfo();
  7081. m_lastResult = result;
  7082. }
  7083. void RunContext::resetAssertionInfo() {
  7084. m_lastAssertionInfo.macroName = StringRef();
  7085. m_lastAssertionInfo.capturedExpression = "{Unknown expression after the reported line}"_sr;
  7086. }
  7087. bool RunContext::sectionStarted(SectionInfo const & sectionInfo, Counts & assertions) {
  7088. ITracker& sectionTracker = SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(sectionInfo.name, sectionInfo.lineInfo));
  7089. if (!sectionTracker.isOpen())
  7090. return false;
  7091. m_activeSections.push_back(&sectionTracker);
  7092. m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;
  7093. m_reporter->sectionStarting(sectionInfo);
  7094. assertions = m_totals.assertions;
  7095. return true;
  7096. }
  7097. bool RunContext::testForMissingAssertions(Counts& assertions) {
  7098. if (assertions.total() != 0)
  7099. return false;
  7100. if (!m_config->warnAboutMissingAssertions())
  7101. return false;
  7102. if (m_trackerContext.currentTracker().hasChildren())
  7103. return false;
  7104. m_totals.assertions.failed++;
  7105. assertions.failed++;
  7106. return true;
  7107. }
  7108. void RunContext::sectionEnded(SectionEndInfo const & endInfo) {
  7109. Counts assertions = m_totals.assertions - endInfo.prevAssertions;
  7110. bool missingAssertions = testForMissingAssertions(assertions);
  7111. if (!m_activeSections.empty()) {
  7112. m_activeSections.back()->close();
  7113. m_activeSections.pop_back();
  7114. }
  7115. m_reporter->sectionEnded(SectionStats(endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions));
  7116. m_messages.clear();
  7117. }
  7118. void RunContext::sectionEndedEarly(SectionEndInfo const & endInfo) {
  7119. if (m_unfinishedSections.empty())
  7120. m_activeSections.back()->fail();
  7121. else
  7122. m_activeSections.back()->close();
  7123. m_activeSections.pop_back();
  7124. m_unfinishedSections.push_back(endInfo);
  7125. }
  7126. void RunContext::benchmarkStarting( BenchmarkInfo const& info ) {
  7127. m_reporter->benchmarkStarting( info );
  7128. }
  7129. void RunContext::benchmarkEnded( BenchmarkStats const& stats ) {
  7130. m_reporter->benchmarkEnded( stats );
  7131. }
  7132. void RunContext::pushScopedMessage(MessageInfo const & message) {
  7133. m_messages.push_back(message);
  7134. }
  7135. void RunContext::popScopedMessage(MessageInfo const & message) {
  7136. m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end());
  7137. }
  7138. std::string RunContext::getCurrentTestName() const {
  7139. return m_activeTestCase
  7140. ? m_activeTestCase->getTestCaseInfo().name
  7141. : std::string();
  7142. }
  7143. const AssertionResult * RunContext::getLastResult() const {
  7144. return &(*m_lastResult);
  7145. }
  7146. void RunContext::exceptionEarlyReported() {
  7147. m_shouldReportUnexpected = false;
  7148. }
  7149. void RunContext::handleFatalErrorCondition( StringRef message ) {
  7150. // First notify reporter that bad things happened
  7151. m_reporter->fatalErrorEncountered(message);
  7152. // Don't rebuild the result -- the stringification itself can cause more fatal errors
  7153. // Instead, fake a result data.
  7154. AssertionResultData tempResult( ResultWas::FatalErrorCondition, { false } );
  7155. tempResult.message = message;
  7156. AssertionResult result(m_lastAssertionInfo, tempResult);
  7157. assertionEnded(result);
  7158. handleUnfinishedSections();
  7159. // Recreate section for test case (as we will lose the one that was in scope)
  7160. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  7161. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name, testCaseInfo.description);
  7162. Counts assertions;
  7163. assertions.failed = 1;
  7164. SectionStats testCaseSectionStats(testCaseSection, assertions, 0, false);
  7165. m_reporter->sectionEnded(testCaseSectionStats);
  7166. auto const& testInfo = m_activeTestCase->getTestCaseInfo();
  7167. Totals deltaTotals;
  7168. deltaTotals.testCases.failed = 1;
  7169. deltaTotals.assertions.failed = 1;
  7170. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  7171. deltaTotals,
  7172. std::string(),
  7173. std::string(),
  7174. false));
  7175. m_totals.testCases.failed++;
  7176. testGroupEnded(std::string(), m_totals, 1, 1);
  7177. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, false));
  7178. }
  7179. bool RunContext::lastAssertionPassed() {
  7180. return m_lastAssertionPassed;
  7181. }
  7182. void RunContext::assertionPassed() {
  7183. m_lastAssertionPassed = true;
  7184. ++m_totals.assertions.passed;
  7185. resetAssertionInfo();
  7186. }
  7187. bool RunContext::aborting() const {
  7188. return m_totals.assertions.failed == static_cast<std::size_t>(m_config->abortAfter());
  7189. }
  7190. void RunContext::runCurrentTest(std::string & redirectedCout, std::string & redirectedCerr) {
  7191. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  7192. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name, testCaseInfo.description);
  7193. m_reporter->sectionStarting(testCaseSection);
  7194. Counts prevAssertions = m_totals.assertions;
  7195. double duration = 0;
  7196. m_shouldReportUnexpected = true;
  7197. m_lastAssertionInfo = { "TEST_CASE"_sr, testCaseInfo.lineInfo, StringRef(), ResultDisposition::Normal };
  7198. seedRng(*m_config);
  7199. Timer timer;
  7200. try {
  7201. if (m_reporter->getPreferences().shouldRedirectStdOut) {
  7202. #if !defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
  7203. RedirectedStdOut redirectedStdOut;
  7204. RedirectedStdErr redirectedStdErr;
  7205. timer.start();
  7206. invokeActiveTestCase();
  7207. redirectedCout += redirectedStdOut.str();
  7208. redirectedCerr += redirectedStdErr.str();
  7209. #else
  7210. OutputRedirect r(redirectedCout, redirectedCerr);
  7211. timer.start();
  7212. invokeActiveTestCase();
  7213. #endif
  7214. } else {
  7215. timer.start();
  7216. invokeActiveTestCase();
  7217. }
  7218. duration = timer.getElapsedSeconds();
  7219. } catch (TestFailureException&) {
  7220. // This just means the test was aborted due to failure
  7221. } catch (...) {
  7222. // Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under REQUIRE assertions
  7223. // are reported without translation at the point of origin.
  7224. if( m_shouldReportUnexpected ) {
  7225. AssertionReaction dummyReaction;
  7226. handleUnexpectedInflightException( m_lastAssertionInfo, translateActiveException(), dummyReaction );
  7227. }
  7228. }
  7229. Counts assertions = m_totals.assertions - prevAssertions;
  7230. bool missingAssertions = testForMissingAssertions(assertions);
  7231. m_testCaseTracker->close();
  7232. handleUnfinishedSections();
  7233. m_messages.clear();
  7234. SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions);
  7235. m_reporter->sectionEnded(testCaseSectionStats);
  7236. }
  7237. void RunContext::invokeActiveTestCase() {
  7238. FatalConditionHandler fatalConditionHandler; // Handle signals
  7239. m_activeTestCase->invoke();
  7240. fatalConditionHandler.reset();
  7241. }
  7242. void RunContext::handleUnfinishedSections() {
  7243. // If sections ended prematurely due to an exception we stored their
  7244. // infos here so we can tear them down outside the unwind process.
  7245. for (auto it = m_unfinishedSections.rbegin(),
  7246. itEnd = m_unfinishedSections.rend();
  7247. it != itEnd;
  7248. ++it)
  7249. sectionEnded(*it);
  7250. m_unfinishedSections.clear();
  7251. }
  7252. void RunContext::handleExpr(
  7253. AssertionInfo const& info,
  7254. ITransientExpression const& expr,
  7255. AssertionReaction& reaction
  7256. ) {
  7257. m_reporter->assertionStarting( info );
  7258. bool negated = isFalseTest( info.resultDisposition );
  7259. bool result = expr.getResult() != negated;
  7260. if( result ) {
  7261. if (!m_includeSuccessfulResults) {
  7262. assertionPassed();
  7263. }
  7264. else {
  7265. reportExpr(info, ResultWas::Ok, &expr, negated);
  7266. }
  7267. }
  7268. else {
  7269. reportExpr(info, ResultWas::ExpressionFailed, &expr, negated );
  7270. populateReaction( reaction );
  7271. }
  7272. }
  7273. void RunContext::reportExpr(
  7274. AssertionInfo const &info,
  7275. ResultWas::OfType resultType,
  7276. ITransientExpression const *expr,
  7277. bool negated ) {
  7278. m_lastAssertionInfo = info;
  7279. AssertionResultData data( resultType, LazyExpression( negated ) );
  7280. AssertionResult assertionResult{ info, data };
  7281. assertionResult.m_resultData.lazyExpression.m_transientExpression = expr;
  7282. assertionEnded( assertionResult );
  7283. }
  7284. void RunContext::handleMessage(
  7285. AssertionInfo const& info,
  7286. ResultWas::OfType resultType,
  7287. StringRef const& message,
  7288. AssertionReaction& reaction
  7289. ) {
  7290. m_reporter->assertionStarting( info );
  7291. m_lastAssertionInfo = info;
  7292. AssertionResultData data( resultType, LazyExpression( false ) );
  7293. data.message = message;
  7294. AssertionResult assertionResult{ m_lastAssertionInfo, data };
  7295. assertionEnded( assertionResult );
  7296. if( !assertionResult.isOk() )
  7297. populateReaction( reaction );
  7298. }
  7299. void RunContext::handleUnexpectedExceptionNotThrown(
  7300. AssertionInfo const& info,
  7301. AssertionReaction& reaction
  7302. ) {
  7303. handleNonExpr(info, Catch::ResultWas::DidntThrowException, reaction);
  7304. }
  7305. void RunContext::handleUnexpectedInflightException(
  7306. AssertionInfo const& info,
  7307. std::string const& message,
  7308. AssertionReaction& reaction
  7309. ) {
  7310. m_lastAssertionInfo = info;
  7311. AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
  7312. data.message = message;
  7313. AssertionResult assertionResult{ info, data };
  7314. assertionEnded( assertionResult );
  7315. populateReaction( reaction );
  7316. }
  7317. void RunContext::populateReaction( AssertionReaction& reaction ) {
  7318. reaction.shouldDebugBreak = m_config->shouldDebugBreak();
  7319. reaction.shouldThrow = aborting() || (m_lastAssertionInfo.resultDisposition & ResultDisposition::Normal);
  7320. }
  7321. void RunContext::handleIncomplete(
  7322. AssertionInfo const& info
  7323. ) {
  7324. m_lastAssertionInfo = info;
  7325. AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
  7326. data.message = "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE";
  7327. AssertionResult assertionResult{ info, data };
  7328. assertionEnded( assertionResult );
  7329. }
  7330. void RunContext::handleNonExpr(
  7331. AssertionInfo const &info,
  7332. ResultWas::OfType resultType,
  7333. AssertionReaction &reaction
  7334. ) {
  7335. m_lastAssertionInfo = info;
  7336. AssertionResultData data( resultType, LazyExpression( false ) );
  7337. AssertionResult assertionResult{ info, data };
  7338. assertionEnded( assertionResult );
  7339. if( !assertionResult.isOk() )
  7340. populateReaction( reaction );
  7341. }
  7342. IResultCapture& getResultCapture() {
  7343. if (auto* capture = getCurrentContext().getResultCapture())
  7344. return *capture;
  7345. else
  7346. CATCH_INTERNAL_ERROR("No result capture instance");
  7347. }
  7348. }
  7349. // end catch_run_context.cpp
  7350. // start catch_section.cpp
  7351. namespace Catch {
  7352. Section::Section( SectionInfo const& info )
  7353. : m_info( info ),
  7354. m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) )
  7355. {
  7356. m_timer.start();
  7357. }
  7358. Section::~Section() {
  7359. if( m_sectionIncluded ) {
  7360. SectionEndInfo endInfo( m_info, m_assertions, m_timer.getElapsedSeconds() );
  7361. if( uncaught_exceptions() )
  7362. getResultCapture().sectionEndedEarly( endInfo );
  7363. else
  7364. getResultCapture().sectionEnded( endInfo );
  7365. }
  7366. }
  7367. // This indicates whether the section should be executed or not
  7368. Section::operator bool() const {
  7369. return m_sectionIncluded;
  7370. }
  7371. } // end namespace Catch
  7372. // end catch_section.cpp
  7373. // start catch_section_info.cpp
  7374. namespace Catch {
  7375. SectionInfo::SectionInfo
  7376. ( SourceLineInfo const& _lineInfo,
  7377. std::string const& _name,
  7378. std::string const& _description )
  7379. : name( _name ),
  7380. description( _description ),
  7381. lineInfo( _lineInfo )
  7382. {}
  7383. SectionEndInfo::SectionEndInfo( SectionInfo const& _sectionInfo, Counts const& _prevAssertions, double _durationInSeconds )
  7384. : sectionInfo( _sectionInfo ), prevAssertions( _prevAssertions ), durationInSeconds( _durationInSeconds )
  7385. {}
  7386. } // end namespace Catch
  7387. // end catch_section_info.cpp
  7388. // start catch_session.cpp
  7389. // start catch_session.h
  7390. #include <memory>
  7391. namespace Catch {
  7392. class Session : NonCopyable {
  7393. public:
  7394. Session();
  7395. ~Session() override;
  7396. void showHelp() const;
  7397. void libIdentify();
  7398. int applyCommandLine( int argc, char const * const * argv );
  7399. void useConfigData( ConfigData const& configData );
  7400. int run( int argc, char* argv[] );
  7401. #if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(UNICODE)
  7402. int run( int argc, wchar_t* const argv[] );
  7403. #endif
  7404. int run();
  7405. clara::Parser const& cli() const;
  7406. void cli( clara::Parser const& newParser );
  7407. ConfigData& configData();
  7408. Config& config();
  7409. private:
  7410. int runInternal();
  7411. clara::Parser m_cli;
  7412. ConfigData m_configData;
  7413. std::shared_ptr<Config> m_config;
  7414. bool m_startupExceptions = false;
  7415. };
  7416. } // end namespace Catch
  7417. // end catch_session.h
  7418. // start catch_version.h
  7419. #include <iosfwd>
  7420. namespace Catch {
  7421. // Versioning information
  7422. struct Version {
  7423. Version( Version const& ) = delete;
  7424. Version& operator=( Version const& ) = delete;
  7425. Version( unsigned int _majorVersion,
  7426. unsigned int _minorVersion,
  7427. unsigned int _patchNumber,
  7428. char const * const _branchName,
  7429. unsigned int _buildNumber );
  7430. unsigned int const majorVersion;
  7431. unsigned int const minorVersion;
  7432. unsigned int const patchNumber;
  7433. // buildNumber is only used if branchName is not null
  7434. char const * const branchName;
  7435. unsigned int const buildNumber;
  7436. friend std::ostream& operator << ( std::ostream& os, Version const& version );
  7437. };
  7438. Version const& libraryVersion();
  7439. }
  7440. // end catch_version.h
  7441. #include <cstdlib>
  7442. #include <iomanip>
  7443. namespace Catch {
  7444. namespace {
  7445. const int MaxExitCode = 255;
  7446. IStreamingReporterPtr createReporter(std::string const& reporterName, IConfigPtr const& config) {
  7447. auto reporter = Catch::getRegistryHub().getReporterRegistry().create(reporterName, config);
  7448. CATCH_ENFORCE(reporter, "No reporter registered with name: '" << reporterName << "'");
  7449. return reporter;
  7450. }
  7451. IStreamingReporterPtr makeReporter(std::shared_ptr<Config> const& config) {
  7452. if (Catch::getRegistryHub().getReporterRegistry().getListeners().empty()) {
  7453. return createReporter(config->getReporterName(), config);
  7454. }
  7455. auto multi = std::unique_ptr<ListeningReporter>(new ListeningReporter);
  7456. auto const& listeners = Catch::getRegistryHub().getReporterRegistry().getListeners();
  7457. for (auto const& listener : listeners) {
  7458. multi->addListener(listener->create(Catch::ReporterConfig(config)));
  7459. }
  7460. multi->addReporter(createReporter(config->getReporterName(), config));
  7461. return std::move(multi);
  7462. }
  7463. Catch::Totals runTests(std::shared_ptr<Config> const& config) {
  7464. // FixMe: Add listeners in order first, then add reporters.
  7465. auto reporter = makeReporter(config);
  7466. RunContext context(config, std::move(reporter));
  7467. Totals totals;
  7468. context.testGroupStarting(config->name(), 1, 1);
  7469. TestSpec testSpec = config->testSpec();
  7470. auto const& allTestCases = getAllTestCasesSorted(*config);
  7471. for (auto const& testCase : allTestCases) {
  7472. if (!context.aborting() && matchTest(testCase, testSpec, *config))
  7473. totals += context.runTest(testCase);
  7474. else
  7475. context.reporter().skipTest(testCase);
  7476. }
  7477. if (config->warnAboutNoTests() && totals.testCases.total() == 0) {
  7478. ReusableStringStream testConfig;
  7479. bool first = true;
  7480. for (const auto& input : config->getTestsOrTags()) {
  7481. if (!first) { testConfig << ' '; }
  7482. first = false;
  7483. testConfig << input;
  7484. }
  7485. context.reporter().noMatchingTestCases(testConfig.str());
  7486. totals.error = -1;
  7487. }
  7488. context.testGroupEnded(config->name(), totals, 1, 1);
  7489. return totals;
  7490. }
  7491. void applyFilenamesAsTags(Catch::IConfig const& config) {
  7492. auto& tests = const_cast<std::vector<TestCase>&>(getAllTestCasesSorted(config));
  7493. for (auto& testCase : tests) {
  7494. auto tags = testCase.tags;
  7495. std::string filename = testCase.lineInfo.file;
  7496. auto lastSlash = filename.find_last_of("\\/");
  7497. if (lastSlash != std::string::npos) {
  7498. filename.erase(0, lastSlash);
  7499. filename[0] = '#';
  7500. }
  7501. auto lastDot = filename.find_last_of('.');
  7502. if (lastDot != std::string::npos) {
  7503. filename.erase(lastDot);
  7504. }
  7505. tags.push_back(std::move(filename));
  7506. setTags(testCase, tags);
  7507. }
  7508. }
  7509. } // anon namespace
  7510. Session::Session() {
  7511. static bool alreadyInstantiated = false;
  7512. if( alreadyInstantiated ) {
  7513. try { CATCH_INTERNAL_ERROR( "Only one instance of Catch::Session can ever be used" ); }
  7514. catch(...) { getMutableRegistryHub().registerStartupException(); }
  7515. }
  7516. const auto& exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions();
  7517. if ( !exceptions.empty() ) {
  7518. m_startupExceptions = true;
  7519. Colour colourGuard( Colour::Red );
  7520. Catch::cerr() << "Errors occurred during startup!" << '\n';
  7521. // iterate over all exceptions and notify user
  7522. for ( const auto& ex_ptr : exceptions ) {
  7523. try {
  7524. std::rethrow_exception(ex_ptr);
  7525. } catch ( std::exception const& ex ) {
  7526. Catch::cerr() << Column( ex.what() ).indent(2) << '\n';
  7527. }
  7528. }
  7529. }
  7530. alreadyInstantiated = true;
  7531. m_cli = makeCommandLineParser( m_configData );
  7532. }
  7533. Session::~Session() {
  7534. Catch::cleanUp();
  7535. }
  7536. void Session::showHelp() const {
  7537. Catch::cout()
  7538. << "\nCatch v" << libraryVersion() << "\n"
  7539. << m_cli << std::endl
  7540. << "For more detailed usage please see the project docs\n" << std::endl;
  7541. }
  7542. void Session::libIdentify() {
  7543. Catch::cout()
  7544. << std::left << std::setw(16) << "description: " << "A Catch test executable\n"
  7545. << std::left << std::setw(16) << "category: " << "testframework\n"
  7546. << std::left << std::setw(16) << "framework: " << "Catch Test\n"
  7547. << std::left << std::setw(16) << "version: " << libraryVersion() << std::endl;
  7548. }
  7549. int Session::applyCommandLine( int argc, char const * const * argv ) {
  7550. if( m_startupExceptions )
  7551. return 1;
  7552. auto result = m_cli.parse( clara::Args( argc, argv ) );
  7553. if( !result ) {
  7554. Catch::cerr()
  7555. << Colour( Colour::Red )
  7556. << "\nError(s) in input:\n"
  7557. << Column( result.errorMessage() ).indent( 2 )
  7558. << "\n\n";
  7559. Catch::cerr() << "Run with -? for usage\n" << std::endl;
  7560. return MaxExitCode;
  7561. }
  7562. if( m_configData.showHelp )
  7563. showHelp();
  7564. if( m_configData.libIdentify )
  7565. libIdentify();
  7566. m_config.reset();
  7567. return 0;
  7568. }
  7569. void Session::useConfigData( ConfigData const& configData ) {
  7570. m_configData = configData;
  7571. m_config.reset();
  7572. }
  7573. int Session::run( int argc, char* argv[] ) {
  7574. if( m_startupExceptions )
  7575. return 1;
  7576. int returnCode = applyCommandLine( argc, argv );
  7577. if( returnCode == 0 )
  7578. returnCode = run();
  7579. return returnCode;
  7580. }
  7581. #if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(UNICODE)
  7582. int Session::run( int argc, wchar_t* const argv[] ) {
  7583. char **utf8Argv = new char *[ argc ];
  7584. for ( int i = 0; i < argc; ++i ) {
  7585. int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, NULL, 0, NULL, NULL );
  7586. utf8Argv[ i ] = new char[ bufSize ];
  7587. WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, NULL, NULL );
  7588. }
  7589. int returnCode = run( argc, utf8Argv );
  7590. for ( int i = 0; i < argc; ++i )
  7591. delete [] utf8Argv[ i ];
  7592. delete [] utf8Argv;
  7593. return returnCode;
  7594. }
  7595. #endif
  7596. int Session::run() {
  7597. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeStart ) != 0 ) {
  7598. Catch::cout() << "...waiting for enter/ return before starting" << std::endl;
  7599. static_cast<void>(std::getchar());
  7600. }
  7601. int exitCode = runInternal();
  7602. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeExit ) != 0 ) {
  7603. Catch::cout() << "...waiting for enter/ return before exiting, with code: " << exitCode << std::endl;
  7604. static_cast<void>(std::getchar());
  7605. }
  7606. return exitCode;
  7607. }
  7608. clara::Parser const& Session::cli() const {
  7609. return m_cli;
  7610. }
  7611. void Session::cli( clara::Parser const& newParser ) {
  7612. m_cli = newParser;
  7613. }
  7614. ConfigData& Session::configData() {
  7615. return m_configData;
  7616. }
  7617. Config& Session::config() {
  7618. if( !m_config )
  7619. m_config = std::make_shared<Config>( m_configData );
  7620. return *m_config;
  7621. }
  7622. int Session::runInternal() {
  7623. if( m_startupExceptions )
  7624. return 1;
  7625. if( m_configData.showHelp || m_configData.libIdentify )
  7626. return 0;
  7627. try
  7628. {
  7629. config(); // Force config to be constructed
  7630. seedRng( *m_config );
  7631. if( m_configData.filenamesAsTags )
  7632. applyFilenamesAsTags( *m_config );
  7633. // Handle list request
  7634. if( Option<std::size_t> listed = list( config() ) )
  7635. return static_cast<int>( *listed );
  7636. auto totals = runTests( m_config );
  7637. // Note that on unices only the lower 8 bits are usually used, clamping
  7638. // the return value to 255 prevents false negative when some multiple
  7639. // of 256 tests has failed
  7640. return (std::min) (MaxExitCode, (std::max) (totals.error, static_cast<int>(totals.assertions.failed)));
  7641. }
  7642. catch( std::exception& ex ) {
  7643. Catch::cerr() << ex.what() << std::endl;
  7644. return MaxExitCode;
  7645. }
  7646. }
  7647. } // end namespace Catch
  7648. // end catch_session.cpp
  7649. // start catch_startup_exception_registry.cpp
  7650. namespace Catch {
  7651. void StartupExceptionRegistry::add( std::exception_ptr const& exception ) noexcept {
  7652. try {
  7653. m_exceptions.push_back(exception);
  7654. }
  7655. catch(...) {
  7656. // If we run out of memory during start-up there's really not a lot more we can do about it
  7657. std::terminate();
  7658. }
  7659. }
  7660. std::vector<std::exception_ptr> const& StartupExceptionRegistry::getExceptions() const noexcept {
  7661. return m_exceptions;
  7662. }
  7663. } // end namespace Catch
  7664. // end catch_startup_exception_registry.cpp
  7665. // start catch_stream.cpp
  7666. #include <cstdio>
  7667. #include <iostream>
  7668. #include <fstream>
  7669. #include <sstream>
  7670. #include <vector>
  7671. #include <memory>
  7672. #if defined(__clang__)
  7673. # pragma clang diagnostic push
  7674. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  7675. #endif
  7676. namespace Catch {
  7677. Catch::IStream::~IStream() = default;
  7678. namespace detail { namespace {
  7679. template<typename WriterF, std::size_t bufferSize=256>
  7680. class StreamBufImpl : public std::streambuf {
  7681. char data[bufferSize];
  7682. WriterF m_writer;
  7683. public:
  7684. StreamBufImpl() {
  7685. setp( data, data + sizeof(data) );
  7686. }
  7687. ~StreamBufImpl() noexcept {
  7688. StreamBufImpl::sync();
  7689. }
  7690. private:
  7691. int overflow( int c ) override {
  7692. sync();
  7693. if( c != EOF ) {
  7694. if( pbase() == epptr() )
  7695. m_writer( std::string( 1, static_cast<char>( c ) ) );
  7696. else
  7697. sputc( static_cast<char>( c ) );
  7698. }
  7699. return 0;
  7700. }
  7701. int sync() override {
  7702. if( pbase() != pptr() ) {
  7703. m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) );
  7704. setp( pbase(), epptr() );
  7705. }
  7706. return 0;
  7707. }
  7708. };
  7709. ///////////////////////////////////////////////////////////////////////////
  7710. struct OutputDebugWriter {
  7711. void operator()( std::string const&str ) {
  7712. writeToDebugConsole( str );
  7713. }
  7714. };
  7715. ///////////////////////////////////////////////////////////////////////////
  7716. class FileStream : public IStream {
  7717. mutable std::ofstream m_ofs;
  7718. public:
  7719. FileStream( StringRef filename ) {
  7720. m_ofs.open( filename.c_str() );
  7721. CATCH_ENFORCE( !m_ofs.fail(), "Unable to open file: '" << filename << "'" );
  7722. }
  7723. ~FileStream() override = default;
  7724. public: // IStream
  7725. std::ostream& stream() const override {
  7726. return m_ofs;
  7727. }
  7728. };
  7729. ///////////////////////////////////////////////////////////////////////////
  7730. class CoutStream : public IStream {
  7731. mutable std::ostream m_os;
  7732. public:
  7733. // Store the streambuf from cout up-front because
  7734. // cout may get redirected when running tests
  7735. CoutStream() : m_os( Catch::cout().rdbuf() ) {}
  7736. ~CoutStream() override = default;
  7737. public: // IStream
  7738. std::ostream& stream() const override { return m_os; }
  7739. };
  7740. ///////////////////////////////////////////////////////////////////////////
  7741. class DebugOutStream : public IStream {
  7742. std::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf;
  7743. mutable std::ostream m_os;
  7744. public:
  7745. DebugOutStream()
  7746. : m_streamBuf( new StreamBufImpl<OutputDebugWriter>() ),
  7747. m_os( m_streamBuf.get() )
  7748. {}
  7749. ~DebugOutStream() override = default;
  7750. public: // IStream
  7751. std::ostream& stream() const override { return m_os; }
  7752. };
  7753. }} // namespace anon::detail
  7754. ///////////////////////////////////////////////////////////////////////////
  7755. auto makeStream( StringRef const &filename ) -> IStream const* {
  7756. if( filename.empty() )
  7757. return new detail::CoutStream();
  7758. else if( filename[0] == '%' ) {
  7759. if( filename == "%debug" )
  7760. return new detail::DebugOutStream();
  7761. else
  7762. CATCH_ERROR( "Unrecognised stream: '" << filename << "'" );
  7763. }
  7764. else
  7765. return new detail::FileStream( filename );
  7766. }
  7767. // This class encapsulates the idea of a pool of ostringstreams that can be reused.
  7768. struct StringStreams {
  7769. std::vector<std::unique_ptr<std::ostringstream>> m_streams;
  7770. std::vector<std::size_t> m_unused;
  7771. std::ostringstream m_referenceStream; // Used for copy state/ flags from
  7772. static StringStreams* s_instance;
  7773. auto add() -> std::size_t {
  7774. if( m_unused.empty() ) {
  7775. m_streams.push_back( std::unique_ptr<std::ostringstream>( new std::ostringstream ) );
  7776. return m_streams.size()-1;
  7777. }
  7778. else {
  7779. auto index = m_unused.back();
  7780. m_unused.pop_back();
  7781. return index;
  7782. }
  7783. }
  7784. void release( std::size_t index ) {
  7785. m_streams[index]->copyfmt( m_referenceStream ); // Restore initial flags and other state
  7786. m_unused.push_back(index);
  7787. }
  7788. // !TBD: put in TLS
  7789. static auto instance() -> StringStreams& {
  7790. if( !s_instance )
  7791. s_instance = new StringStreams();
  7792. return *s_instance;
  7793. }
  7794. static void cleanup() {
  7795. delete s_instance;
  7796. s_instance = nullptr;
  7797. }
  7798. };
  7799. StringStreams* StringStreams::s_instance = nullptr;
  7800. void ReusableStringStream::cleanup() {
  7801. StringStreams::cleanup();
  7802. }
  7803. ReusableStringStream::ReusableStringStream()
  7804. : m_index( StringStreams::instance().add() ),
  7805. m_oss( StringStreams::instance().m_streams[m_index].get() )
  7806. {}
  7807. ReusableStringStream::~ReusableStringStream() {
  7808. static_cast<std::ostringstream*>( m_oss )->str("");
  7809. m_oss->clear();
  7810. StringStreams::instance().release( m_index );
  7811. }
  7812. auto ReusableStringStream::str() const -> std::string {
  7813. return static_cast<std::ostringstream*>( m_oss )->str();
  7814. }
  7815. ///////////////////////////////////////////////////////////////////////////
  7816. #ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions
  7817. std::ostream& cout() { return std::cout; }
  7818. std::ostream& cerr() { return std::cerr; }
  7819. std::ostream& clog() { return std::clog; }
  7820. #endif
  7821. }
  7822. #if defined(__clang__)
  7823. # pragma clang diagnostic pop
  7824. #endif
  7825. // end catch_stream.cpp
  7826. // start catch_string_manip.cpp
  7827. #include <algorithm>
  7828. #include <ostream>
  7829. #include <cstring>
  7830. #include <cctype>
  7831. namespace Catch {
  7832. bool startsWith( std::string const& s, std::string const& prefix ) {
  7833. return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
  7834. }
  7835. bool startsWith( std::string const& s, char prefix ) {
  7836. return !s.empty() && s[0] == prefix;
  7837. }
  7838. bool endsWith( std::string const& s, std::string const& suffix ) {
  7839. return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
  7840. }
  7841. bool endsWith( std::string const& s, char suffix ) {
  7842. return !s.empty() && s[s.size()-1] == suffix;
  7843. }
  7844. bool contains( std::string const& s, std::string const& infix ) {
  7845. return s.find( infix ) != std::string::npos;
  7846. }
  7847. char toLowerCh(char c) {
  7848. return static_cast<char>( std::tolower( c ) );
  7849. }
  7850. void toLowerInPlace( std::string& s ) {
  7851. std::transform( s.begin(), s.end(), s.begin(), toLowerCh );
  7852. }
  7853. std::string toLower( std::string const& s ) {
  7854. std::string lc = s;
  7855. toLowerInPlace( lc );
  7856. return lc;
  7857. }
  7858. std::string trim( std::string const& str ) {
  7859. static char const* whitespaceChars = "\n\r\t ";
  7860. std::string::size_type start = str.find_first_not_of( whitespaceChars );
  7861. std::string::size_type end = str.find_last_not_of( whitespaceChars );
  7862. return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string();
  7863. }
  7864. bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) {
  7865. bool replaced = false;
  7866. std::size_t i = str.find( replaceThis );
  7867. while( i != std::string::npos ) {
  7868. replaced = true;
  7869. str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() );
  7870. if( i < str.size()-withThis.size() )
  7871. i = str.find( replaceThis, i+withThis.size() );
  7872. else
  7873. i = std::string::npos;
  7874. }
  7875. return replaced;
  7876. }
  7877. pluralise::pluralise( std::size_t count, std::string const& label )
  7878. : m_count( count ),
  7879. m_label( label )
  7880. {}
  7881. std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) {
  7882. os << pluraliser.m_count << ' ' << pluraliser.m_label;
  7883. if( pluraliser.m_count != 1 )
  7884. os << 's';
  7885. return os;
  7886. }
  7887. }
  7888. // end catch_string_manip.cpp
  7889. // start catch_stringref.cpp
  7890. #if defined(__clang__)
  7891. # pragma clang diagnostic push
  7892. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  7893. #endif
  7894. #include <ostream>
  7895. #include <cstring>
  7896. #include <cstdint>
  7897. namespace {
  7898. const uint32_t byte_2_lead = 0xC0;
  7899. const uint32_t byte_3_lead = 0xE0;
  7900. const uint32_t byte_4_lead = 0xF0;
  7901. }
  7902. namespace Catch {
  7903. StringRef::StringRef( char const* rawChars ) noexcept
  7904. : StringRef( rawChars, static_cast<StringRef::size_type>(std::strlen(rawChars) ) )
  7905. {}
  7906. StringRef::operator std::string() const {
  7907. return std::string( m_start, m_size );
  7908. }
  7909. void StringRef::swap( StringRef& other ) noexcept {
  7910. std::swap( m_start, other.m_start );
  7911. std::swap( m_size, other.m_size );
  7912. std::swap( m_data, other.m_data );
  7913. }
  7914. auto StringRef::c_str() const -> char const* {
  7915. if( isSubstring() )
  7916. const_cast<StringRef*>( this )->takeOwnership();
  7917. return m_start;
  7918. }
  7919. auto StringRef::currentData() const noexcept -> char const* {
  7920. return m_start;
  7921. }
  7922. auto StringRef::isOwned() const noexcept -> bool {
  7923. return m_data != nullptr;
  7924. }
  7925. auto StringRef::isSubstring() const noexcept -> bool {
  7926. return m_start[m_size] != '\0';
  7927. }
  7928. void StringRef::takeOwnership() {
  7929. if( !isOwned() ) {
  7930. m_data = new char[m_size+1];
  7931. memcpy( m_data, m_start, m_size );
  7932. m_data[m_size] = '\0';
  7933. m_start = m_data;
  7934. }
  7935. }
  7936. auto StringRef::substr( size_type start, size_type size ) const noexcept -> StringRef {
  7937. if( start < m_size )
  7938. return StringRef( m_start+start, size );
  7939. else
  7940. return StringRef();
  7941. }
  7942. auto StringRef::operator == ( StringRef const& other ) const noexcept -> bool {
  7943. return
  7944. size() == other.size() &&
  7945. (std::strncmp( m_start, other.m_start, size() ) == 0);
  7946. }
  7947. auto StringRef::operator != ( StringRef const& other ) const noexcept -> bool {
  7948. return !operator==( other );
  7949. }
  7950. auto StringRef::operator[](size_type index) const noexcept -> char {
  7951. return m_start[index];
  7952. }
  7953. auto StringRef::numberOfCharacters() const noexcept -> size_type {
  7954. size_type noChars = m_size;
  7955. // Make adjustments for uft encodings
  7956. for( size_type i=0; i < m_size; ++i ) {
  7957. char c = m_start[i];
  7958. if( ( c & byte_2_lead ) == byte_2_lead ) {
  7959. noChars--;
  7960. if (( c & byte_3_lead ) == byte_3_lead )
  7961. noChars--;
  7962. if( ( c & byte_4_lead ) == byte_4_lead )
  7963. noChars--;
  7964. }
  7965. }
  7966. return noChars;
  7967. }
  7968. auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string {
  7969. std::string str;
  7970. str.reserve( lhs.size() + rhs.size() );
  7971. str += lhs;
  7972. str += rhs;
  7973. return str;
  7974. }
  7975. auto operator + ( StringRef const& lhs, const char* rhs ) -> std::string {
  7976. return std::string( lhs ) + std::string( rhs );
  7977. }
  7978. auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string {
  7979. return std::string( lhs ) + std::string( rhs );
  7980. }
  7981. auto operator << ( std::ostream& os, StringRef const& str ) -> std::ostream& {
  7982. return os.write(str.currentData(), str.size());
  7983. }
  7984. auto operator+=( std::string& lhs, StringRef const& rhs ) -> std::string& {
  7985. lhs.append(rhs.currentData(), rhs.size());
  7986. return lhs;
  7987. }
  7988. } // namespace Catch
  7989. #if defined(__clang__)
  7990. # pragma clang diagnostic pop
  7991. #endif
  7992. // end catch_stringref.cpp
  7993. // start catch_tag_alias.cpp
  7994. namespace Catch {
  7995. TagAlias::TagAlias(std::string const & _tag, SourceLineInfo _lineInfo): tag(_tag), lineInfo(_lineInfo) {}
  7996. }
  7997. // end catch_tag_alias.cpp
  7998. // start catch_tag_alias_autoregistrar.cpp
  7999. namespace Catch {
  8000. RegistrarForTagAliases::RegistrarForTagAliases(char const* alias, char const* tag, SourceLineInfo const& lineInfo) {
  8001. try {
  8002. getMutableRegistryHub().registerTagAlias(alias, tag, lineInfo);
  8003. } catch (...) {
  8004. // Do not throw when constructing global objects, instead register the exception to be processed later
  8005. getMutableRegistryHub().registerStartupException();
  8006. }
  8007. }
  8008. }
  8009. // end catch_tag_alias_autoregistrar.cpp
  8010. // start catch_tag_alias_registry.cpp
  8011. #include <sstream>
  8012. namespace Catch {
  8013. TagAliasRegistry::~TagAliasRegistry() {}
  8014. TagAlias const* TagAliasRegistry::find( std::string const& alias ) const {
  8015. auto it = m_registry.find( alias );
  8016. if( it != m_registry.end() )
  8017. return &(it->second);
  8018. else
  8019. return nullptr;
  8020. }
  8021. std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const {
  8022. std::string expandedTestSpec = unexpandedTestSpec;
  8023. for( auto const& registryKvp : m_registry ) {
  8024. std::size_t pos = expandedTestSpec.find( registryKvp.first );
  8025. if( pos != std::string::npos ) {
  8026. expandedTestSpec = expandedTestSpec.substr( 0, pos ) +
  8027. registryKvp.second.tag +
  8028. expandedTestSpec.substr( pos + registryKvp.first.size() );
  8029. }
  8030. }
  8031. return expandedTestSpec;
  8032. }
  8033. void TagAliasRegistry::add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) {
  8034. CATCH_ENFORCE( startsWith(alias, "[@") && endsWith(alias, ']'),
  8035. "error: tag alias, '" << alias << "' is not of the form [@alias name].\n" << lineInfo );
  8036. CATCH_ENFORCE( m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second,
  8037. "error: tag alias, '" << alias << "' already registered.\n"
  8038. << "\tFirst seen at: " << find(alias)->lineInfo << "\n"
  8039. << "\tRedefined at: " << lineInfo );
  8040. }
  8041. ITagAliasRegistry::~ITagAliasRegistry() {}
  8042. ITagAliasRegistry const& ITagAliasRegistry::get() {
  8043. return getRegistryHub().getTagAliasRegistry();
  8044. }
  8045. } // end namespace Catch
  8046. // end catch_tag_alias_registry.cpp
  8047. // start catch_test_case_info.cpp
  8048. #include <cctype>
  8049. #include <exception>
  8050. #include <algorithm>
  8051. #include <sstream>
  8052. namespace Catch {
  8053. TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) {
  8054. if( startsWith( tag, '.' ) ||
  8055. tag == "!hide" )
  8056. return TestCaseInfo::IsHidden;
  8057. else if( tag == "!throws" )
  8058. return TestCaseInfo::Throws;
  8059. else if( tag == "!shouldfail" )
  8060. return TestCaseInfo::ShouldFail;
  8061. else if( tag == "!mayfail" )
  8062. return TestCaseInfo::MayFail;
  8063. else if( tag == "!nonportable" )
  8064. return TestCaseInfo::NonPortable;
  8065. else if( tag == "!benchmark" )
  8066. return static_cast<TestCaseInfo::SpecialProperties>( TestCaseInfo::Benchmark | TestCaseInfo::IsHidden );
  8067. else
  8068. return TestCaseInfo::None;
  8069. }
  8070. bool isReservedTag( std::string const& tag ) {
  8071. return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !std::isalnum( static_cast<unsigned char>(tag[0]) );
  8072. }
  8073. void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) {
  8074. CATCH_ENFORCE( !isReservedTag(tag),
  8075. "Tag name: [" << tag << "] is not allowed.\n"
  8076. << "Tag names starting with non alpha-numeric characters are reserved\n"
  8077. << _lineInfo );
  8078. }
  8079. TestCase makeTestCase( ITestInvoker* _testCase,
  8080. std::string const& _className,
  8081. NameAndTags const& nameAndTags,
  8082. SourceLineInfo const& _lineInfo )
  8083. {
  8084. bool isHidden = false;
  8085. // Parse out tags
  8086. std::vector<std::string> tags;
  8087. std::string desc, tag;
  8088. bool inTag = false;
  8089. std::string _descOrTags = nameAndTags.tags;
  8090. for (char c : _descOrTags) {
  8091. if( !inTag ) {
  8092. if( c == '[' )
  8093. inTag = true;
  8094. else
  8095. desc += c;
  8096. }
  8097. else {
  8098. if( c == ']' ) {
  8099. TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag );
  8100. if( ( prop & TestCaseInfo::IsHidden ) != 0 )
  8101. isHidden = true;
  8102. else if( prop == TestCaseInfo::None )
  8103. enforceNotReservedTag( tag, _lineInfo );
  8104. tags.push_back( tag );
  8105. tag.clear();
  8106. inTag = false;
  8107. }
  8108. else
  8109. tag += c;
  8110. }
  8111. }
  8112. if( isHidden ) {
  8113. tags.push_back( "." );
  8114. }
  8115. TestCaseInfo info( nameAndTags.name, _className, desc, tags, _lineInfo );
  8116. return TestCase( _testCase, std::move(info) );
  8117. }
  8118. void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags ) {
  8119. std::sort(begin(tags), end(tags));
  8120. tags.erase(std::unique(begin(tags), end(tags)), end(tags));
  8121. testCaseInfo.lcaseTags.clear();
  8122. for( auto const& tag : tags ) {
  8123. std::string lcaseTag = toLower( tag );
  8124. testCaseInfo.properties = static_cast<TestCaseInfo::SpecialProperties>( testCaseInfo.properties | parseSpecialTag( lcaseTag ) );
  8125. testCaseInfo.lcaseTags.push_back( lcaseTag );
  8126. }
  8127. testCaseInfo.tags = std::move(tags);
  8128. }
  8129. TestCaseInfo::TestCaseInfo( std::string const& _name,
  8130. std::string const& _className,
  8131. std::string const& _description,
  8132. std::vector<std::string> const& _tags,
  8133. SourceLineInfo const& _lineInfo )
  8134. : name( _name ),
  8135. className( _className ),
  8136. description( _description ),
  8137. lineInfo( _lineInfo ),
  8138. properties( None )
  8139. {
  8140. setTags( *this, _tags );
  8141. }
  8142. bool TestCaseInfo::isHidden() const {
  8143. return ( properties & IsHidden ) != 0;
  8144. }
  8145. bool TestCaseInfo::throws() const {
  8146. return ( properties & Throws ) != 0;
  8147. }
  8148. bool TestCaseInfo::okToFail() const {
  8149. return ( properties & (ShouldFail | MayFail ) ) != 0;
  8150. }
  8151. bool TestCaseInfo::expectedToFail() const {
  8152. return ( properties & (ShouldFail ) ) != 0;
  8153. }
  8154. std::string TestCaseInfo::tagsAsString() const {
  8155. std::string ret;
  8156. // '[' and ']' per tag
  8157. std::size_t full_size = 2 * tags.size();
  8158. for (const auto& tag : tags) {
  8159. full_size += tag.size();
  8160. }
  8161. ret.reserve(full_size);
  8162. for (const auto& tag : tags) {
  8163. ret.push_back('[');
  8164. ret.append(tag);
  8165. ret.push_back(']');
  8166. }
  8167. return ret;
  8168. }
  8169. TestCase::TestCase( ITestInvoker* testCase, TestCaseInfo&& info ) : TestCaseInfo( std::move(info) ), test( testCase ) {}
  8170. TestCase TestCase::withName( std::string const& _newName ) const {
  8171. TestCase other( *this );
  8172. other.name = _newName;
  8173. return other;
  8174. }
  8175. void TestCase::invoke() const {
  8176. test->invoke();
  8177. }
  8178. bool TestCase::operator == ( TestCase const& other ) const {
  8179. return test.get() == other.test.get() &&
  8180. name == other.name &&
  8181. className == other.className;
  8182. }
  8183. bool TestCase::operator < ( TestCase const& other ) const {
  8184. return name < other.name;
  8185. }
  8186. TestCaseInfo const& TestCase::getTestCaseInfo() const
  8187. {
  8188. return *this;
  8189. }
  8190. } // end namespace Catch
  8191. // end catch_test_case_info.cpp
  8192. // start catch_test_case_registry_impl.cpp
  8193. #include <sstream>
  8194. namespace Catch {
  8195. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases ) {
  8196. std::vector<TestCase> sorted = unsortedTestCases;
  8197. switch( config.runOrder() ) {
  8198. case RunTests::InLexicographicalOrder:
  8199. std::sort( sorted.begin(), sorted.end() );
  8200. break;
  8201. case RunTests::InRandomOrder:
  8202. seedRng( config );
  8203. RandomNumberGenerator::shuffle( sorted );
  8204. break;
  8205. case RunTests::InDeclarationOrder:
  8206. // already in declaration order
  8207. break;
  8208. }
  8209. return sorted;
  8210. }
  8211. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ) {
  8212. return testSpec.matches( testCase ) && ( config.allowThrows() || !testCase.throws() );
  8213. }
  8214. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions ) {
  8215. std::set<TestCase> seenFunctions;
  8216. for( auto const& function : functions ) {
  8217. auto prev = seenFunctions.insert( function );
  8218. CATCH_ENFORCE( prev.second,
  8219. "error: TEST_CASE( \"" << function.name << "\" ) already defined.\n"
  8220. << "\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo << "\n"
  8221. << "\tRedefined at " << function.getTestCaseInfo().lineInfo );
  8222. }
  8223. }
  8224. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config ) {
  8225. std::vector<TestCase> filtered;
  8226. filtered.reserve( testCases.size() );
  8227. for( auto const& testCase : testCases )
  8228. if( matchTest( testCase, testSpec, config ) )
  8229. filtered.push_back( testCase );
  8230. return filtered;
  8231. }
  8232. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config ) {
  8233. return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config );
  8234. }
  8235. void TestRegistry::registerTest( TestCase const& testCase ) {
  8236. std::string name = testCase.getTestCaseInfo().name;
  8237. if( name.empty() ) {
  8238. ReusableStringStream rss;
  8239. rss << "Anonymous test case " << ++m_unnamedCount;
  8240. return registerTest( testCase.withName( rss.str() ) );
  8241. }
  8242. m_functions.push_back( testCase );
  8243. }
  8244. std::vector<TestCase> const& TestRegistry::getAllTests() const {
  8245. return m_functions;
  8246. }
  8247. std::vector<TestCase> const& TestRegistry::getAllTestsSorted( IConfig const& config ) const {
  8248. if( m_sortedFunctions.empty() )
  8249. enforceNoDuplicateTestCases( m_functions );
  8250. if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) {
  8251. m_sortedFunctions = sortTests( config, m_functions );
  8252. m_currentSortOrder = config.runOrder();
  8253. }
  8254. return m_sortedFunctions;
  8255. }
  8256. ///////////////////////////////////////////////////////////////////////////
  8257. TestInvokerAsFunction::TestInvokerAsFunction( void(*testAsFunction)() ) noexcept : m_testAsFunction( testAsFunction ) {}
  8258. void TestInvokerAsFunction::invoke() const {
  8259. m_testAsFunction();
  8260. }
  8261. std::string extractClassName( StringRef const& classOrQualifiedMethodName ) {
  8262. std::string className = classOrQualifiedMethodName;
  8263. if( startsWith( className, '&' ) )
  8264. {
  8265. std::size_t lastColons = className.rfind( "::" );
  8266. std::size_t penultimateColons = className.rfind( "::", lastColons-1 );
  8267. if( penultimateColons == std::string::npos )
  8268. penultimateColons = 1;
  8269. className = className.substr( penultimateColons, lastColons-penultimateColons );
  8270. }
  8271. return className;
  8272. }
  8273. } // end namespace Catch
  8274. // end catch_test_case_registry_impl.cpp
  8275. // start catch_test_case_tracker.cpp
  8276. #include <algorithm>
  8277. #include <cassert>
  8278. #include <stdexcept>
  8279. #include <memory>
  8280. #include <sstream>
  8281. #if defined(__clang__)
  8282. # pragma clang diagnostic push
  8283. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  8284. #endif
  8285. namespace Catch {
  8286. namespace TestCaseTracking {
  8287. NameAndLocation::NameAndLocation( std::string const& _name, SourceLineInfo const& _location )
  8288. : name( _name ),
  8289. location( _location )
  8290. {}
  8291. ITracker::~ITracker() = default;
  8292. TrackerContext& TrackerContext::instance() {
  8293. static TrackerContext s_instance;
  8294. return s_instance;
  8295. }
  8296. ITracker& TrackerContext::startRun() {
  8297. m_rootTracker = std::make_shared<SectionTracker>( NameAndLocation( "{root}", CATCH_INTERNAL_LINEINFO ), *this, nullptr );
  8298. m_currentTracker = nullptr;
  8299. m_runState = Executing;
  8300. return *m_rootTracker;
  8301. }
  8302. void TrackerContext::endRun() {
  8303. m_rootTracker.reset();
  8304. m_currentTracker = nullptr;
  8305. m_runState = NotStarted;
  8306. }
  8307. void TrackerContext::startCycle() {
  8308. m_currentTracker = m_rootTracker.get();
  8309. m_runState = Executing;
  8310. }
  8311. void TrackerContext::completeCycle() {
  8312. m_runState = CompletedCycle;
  8313. }
  8314. bool TrackerContext::completedCycle() const {
  8315. return m_runState == CompletedCycle;
  8316. }
  8317. ITracker& TrackerContext::currentTracker() {
  8318. return *m_currentTracker;
  8319. }
  8320. void TrackerContext::setCurrentTracker( ITracker* tracker ) {
  8321. m_currentTracker = tracker;
  8322. }
  8323. TrackerBase::TrackerHasName::TrackerHasName( NameAndLocation const& nameAndLocation ) : m_nameAndLocation( nameAndLocation ) {}
  8324. bool TrackerBase::TrackerHasName::operator ()( ITrackerPtr const& tracker ) const {
  8325. return
  8326. tracker->nameAndLocation().name == m_nameAndLocation.name &&
  8327. tracker->nameAndLocation().location == m_nameAndLocation.location;
  8328. }
  8329. TrackerBase::TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  8330. : m_nameAndLocation( nameAndLocation ),
  8331. m_ctx( ctx ),
  8332. m_parent( parent )
  8333. {}
  8334. NameAndLocation const& TrackerBase::nameAndLocation() const {
  8335. return m_nameAndLocation;
  8336. }
  8337. bool TrackerBase::isComplete() const {
  8338. return m_runState == CompletedSuccessfully || m_runState == Failed;
  8339. }
  8340. bool TrackerBase::isSuccessfullyCompleted() const {
  8341. return m_runState == CompletedSuccessfully;
  8342. }
  8343. bool TrackerBase::isOpen() const {
  8344. return m_runState != NotStarted && !isComplete();
  8345. }
  8346. bool TrackerBase::hasChildren() const {
  8347. return !m_children.empty();
  8348. }
  8349. void TrackerBase::addChild( ITrackerPtr const& child ) {
  8350. m_children.push_back( child );
  8351. }
  8352. ITrackerPtr TrackerBase::findChild( NameAndLocation const& nameAndLocation ) {
  8353. auto it = std::find_if( m_children.begin(), m_children.end(), TrackerHasName( nameAndLocation ) );
  8354. return( it != m_children.end() )
  8355. ? *it
  8356. : nullptr;
  8357. }
  8358. ITracker& TrackerBase::parent() {
  8359. assert( m_parent ); // Should always be non-null except for root
  8360. return *m_parent;
  8361. }
  8362. void TrackerBase::openChild() {
  8363. if( m_runState != ExecutingChildren ) {
  8364. m_runState = ExecutingChildren;
  8365. if( m_parent )
  8366. m_parent->openChild();
  8367. }
  8368. }
  8369. bool TrackerBase::isSectionTracker() const { return false; }
  8370. bool TrackerBase::isIndexTracker() const { return false; }
  8371. void TrackerBase::open() {
  8372. m_runState = Executing;
  8373. moveToThis();
  8374. if( m_parent )
  8375. m_parent->openChild();
  8376. }
  8377. void TrackerBase::close() {
  8378. // Close any still open children (e.g. generators)
  8379. while( &m_ctx.currentTracker() != this )
  8380. m_ctx.currentTracker().close();
  8381. switch( m_runState ) {
  8382. case NeedsAnotherRun:
  8383. break;
  8384. case Executing:
  8385. m_runState = CompletedSuccessfully;
  8386. break;
  8387. case ExecutingChildren:
  8388. if( m_children.empty() || m_children.back()->isComplete() )
  8389. m_runState = CompletedSuccessfully;
  8390. break;
  8391. case NotStarted:
  8392. case CompletedSuccessfully:
  8393. case Failed:
  8394. CATCH_INTERNAL_ERROR( "Illogical state: " << m_runState );
  8395. default:
  8396. CATCH_INTERNAL_ERROR( "Unknown state: " << m_runState );
  8397. }
  8398. moveToParent();
  8399. m_ctx.completeCycle();
  8400. }
  8401. void TrackerBase::fail() {
  8402. m_runState = Failed;
  8403. if( m_parent )
  8404. m_parent->markAsNeedingAnotherRun();
  8405. moveToParent();
  8406. m_ctx.completeCycle();
  8407. }
  8408. void TrackerBase::markAsNeedingAnotherRun() {
  8409. m_runState = NeedsAnotherRun;
  8410. }
  8411. void TrackerBase::moveToParent() {
  8412. assert( m_parent );
  8413. m_ctx.setCurrentTracker( m_parent );
  8414. }
  8415. void TrackerBase::moveToThis() {
  8416. m_ctx.setCurrentTracker( this );
  8417. }
  8418. SectionTracker::SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  8419. : TrackerBase( nameAndLocation, ctx, parent )
  8420. {
  8421. if( parent ) {
  8422. while( !parent->isSectionTracker() )
  8423. parent = &parent->parent();
  8424. SectionTracker& parentSection = static_cast<SectionTracker&>( *parent );
  8425. addNextFilters( parentSection.m_filters );
  8426. }
  8427. }
  8428. bool SectionTracker::isSectionTracker() const { return true; }
  8429. SectionTracker& SectionTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ) {
  8430. std::shared_ptr<SectionTracker> section;
  8431. ITracker& currentTracker = ctx.currentTracker();
  8432. if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  8433. assert( childTracker );
  8434. assert( childTracker->isSectionTracker() );
  8435. section = std::static_pointer_cast<SectionTracker>( childTracker );
  8436. }
  8437. else {
  8438. section = std::make_shared<SectionTracker>( nameAndLocation, ctx, &currentTracker );
  8439. currentTracker.addChild( section );
  8440. }
  8441. if( !ctx.completedCycle() )
  8442. section->tryOpen();
  8443. return *section;
  8444. }
  8445. void SectionTracker::tryOpen() {
  8446. if( !isComplete() && (m_filters.empty() || m_filters[0].empty() || m_filters[0] == m_nameAndLocation.name ) )
  8447. open();
  8448. }
  8449. void SectionTracker::addInitialFilters( std::vector<std::string> const& filters ) {
  8450. if( !filters.empty() ) {
  8451. m_filters.push_back(""); // Root - should never be consulted
  8452. m_filters.push_back(""); // Test Case - not a section filter
  8453. m_filters.insert( m_filters.end(), filters.begin(), filters.end() );
  8454. }
  8455. }
  8456. void SectionTracker::addNextFilters( std::vector<std::string> const& filters ) {
  8457. if( filters.size() > 1 )
  8458. m_filters.insert( m_filters.end(), ++filters.begin(), filters.end() );
  8459. }
  8460. IndexTracker::IndexTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent, int size )
  8461. : TrackerBase( nameAndLocation, ctx, parent ),
  8462. m_size( size )
  8463. {}
  8464. bool IndexTracker::isIndexTracker() const { return true; }
  8465. IndexTracker& IndexTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation, int size ) {
  8466. std::shared_ptr<IndexTracker> tracker;
  8467. ITracker& currentTracker = ctx.currentTracker();
  8468. if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  8469. assert( childTracker );
  8470. assert( childTracker->isIndexTracker() );
  8471. tracker = std::static_pointer_cast<IndexTracker>( childTracker );
  8472. }
  8473. else {
  8474. tracker = std::make_shared<IndexTracker>( nameAndLocation, ctx, &currentTracker, size );
  8475. currentTracker.addChild( tracker );
  8476. }
  8477. if( !ctx.completedCycle() && !tracker->isComplete() ) {
  8478. if( tracker->m_runState != ExecutingChildren && tracker->m_runState != NeedsAnotherRun )
  8479. tracker->moveNext();
  8480. tracker->open();
  8481. }
  8482. return *tracker;
  8483. }
  8484. int IndexTracker::index() const { return m_index; }
  8485. void IndexTracker::moveNext() {
  8486. m_index++;
  8487. m_children.clear();
  8488. }
  8489. void IndexTracker::close() {
  8490. TrackerBase::close();
  8491. if( m_runState == CompletedSuccessfully && m_index < m_size-1 )
  8492. m_runState = Executing;
  8493. }
  8494. } // namespace TestCaseTracking
  8495. using TestCaseTracking::ITracker;
  8496. using TestCaseTracking::TrackerContext;
  8497. using TestCaseTracking::SectionTracker;
  8498. using TestCaseTracking::IndexTracker;
  8499. } // namespace Catch
  8500. #if defined(__clang__)
  8501. # pragma clang diagnostic pop
  8502. #endif
  8503. // end catch_test_case_tracker.cpp
  8504. // start catch_test_registry.cpp
  8505. namespace Catch {
  8506. auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker* {
  8507. return new(std::nothrow) TestInvokerAsFunction( testAsFunction );
  8508. }
  8509. NameAndTags::NameAndTags( StringRef const& name_ , StringRef const& tags_ ) noexcept : name( name_ ), tags( tags_ ) {}
  8510. AutoReg::AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept {
  8511. try {
  8512. getMutableRegistryHub()
  8513. .registerTest(
  8514. makeTestCase(
  8515. invoker,
  8516. extractClassName( classOrMethod ),
  8517. nameAndTags,
  8518. lineInfo));
  8519. } catch (...) {
  8520. // Do not throw when constructing global objects, instead register the exception to be processed later
  8521. getMutableRegistryHub().registerStartupException();
  8522. }
  8523. }
  8524. AutoReg::~AutoReg() = default;
  8525. }
  8526. // end catch_test_registry.cpp
  8527. // start catch_test_spec.cpp
  8528. #include <algorithm>
  8529. #include <string>
  8530. #include <vector>
  8531. #include <memory>
  8532. namespace Catch {
  8533. TestSpec::Pattern::~Pattern() = default;
  8534. TestSpec::NamePattern::~NamePattern() = default;
  8535. TestSpec::TagPattern::~TagPattern() = default;
  8536. TestSpec::ExcludedPattern::~ExcludedPattern() = default;
  8537. TestSpec::NamePattern::NamePattern( std::string const& name )
  8538. : m_wildcardPattern( toLower( name ), CaseSensitive::No )
  8539. {}
  8540. bool TestSpec::NamePattern::matches( TestCaseInfo const& testCase ) const {
  8541. return m_wildcardPattern.matches( toLower( testCase.name ) );
  8542. }
  8543. TestSpec::TagPattern::TagPattern( std::string const& tag ) : m_tag( toLower( tag ) ) {}
  8544. bool TestSpec::TagPattern::matches( TestCaseInfo const& testCase ) const {
  8545. return std::find(begin(testCase.lcaseTags),
  8546. end(testCase.lcaseTags),
  8547. m_tag) != end(testCase.lcaseTags);
  8548. }
  8549. TestSpec::ExcludedPattern::ExcludedPattern( PatternPtr const& underlyingPattern ) : m_underlyingPattern( underlyingPattern ) {}
  8550. bool TestSpec::ExcludedPattern::matches( TestCaseInfo const& testCase ) const { return !m_underlyingPattern->matches( testCase ); }
  8551. bool TestSpec::Filter::matches( TestCaseInfo const& testCase ) const {
  8552. // All patterns in a filter must match for the filter to be a match
  8553. for( auto const& pattern : m_patterns ) {
  8554. if( !pattern->matches( testCase ) )
  8555. return false;
  8556. }
  8557. return true;
  8558. }
  8559. bool TestSpec::hasFilters() const {
  8560. return !m_filters.empty();
  8561. }
  8562. bool TestSpec::matches( TestCaseInfo const& testCase ) const {
  8563. // A TestSpec matches if any filter matches
  8564. for( auto const& filter : m_filters )
  8565. if( filter.matches( testCase ) )
  8566. return true;
  8567. return false;
  8568. }
  8569. }
  8570. // end catch_test_spec.cpp
  8571. // start catch_test_spec_parser.cpp
  8572. namespace Catch {
  8573. TestSpecParser::TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {}
  8574. TestSpecParser& TestSpecParser::parse( std::string const& arg ) {
  8575. m_mode = None;
  8576. m_exclusion = false;
  8577. m_start = std::string::npos;
  8578. m_arg = m_tagAliases->expandAliases( arg );
  8579. m_escapeChars.clear();
  8580. for( m_pos = 0; m_pos < m_arg.size(); ++m_pos )
  8581. visitChar( m_arg[m_pos] );
  8582. if( m_mode == Name )
  8583. addPattern<TestSpec::NamePattern>();
  8584. return *this;
  8585. }
  8586. TestSpec TestSpecParser::testSpec() {
  8587. addFilter();
  8588. return m_testSpec;
  8589. }
  8590. void TestSpecParser::visitChar( char c ) {
  8591. if( m_mode == None ) {
  8592. switch( c ) {
  8593. case ' ': return;
  8594. case '~': m_exclusion = true; return;
  8595. case '[': return startNewMode( Tag, ++m_pos );
  8596. case '"': return startNewMode( QuotedName, ++m_pos );
  8597. case '\\': return escape();
  8598. default: startNewMode( Name, m_pos ); break;
  8599. }
  8600. }
  8601. if( m_mode == Name ) {
  8602. if( c == ',' ) {
  8603. addPattern<TestSpec::NamePattern>();
  8604. addFilter();
  8605. }
  8606. else if( c == '[' ) {
  8607. if( subString() == "exclude:" )
  8608. m_exclusion = true;
  8609. else
  8610. addPattern<TestSpec::NamePattern>();
  8611. startNewMode( Tag, ++m_pos );
  8612. }
  8613. else if( c == '\\' )
  8614. escape();
  8615. }
  8616. else if( m_mode == EscapedName )
  8617. m_mode = Name;
  8618. else if( m_mode == QuotedName && c == '"' )
  8619. addPattern<TestSpec::NamePattern>();
  8620. else if( m_mode == Tag && c == ']' )
  8621. addPattern<TestSpec::TagPattern>();
  8622. }
  8623. void TestSpecParser::startNewMode( Mode mode, std::size_t start ) {
  8624. m_mode = mode;
  8625. m_start = start;
  8626. }
  8627. void TestSpecParser::escape() {
  8628. if( m_mode == None )
  8629. m_start = m_pos;
  8630. m_mode = EscapedName;
  8631. m_escapeChars.push_back( m_pos );
  8632. }
  8633. std::string TestSpecParser::subString() const { return m_arg.substr( m_start, m_pos - m_start ); }
  8634. void TestSpecParser::addFilter() {
  8635. if( !m_currentFilter.m_patterns.empty() ) {
  8636. m_testSpec.m_filters.push_back( m_currentFilter );
  8637. m_currentFilter = TestSpec::Filter();
  8638. }
  8639. }
  8640. TestSpec parseTestSpec( std::string const& arg ) {
  8641. return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec();
  8642. }
  8643. } // namespace Catch
  8644. // end catch_test_spec_parser.cpp
  8645. // start catch_timer.cpp
  8646. #include <chrono>
  8647. static const uint64_t nanosecondsInSecond = 1000000000;
  8648. namespace Catch {
  8649. auto getCurrentNanosecondsSinceEpoch() -> uint64_t {
  8650. return std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::high_resolution_clock::now().time_since_epoch() ).count();
  8651. }
  8652. auto estimateClockResolution() -> uint64_t {
  8653. uint64_t sum = 0;
  8654. static const uint64_t iterations = 1000000;
  8655. auto startTime = getCurrentNanosecondsSinceEpoch();
  8656. for( std::size_t i = 0; i < iterations; ++i ) {
  8657. uint64_t ticks;
  8658. uint64_t baseTicks = getCurrentNanosecondsSinceEpoch();
  8659. do {
  8660. ticks = getCurrentNanosecondsSinceEpoch();
  8661. } while( ticks == baseTicks );
  8662. auto delta = ticks - baseTicks;
  8663. sum += delta;
  8664. // If we have been calibrating for over 3 seconds -- the clock
  8665. // is terrible and we should move on.
  8666. // TBD: How to signal that the measured resolution is probably wrong?
  8667. if (ticks > startTime + 3 * nanosecondsInSecond) {
  8668. return sum / i;
  8669. }
  8670. }
  8671. // We're just taking the mean, here. To do better we could take the std. dev and exclude outliers
  8672. // - and potentially do more iterations if there's a high variance.
  8673. return sum/iterations;
  8674. }
  8675. auto getEstimatedClockResolution() -> uint64_t {
  8676. static auto s_resolution = estimateClockResolution();
  8677. return s_resolution;
  8678. }
  8679. void Timer::start() {
  8680. m_nanoseconds = getCurrentNanosecondsSinceEpoch();
  8681. }
  8682. auto Timer::getElapsedNanoseconds() const -> uint64_t {
  8683. return getCurrentNanosecondsSinceEpoch() - m_nanoseconds;
  8684. }
  8685. auto Timer::getElapsedMicroseconds() const -> uint64_t {
  8686. return getElapsedNanoseconds()/1000;
  8687. }
  8688. auto Timer::getElapsedMilliseconds() const -> unsigned int {
  8689. return static_cast<unsigned int>(getElapsedMicroseconds()/1000);
  8690. }
  8691. auto Timer::getElapsedSeconds() const -> double {
  8692. return getElapsedMicroseconds()/1000000.0;
  8693. }
  8694. } // namespace Catch
  8695. // end catch_timer.cpp
  8696. // start catch_tostring.cpp
  8697. #if defined(__clang__)
  8698. # pragma clang diagnostic push
  8699. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  8700. # pragma clang diagnostic ignored "-Wglobal-constructors"
  8701. #endif
  8702. // Enable specific decls locally
  8703. #if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  8704. #define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  8705. #endif
  8706. #include <cmath>
  8707. #include <iomanip>
  8708. namespace Catch {
  8709. namespace Detail {
  8710. const std::string unprintableString = "{?}";
  8711. namespace {
  8712. const int hexThreshold = 255;
  8713. struct Endianness {
  8714. enum Arch { Big, Little };
  8715. static Arch which() {
  8716. union _{
  8717. int asInt;
  8718. char asChar[sizeof (int)];
  8719. } u;
  8720. u.asInt = 1;
  8721. return ( u.asChar[sizeof(int)-1] == 1 ) ? Big : Little;
  8722. }
  8723. };
  8724. }
  8725. std::string rawMemoryToString( const void *object, std::size_t size ) {
  8726. // Reverse order for little endian architectures
  8727. int i = 0, end = static_cast<int>( size ), inc = 1;
  8728. if( Endianness::which() == Endianness::Little ) {
  8729. i = end-1;
  8730. end = inc = -1;
  8731. }
  8732. unsigned char const *bytes = static_cast<unsigned char const *>(object);
  8733. ReusableStringStream rss;
  8734. rss << "0x" << std::setfill('0') << std::hex;
  8735. for( ; i != end; i += inc )
  8736. rss << std::setw(2) << static_cast<unsigned>(bytes[i]);
  8737. return rss.str();
  8738. }
  8739. }
  8740. template<typename T>
  8741. std::string fpToString( T value, int precision ) {
  8742. if (std::isnan(value)) {
  8743. return "nan";
  8744. }
  8745. ReusableStringStream rss;
  8746. rss << std::setprecision( precision )
  8747. << std::fixed
  8748. << value;
  8749. std::string d = rss.str();
  8750. std::size_t i = d.find_last_not_of( '0' );
  8751. if( i != std::string::npos && i != d.size()-1 ) {
  8752. if( d[i] == '.' )
  8753. i++;
  8754. d = d.substr( 0, i+1 );
  8755. }
  8756. return d;
  8757. }
  8758. //// ======================================================= ////
  8759. //
  8760. // Out-of-line defs for full specialization of StringMaker
  8761. //
  8762. //// ======================================================= ////
  8763. std::string StringMaker<std::string>::convert(const std::string& str) {
  8764. if (!getCurrentContext().getConfig()->showInvisibles()) {
  8765. return '"' + str + '"';
  8766. }
  8767. std::string s("\"");
  8768. for (char c : str) {
  8769. switch (c) {
  8770. case '\n':
  8771. s.append("\\n");
  8772. break;
  8773. case '\t':
  8774. s.append("\\t");
  8775. break;
  8776. default:
  8777. s.push_back(c);
  8778. break;
  8779. }
  8780. }
  8781. s.append("\"");
  8782. return s;
  8783. }
  8784. #ifdef CATCH_CONFIG_WCHAR
  8785. std::string StringMaker<std::wstring>::convert(const std::wstring& wstr) {
  8786. std::string s;
  8787. s.reserve(wstr.size());
  8788. for (auto c : wstr) {
  8789. s += (c <= 0xff) ? static_cast<char>(c) : '?';
  8790. }
  8791. return ::Catch::Detail::stringify(s);
  8792. }
  8793. #endif
  8794. std::string StringMaker<char const*>::convert(char const* str) {
  8795. if (str) {
  8796. return ::Catch::Detail::stringify(std::string{ str });
  8797. } else {
  8798. return{ "{null string}" };
  8799. }
  8800. }
  8801. std::string StringMaker<char*>::convert(char* str) {
  8802. if (str) {
  8803. return ::Catch::Detail::stringify(std::string{ str });
  8804. } else {
  8805. return{ "{null string}" };
  8806. }
  8807. }
  8808. #ifdef CATCH_CONFIG_WCHAR
  8809. std::string StringMaker<wchar_t const*>::convert(wchar_t const * str) {
  8810. if (str) {
  8811. return ::Catch::Detail::stringify(std::wstring{ str });
  8812. } else {
  8813. return{ "{null string}" };
  8814. }
  8815. }
  8816. std::string StringMaker<wchar_t *>::convert(wchar_t * str) {
  8817. if (str) {
  8818. return ::Catch::Detail::stringify(std::wstring{ str });
  8819. } else {
  8820. return{ "{null string}" };
  8821. }
  8822. }
  8823. #endif
  8824. std::string StringMaker<int>::convert(int value) {
  8825. return ::Catch::Detail::stringify(static_cast<long long>(value));
  8826. }
  8827. std::string StringMaker<long>::convert(long value) {
  8828. return ::Catch::Detail::stringify(static_cast<long long>(value));
  8829. }
  8830. std::string StringMaker<long long>::convert(long long value) {
  8831. ReusableStringStream rss;
  8832. rss << value;
  8833. if (value > Detail::hexThreshold) {
  8834. rss << " (0x" << std::hex << value << ')';
  8835. }
  8836. return rss.str();
  8837. }
  8838. std::string StringMaker<unsigned int>::convert(unsigned int value) {
  8839. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  8840. }
  8841. std::string StringMaker<unsigned long>::convert(unsigned long value) {
  8842. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  8843. }
  8844. std::string StringMaker<unsigned long long>::convert(unsigned long long value) {
  8845. ReusableStringStream rss;
  8846. rss << value;
  8847. if (value > Detail::hexThreshold) {
  8848. rss << " (0x" << std::hex << value << ')';
  8849. }
  8850. return rss.str();
  8851. }
  8852. std::string StringMaker<bool>::convert(bool b) {
  8853. return b ? "true" : "false";
  8854. }
  8855. std::string StringMaker<char>::convert(char value) {
  8856. if (value == '\r') {
  8857. return "'\\r'";
  8858. } else if (value == '\f') {
  8859. return "'\\f'";
  8860. } else if (value == '\n') {
  8861. return "'\\n'";
  8862. } else if (value == '\t') {
  8863. return "'\\t'";
  8864. } else if ('\0' <= value && value < ' ') {
  8865. return ::Catch::Detail::stringify(static_cast<unsigned int>(value));
  8866. } else {
  8867. char chstr[] = "' '";
  8868. chstr[1] = value;
  8869. return chstr;
  8870. }
  8871. }
  8872. std::string StringMaker<signed char>::convert(signed char c) {
  8873. return ::Catch::Detail::stringify(static_cast<char>(c));
  8874. }
  8875. std::string StringMaker<unsigned char>::convert(unsigned char c) {
  8876. return ::Catch::Detail::stringify(static_cast<char>(c));
  8877. }
  8878. std::string StringMaker<std::nullptr_t>::convert(std::nullptr_t) {
  8879. return "nullptr";
  8880. }
  8881. std::string StringMaker<float>::convert(float value) {
  8882. return fpToString(value, 5) + 'f';
  8883. }
  8884. std::string StringMaker<double>::convert(double value) {
  8885. return fpToString(value, 10);
  8886. }
  8887. std::string ratio_string<std::atto>::symbol() { return "a"; }
  8888. std::string ratio_string<std::femto>::symbol() { return "f"; }
  8889. std::string ratio_string<std::pico>::symbol() { return "p"; }
  8890. std::string ratio_string<std::nano>::symbol() { return "n"; }
  8891. std::string ratio_string<std::micro>::symbol() { return "u"; }
  8892. std::string ratio_string<std::milli>::symbol() { return "m"; }
  8893. } // end namespace Catch
  8894. #if defined(__clang__)
  8895. # pragma clang diagnostic pop
  8896. #endif
  8897. // end catch_tostring.cpp
  8898. // start catch_totals.cpp
  8899. namespace Catch {
  8900. Counts Counts::operator - ( Counts const& other ) const {
  8901. Counts diff;
  8902. diff.passed = passed - other.passed;
  8903. diff.failed = failed - other.failed;
  8904. diff.failedButOk = failedButOk - other.failedButOk;
  8905. return diff;
  8906. }
  8907. Counts& Counts::operator += ( Counts const& other ) {
  8908. passed += other.passed;
  8909. failed += other.failed;
  8910. failedButOk += other.failedButOk;
  8911. return *this;
  8912. }
  8913. std::size_t Counts::total() const {
  8914. return passed + failed + failedButOk;
  8915. }
  8916. bool Counts::allPassed() const {
  8917. return failed == 0 && failedButOk == 0;
  8918. }
  8919. bool Counts::allOk() const {
  8920. return failed == 0;
  8921. }
  8922. Totals Totals::operator - ( Totals const& other ) const {
  8923. Totals diff;
  8924. diff.assertions = assertions - other.assertions;
  8925. diff.testCases = testCases - other.testCases;
  8926. return diff;
  8927. }
  8928. Totals& Totals::operator += ( Totals const& other ) {
  8929. assertions += other.assertions;
  8930. testCases += other.testCases;
  8931. return *this;
  8932. }
  8933. Totals Totals::delta( Totals const& prevTotals ) const {
  8934. Totals diff = *this - prevTotals;
  8935. if( diff.assertions.failed > 0 )
  8936. ++diff.testCases.failed;
  8937. else if( diff.assertions.failedButOk > 0 )
  8938. ++diff.testCases.failedButOk;
  8939. else
  8940. ++diff.testCases.passed;
  8941. return diff;
  8942. }
  8943. }
  8944. // end catch_totals.cpp
  8945. // start catch_uncaught_exceptions.cpp
  8946. #include <exception>
  8947. namespace Catch {
  8948. bool uncaught_exceptions() {
  8949. #if defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
  8950. return std::uncaught_exceptions() > 0;
  8951. #else
  8952. return std::uncaught_exception();
  8953. #endif
  8954. }
  8955. } // end namespace Catch
  8956. // end catch_uncaught_exceptions.cpp
  8957. // start catch_version.cpp
  8958. #include <ostream>
  8959. namespace Catch {
  8960. Version::Version
  8961. ( unsigned int _majorVersion,
  8962. unsigned int _minorVersion,
  8963. unsigned int _patchNumber,
  8964. char const * const _branchName,
  8965. unsigned int _buildNumber )
  8966. : majorVersion( _majorVersion ),
  8967. minorVersion( _minorVersion ),
  8968. patchNumber( _patchNumber ),
  8969. branchName( _branchName ),
  8970. buildNumber( _buildNumber )
  8971. {}
  8972. std::ostream& operator << ( std::ostream& os, Version const& version ) {
  8973. os << version.majorVersion << '.'
  8974. << version.minorVersion << '.'
  8975. << version.patchNumber;
  8976. // branchName is never null -> 0th char is \0 if it is empty
  8977. if (version.branchName[0]) {
  8978. os << '-' << version.branchName
  8979. << '.' << version.buildNumber;
  8980. }
  8981. return os;
  8982. }
  8983. Version const& libraryVersion() {
  8984. static Version version( 2, 2, 3, "", 0 );
  8985. return version;
  8986. }
  8987. }
  8988. // end catch_version.cpp
  8989. // start catch_wildcard_pattern.cpp
  8990. #include <sstream>
  8991. namespace Catch {
  8992. WildcardPattern::WildcardPattern( std::string const& pattern,
  8993. CaseSensitive::Choice caseSensitivity )
  8994. : m_caseSensitivity( caseSensitivity ),
  8995. m_pattern( adjustCase( pattern ) )
  8996. {
  8997. if( startsWith( m_pattern, '*' ) ) {
  8998. m_pattern = m_pattern.substr( 1 );
  8999. m_wildcard = WildcardAtStart;
  9000. }
  9001. if( endsWith( m_pattern, '*' ) ) {
  9002. m_pattern = m_pattern.substr( 0, m_pattern.size()-1 );
  9003. m_wildcard = static_cast<WildcardPosition>( m_wildcard | WildcardAtEnd );
  9004. }
  9005. }
  9006. bool WildcardPattern::matches( std::string const& str ) const {
  9007. switch( m_wildcard ) {
  9008. case NoWildcard:
  9009. return m_pattern == adjustCase( str );
  9010. case WildcardAtStart:
  9011. return endsWith( adjustCase( str ), m_pattern );
  9012. case WildcardAtEnd:
  9013. return startsWith( adjustCase( str ), m_pattern );
  9014. case WildcardAtBothEnds:
  9015. return contains( adjustCase( str ), m_pattern );
  9016. default:
  9017. CATCH_INTERNAL_ERROR( "Unknown enum" );
  9018. }
  9019. }
  9020. std::string WildcardPattern::adjustCase( std::string const& str ) const {
  9021. return m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str;
  9022. }
  9023. }
  9024. // end catch_wildcard_pattern.cpp
  9025. // start catch_xmlwriter.cpp
  9026. #include <iomanip>
  9027. using uchar = unsigned char;
  9028. namespace Catch {
  9029. namespace {
  9030. size_t trailingBytes(unsigned char c) {
  9031. if ((c & 0xE0) == 0xC0) {
  9032. return 2;
  9033. }
  9034. if ((c & 0xF0) == 0xE0) {
  9035. return 3;
  9036. }
  9037. if ((c & 0xF8) == 0xF0) {
  9038. return 4;
  9039. }
  9040. CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
  9041. }
  9042. uint32_t headerValue(unsigned char c) {
  9043. if ((c & 0xE0) == 0xC0) {
  9044. return c & 0x1F;
  9045. }
  9046. if ((c & 0xF0) == 0xE0) {
  9047. return c & 0x0F;
  9048. }
  9049. if ((c & 0xF8) == 0xF0) {
  9050. return c & 0x07;
  9051. }
  9052. CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
  9053. }
  9054. void hexEscapeChar(std::ostream& os, unsigned char c) {
  9055. os << "\\x"
  9056. << std::uppercase << std::hex << std::setfill('0') << std::setw(2)
  9057. << static_cast<int>(c);
  9058. }
  9059. } // anonymous namespace
  9060. XmlEncode::XmlEncode( std::string const& str, ForWhat forWhat )
  9061. : m_str( str ),
  9062. m_forWhat( forWhat )
  9063. {}
  9064. void XmlEncode::encodeTo( std::ostream& os ) const {
  9065. // Apostrophe escaping not necessary if we always use " to write attributes
  9066. // (see: http://www.w3.org/TR/xml/#syntax)
  9067. for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) {
  9068. uchar c = m_str[idx];
  9069. switch (c) {
  9070. case '<': os << "&lt;"; break;
  9071. case '&': os << "&amp;"; break;
  9072. case '>':
  9073. // See: http://www.w3.org/TR/xml/#syntax
  9074. if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']')
  9075. os << "&gt;";
  9076. else
  9077. os << c;
  9078. break;
  9079. case '\"':
  9080. if (m_forWhat == ForAttributes)
  9081. os << "&quot;";
  9082. else
  9083. os << c;
  9084. break;
  9085. default:
  9086. // Check for control characters and invalid utf-8
  9087. // Escape control characters in standard ascii
  9088. // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0
  9089. if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) {
  9090. hexEscapeChar(os, c);
  9091. break;
  9092. }
  9093. // Plain ASCII: Write it to stream
  9094. if (c < 0x7F) {
  9095. os << c;
  9096. break;
  9097. }
  9098. // UTF-8 territory
  9099. // Check if the encoding is valid and if it is not, hex escape bytes.
  9100. // Important: We do not check the exact decoded values for validity, only the encoding format
  9101. // First check that this bytes is a valid lead byte:
  9102. // This means that it is not encoded as 1111 1XXX
  9103. // Or as 10XX XXXX
  9104. if (c < 0xC0 ||
  9105. c >= 0xF8) {
  9106. hexEscapeChar(os, c);
  9107. break;
  9108. }
  9109. auto encBytes = trailingBytes(c);
  9110. // Are there enough bytes left to avoid accessing out-of-bounds memory?
  9111. if (idx + encBytes - 1 >= m_str.size()) {
  9112. hexEscapeChar(os, c);
  9113. break;
  9114. }
  9115. // The header is valid, check data
  9116. // The next encBytes bytes must together be a valid utf-8
  9117. // This means: bitpattern 10XX XXXX and the extracted value is sane (ish)
  9118. bool valid = true;
  9119. uint32_t value = headerValue(c);
  9120. for (std::size_t n = 1; n < encBytes; ++n) {
  9121. uchar nc = m_str[idx + n];
  9122. valid &= ((nc & 0xC0) == 0x80);
  9123. value = (value << 6) | (nc & 0x3F);
  9124. }
  9125. if (
  9126. // Wrong bit pattern of following bytes
  9127. (!valid) ||
  9128. // Overlong encodings
  9129. (value < 0x80) ||
  9130. (0x80 <= value && value < 0x800 && encBytes > 2) ||
  9131. (0x800 < value && value < 0x10000 && encBytes > 3) ||
  9132. // Encoded value out of range
  9133. (value >= 0x110000)
  9134. ) {
  9135. hexEscapeChar(os, c);
  9136. break;
  9137. }
  9138. // If we got here, this is in fact a valid(ish) utf-8 sequence
  9139. for (std::size_t n = 0; n < encBytes; ++n) {
  9140. os << m_str[idx + n];
  9141. }
  9142. idx += encBytes - 1;
  9143. break;
  9144. }
  9145. }
  9146. }
  9147. std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) {
  9148. xmlEncode.encodeTo( os );
  9149. return os;
  9150. }
  9151. XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer )
  9152. : m_writer( writer )
  9153. {}
  9154. XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept
  9155. : m_writer( other.m_writer ){
  9156. other.m_writer = nullptr;
  9157. }
  9158. XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) noexcept {
  9159. if ( m_writer ) {
  9160. m_writer->endElement();
  9161. }
  9162. m_writer = other.m_writer;
  9163. other.m_writer = nullptr;
  9164. return *this;
  9165. }
  9166. XmlWriter::ScopedElement::~ScopedElement() {
  9167. if( m_writer )
  9168. m_writer->endElement();
  9169. }
  9170. XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string const& text, bool indent ) {
  9171. m_writer->writeText( text, indent );
  9172. return *this;
  9173. }
  9174. XmlWriter::XmlWriter( std::ostream& os ) : m_os( os )
  9175. {
  9176. writeDeclaration();
  9177. }
  9178. XmlWriter::~XmlWriter() {
  9179. while( !m_tags.empty() )
  9180. endElement();
  9181. }
  9182. XmlWriter& XmlWriter::startElement( std::string const& name ) {
  9183. ensureTagClosed();
  9184. newlineIfNecessary();
  9185. m_os << m_indent << '<' << name;
  9186. m_tags.push_back( name );
  9187. m_indent += " ";
  9188. m_tagIsOpen = true;
  9189. return *this;
  9190. }
  9191. XmlWriter::ScopedElement XmlWriter::scopedElement( std::string const& name ) {
  9192. ScopedElement scoped( this );
  9193. startElement( name );
  9194. return scoped;
  9195. }
  9196. XmlWriter& XmlWriter::endElement() {
  9197. newlineIfNecessary();
  9198. m_indent = m_indent.substr( 0, m_indent.size()-2 );
  9199. if( m_tagIsOpen ) {
  9200. m_os << "/>";
  9201. m_tagIsOpen = false;
  9202. }
  9203. else {
  9204. m_os << m_indent << "</" << m_tags.back() << ">";
  9205. }
  9206. m_os << std::endl;
  9207. m_tags.pop_back();
  9208. return *this;
  9209. }
  9210. XmlWriter& XmlWriter::writeAttribute( std::string const& name, std::string const& attribute ) {
  9211. if( !name.empty() && !attribute.empty() )
  9212. m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"';
  9213. return *this;
  9214. }
  9215. XmlWriter& XmlWriter::writeAttribute( std::string const& name, bool attribute ) {
  9216. m_os << ' ' << name << "=\"" << ( attribute ? "true" : "false" ) << '"';
  9217. return *this;
  9218. }
  9219. XmlWriter& XmlWriter::writeText( std::string const& text, bool indent ) {
  9220. if( !text.empty() ){
  9221. bool tagWasOpen = m_tagIsOpen;
  9222. ensureTagClosed();
  9223. if( tagWasOpen && indent )
  9224. m_os << m_indent;
  9225. m_os << XmlEncode( text );
  9226. m_needsNewline = true;
  9227. }
  9228. return *this;
  9229. }
  9230. XmlWriter& XmlWriter::writeComment( std::string const& text ) {
  9231. ensureTagClosed();
  9232. m_os << m_indent << "<!--" << text << "-->";
  9233. m_needsNewline = true;
  9234. return *this;
  9235. }
  9236. void XmlWriter::writeStylesheetRef( std::string const& url ) {
  9237. m_os << "<?xml-stylesheet type=\"text/xsl\" href=\"" << url << "\"?>\n";
  9238. }
  9239. XmlWriter& XmlWriter::writeBlankLine() {
  9240. ensureTagClosed();
  9241. m_os << '\n';
  9242. return *this;
  9243. }
  9244. void XmlWriter::ensureTagClosed() {
  9245. if( m_tagIsOpen ) {
  9246. m_os << ">" << std::endl;
  9247. m_tagIsOpen = false;
  9248. }
  9249. }
  9250. void XmlWriter::writeDeclaration() {
  9251. m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
  9252. }
  9253. void XmlWriter::newlineIfNecessary() {
  9254. if( m_needsNewline ) {
  9255. m_os << std::endl;
  9256. m_needsNewline = false;
  9257. }
  9258. }
  9259. }
  9260. // end catch_xmlwriter.cpp
  9261. // start catch_reporter_bases.cpp
  9262. #include <cstring>
  9263. #include <cfloat>
  9264. #include <cstdio>
  9265. #include <cassert>
  9266. #include <memory>
  9267. namespace Catch {
  9268. void prepareExpandedExpression(AssertionResult& result) {
  9269. result.getExpandedExpression();
  9270. }
  9271. // Because formatting using c++ streams is stateful, drop down to C is required
  9272. // Alternatively we could use stringstream, but its performance is... not good.
  9273. std::string getFormattedDuration( double duration ) {
  9274. // Max exponent + 1 is required to represent the whole part
  9275. // + 1 for decimal point
  9276. // + 3 for the 3 decimal places
  9277. // + 1 for null terminator
  9278. const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1;
  9279. char buffer[maxDoubleSize];
  9280. // Save previous errno, to prevent sprintf from overwriting it
  9281. ErrnoGuard guard;
  9282. #ifdef _MSC_VER
  9283. sprintf_s(buffer, "%.3f", duration);
  9284. #else
  9285. sprintf(buffer, "%.3f", duration);
  9286. #endif
  9287. return std::string(buffer);
  9288. }
  9289. TestEventListenerBase::TestEventListenerBase(ReporterConfig const & _config)
  9290. :StreamingReporterBase(_config) {}
  9291. void TestEventListenerBase::assertionStarting(AssertionInfo const &) {}
  9292. bool TestEventListenerBase::assertionEnded(AssertionStats const &) {
  9293. return false;
  9294. }
  9295. } // end namespace Catch
  9296. // end catch_reporter_bases.cpp
  9297. // start catch_reporter_compact.cpp
  9298. namespace {
  9299. #ifdef CATCH_PLATFORM_MAC
  9300. const char* failedString() { return "FAILED"; }
  9301. const char* passedString() { return "PASSED"; }
  9302. #else
  9303. const char* failedString() { return "failed"; }
  9304. const char* passedString() { return "passed"; }
  9305. #endif
  9306. // Colour::LightGrey
  9307. Catch::Colour::Code dimColour() { return Catch::Colour::FileName; }
  9308. std::string bothOrAll( std::size_t count ) {
  9309. return count == 1 ? std::string() :
  9310. count == 2 ? "both " : "all " ;
  9311. }
  9312. } // anon namespace
  9313. namespace Catch {
  9314. namespace {
  9315. // Colour, message variants:
  9316. // - white: No tests ran.
  9317. // - red: Failed [both/all] N test cases, failed [both/all] M assertions.
  9318. // - white: Passed [both/all] N test cases (no assertions).
  9319. // - red: Failed N tests cases, failed M assertions.
  9320. // - green: Passed [both/all] N tests cases with M assertions.
  9321. void printTotals(std::ostream& out, const Totals& totals) {
  9322. if (totals.testCases.total() == 0) {
  9323. out << "No tests ran.";
  9324. } else if (totals.testCases.failed == totals.testCases.total()) {
  9325. Colour colour(Colour::ResultError);
  9326. const std::string qualify_assertions_failed =
  9327. totals.assertions.failed == totals.assertions.total() ?
  9328. bothOrAll(totals.assertions.failed) : std::string();
  9329. out <<
  9330. "Failed " << bothOrAll(totals.testCases.failed)
  9331. << pluralise(totals.testCases.failed, "test case") << ", "
  9332. "failed " << qualify_assertions_failed <<
  9333. pluralise(totals.assertions.failed, "assertion") << '.';
  9334. } else if (totals.assertions.total() == 0) {
  9335. out <<
  9336. "Passed " << bothOrAll(totals.testCases.total())
  9337. << pluralise(totals.testCases.total(), "test case")
  9338. << " (no assertions).";
  9339. } else if (totals.assertions.failed) {
  9340. Colour colour(Colour::ResultError);
  9341. out <<
  9342. "Failed " << pluralise(totals.testCases.failed, "test case") << ", "
  9343. "failed " << pluralise(totals.assertions.failed, "assertion") << '.';
  9344. } else {
  9345. Colour colour(Colour::ResultSuccess);
  9346. out <<
  9347. "Passed " << bothOrAll(totals.testCases.passed)
  9348. << pluralise(totals.testCases.passed, "test case") <<
  9349. " with " << pluralise(totals.assertions.passed, "assertion") << '.';
  9350. }
  9351. }
  9352. // Implementation of CompactReporter formatting
  9353. class AssertionPrinter {
  9354. public:
  9355. AssertionPrinter& operator= (AssertionPrinter const&) = delete;
  9356. AssertionPrinter(AssertionPrinter const&) = delete;
  9357. AssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
  9358. : stream(_stream)
  9359. , result(_stats.assertionResult)
  9360. , messages(_stats.infoMessages)
  9361. , itMessage(_stats.infoMessages.begin())
  9362. , printInfoMessages(_printInfoMessages) {}
  9363. void print() {
  9364. printSourceInfo();
  9365. itMessage = messages.begin();
  9366. switch (result.getResultType()) {
  9367. case ResultWas::Ok:
  9368. printResultType(Colour::ResultSuccess, passedString());
  9369. printOriginalExpression();
  9370. printReconstructedExpression();
  9371. if (!result.hasExpression())
  9372. printRemainingMessages(Colour::None);
  9373. else
  9374. printRemainingMessages();
  9375. break;
  9376. case ResultWas::ExpressionFailed:
  9377. if (result.isOk())
  9378. printResultType(Colour::ResultSuccess, failedString() + std::string(" - but was ok"));
  9379. else
  9380. printResultType(Colour::Error, failedString());
  9381. printOriginalExpression();
  9382. printReconstructedExpression();
  9383. printRemainingMessages();
  9384. break;
  9385. case ResultWas::ThrewException:
  9386. printResultType(Colour::Error, failedString());
  9387. printIssue("unexpected exception with message:");
  9388. printMessage();
  9389. printExpressionWas();
  9390. printRemainingMessages();
  9391. break;
  9392. case ResultWas::FatalErrorCondition:
  9393. printResultType(Colour::Error, failedString());
  9394. printIssue("fatal error condition with message:");
  9395. printMessage();
  9396. printExpressionWas();
  9397. printRemainingMessages();
  9398. break;
  9399. case ResultWas::DidntThrowException:
  9400. printResultType(Colour::Error, failedString());
  9401. printIssue("expected exception, got none");
  9402. printExpressionWas();
  9403. printRemainingMessages();
  9404. break;
  9405. case ResultWas::Info:
  9406. printResultType(Colour::None, "info");
  9407. printMessage();
  9408. printRemainingMessages();
  9409. break;
  9410. case ResultWas::Warning:
  9411. printResultType(Colour::None, "warning");
  9412. printMessage();
  9413. printRemainingMessages();
  9414. break;
  9415. case ResultWas::ExplicitFailure:
  9416. printResultType(Colour::Error, failedString());
  9417. printIssue("explicitly");
  9418. printRemainingMessages(Colour::None);
  9419. break;
  9420. // These cases are here to prevent compiler warnings
  9421. case ResultWas::Unknown:
  9422. case ResultWas::FailureBit:
  9423. case ResultWas::Exception:
  9424. printResultType(Colour::Error, "** internal error **");
  9425. break;
  9426. }
  9427. }
  9428. private:
  9429. void printSourceInfo() const {
  9430. Colour colourGuard(Colour::FileName);
  9431. stream << result.getSourceInfo() << ':';
  9432. }
  9433. void printResultType(Colour::Code colour, std::string const& passOrFail) const {
  9434. if (!passOrFail.empty()) {
  9435. {
  9436. Colour colourGuard(colour);
  9437. stream << ' ' << passOrFail;
  9438. }
  9439. stream << ':';
  9440. }
  9441. }
  9442. void printIssue(std::string const& issue) const {
  9443. stream << ' ' << issue;
  9444. }
  9445. void printExpressionWas() {
  9446. if (result.hasExpression()) {
  9447. stream << ';';
  9448. {
  9449. Colour colour(dimColour());
  9450. stream << " expression was:";
  9451. }
  9452. printOriginalExpression();
  9453. }
  9454. }
  9455. void printOriginalExpression() const {
  9456. if (result.hasExpression()) {
  9457. stream << ' ' << result.getExpression();
  9458. }
  9459. }
  9460. void printReconstructedExpression() const {
  9461. if (result.hasExpandedExpression()) {
  9462. {
  9463. Colour colour(dimColour());
  9464. stream << " for: ";
  9465. }
  9466. stream << result.getExpandedExpression();
  9467. }
  9468. }
  9469. void printMessage() {
  9470. if (itMessage != messages.end()) {
  9471. stream << " '" << itMessage->message << '\'';
  9472. ++itMessage;
  9473. }
  9474. }
  9475. void printRemainingMessages(Colour::Code colour = dimColour()) {
  9476. if (itMessage == messages.end())
  9477. return;
  9478. // using messages.end() directly yields (or auto) compilation error:
  9479. std::vector<MessageInfo>::const_iterator itEnd = messages.end();
  9480. const std::size_t N = static_cast<std::size_t>(std::distance(itMessage, itEnd));
  9481. {
  9482. Colour colourGuard(colour);
  9483. stream << " with " << pluralise(N, "message") << ':';
  9484. }
  9485. for (; itMessage != itEnd; ) {
  9486. // If this assertion is a warning ignore any INFO messages
  9487. if (printInfoMessages || itMessage->type != ResultWas::Info) {
  9488. stream << " '" << itMessage->message << '\'';
  9489. if (++itMessage != itEnd) {
  9490. Colour colourGuard(dimColour());
  9491. stream << " and";
  9492. }
  9493. }
  9494. }
  9495. }
  9496. private:
  9497. std::ostream& stream;
  9498. AssertionResult const& result;
  9499. std::vector<MessageInfo> messages;
  9500. std::vector<MessageInfo>::const_iterator itMessage;
  9501. bool printInfoMessages;
  9502. };
  9503. } // anon namespace
  9504. std::string CompactReporter::getDescription() {
  9505. return "Reports test results on a single line, suitable for IDEs";
  9506. }
  9507. ReporterPreferences CompactReporter::getPreferences() const {
  9508. ReporterPreferences prefs;
  9509. prefs.shouldRedirectStdOut = false;
  9510. return prefs;
  9511. }
  9512. void CompactReporter::noMatchingTestCases( std::string const& spec ) {
  9513. stream << "No test cases matched '" << spec << '\'' << std::endl;
  9514. }
  9515. void CompactReporter::assertionStarting( AssertionInfo const& ) {}
  9516. bool CompactReporter::assertionEnded( AssertionStats const& _assertionStats ) {
  9517. AssertionResult const& result = _assertionStats.assertionResult;
  9518. bool printInfoMessages = true;
  9519. // Drop out if result was successful and we're not printing those
  9520. if( !m_config->includeSuccessfulResults() && result.isOk() ) {
  9521. if( result.getResultType() != ResultWas::Warning )
  9522. return false;
  9523. printInfoMessages = false;
  9524. }
  9525. AssertionPrinter printer( stream, _assertionStats, printInfoMessages );
  9526. printer.print();
  9527. stream << std::endl;
  9528. return true;
  9529. }
  9530. void CompactReporter::sectionEnded(SectionStats const& _sectionStats) {
  9531. if (m_config->showDurations() == ShowDurations::Always) {
  9532. stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  9533. }
  9534. }
  9535. void CompactReporter::testRunEnded( TestRunStats const& _testRunStats ) {
  9536. printTotals( stream, _testRunStats.totals );
  9537. stream << '\n' << std::endl;
  9538. StreamingReporterBase::testRunEnded( _testRunStats );
  9539. }
  9540. CompactReporter::~CompactReporter() {}
  9541. CATCH_REGISTER_REPORTER( "compact", CompactReporter )
  9542. } // end namespace Catch
  9543. // end catch_reporter_compact.cpp
  9544. // start catch_reporter_console.cpp
  9545. #include <cfloat>
  9546. #include <cstdio>
  9547. #if defined(_MSC_VER)
  9548. #pragma warning(push)
  9549. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  9550. // Note that 4062 (not all labels are handled
  9551. // and default is missing) is enabled
  9552. #endif
  9553. namespace Catch {
  9554. namespace {
  9555. // Formatter impl for ConsoleReporter
  9556. class ConsoleAssertionPrinter {
  9557. public:
  9558. ConsoleAssertionPrinter& operator= (ConsoleAssertionPrinter const&) = delete;
  9559. ConsoleAssertionPrinter(ConsoleAssertionPrinter const&) = delete;
  9560. ConsoleAssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
  9561. : stream(_stream),
  9562. stats(_stats),
  9563. result(_stats.assertionResult),
  9564. colour(Colour::None),
  9565. message(result.getMessage()),
  9566. messages(_stats.infoMessages),
  9567. printInfoMessages(_printInfoMessages) {
  9568. switch (result.getResultType()) {
  9569. case ResultWas::Ok:
  9570. colour = Colour::Success;
  9571. passOrFail = "PASSED";
  9572. //if( result.hasMessage() )
  9573. if (_stats.infoMessages.size() == 1)
  9574. messageLabel = "with message";
  9575. if (_stats.infoMessages.size() > 1)
  9576. messageLabel = "with messages";
  9577. break;
  9578. case ResultWas::ExpressionFailed:
  9579. if (result.isOk()) {
  9580. colour = Colour::Success;
  9581. passOrFail = "FAILED - but was ok";
  9582. } else {
  9583. colour = Colour::Error;
  9584. passOrFail = "FAILED";
  9585. }
  9586. if (_stats.infoMessages.size() == 1)
  9587. messageLabel = "with message";
  9588. if (_stats.infoMessages.size() > 1)
  9589. messageLabel = "with messages";
  9590. break;
  9591. case ResultWas::ThrewException:
  9592. colour = Colour::Error;
  9593. passOrFail = "FAILED";
  9594. messageLabel = "due to unexpected exception with ";
  9595. if (_stats.infoMessages.size() == 1)
  9596. messageLabel += "message";
  9597. if (_stats.infoMessages.size() > 1)
  9598. messageLabel += "messages";
  9599. break;
  9600. case ResultWas::FatalErrorCondition:
  9601. colour = Colour::Error;
  9602. passOrFail = "FAILED";
  9603. messageLabel = "due to a fatal error condition";
  9604. break;
  9605. case ResultWas::DidntThrowException:
  9606. colour = Colour::Error;
  9607. passOrFail = "FAILED";
  9608. messageLabel = "because no exception was thrown where one was expected";
  9609. break;
  9610. case ResultWas::Info:
  9611. messageLabel = "info";
  9612. break;
  9613. case ResultWas::Warning:
  9614. messageLabel = "warning";
  9615. break;
  9616. case ResultWas::ExplicitFailure:
  9617. passOrFail = "FAILED";
  9618. colour = Colour::Error;
  9619. if (_stats.infoMessages.size() == 1)
  9620. messageLabel = "explicitly with message";
  9621. if (_stats.infoMessages.size() > 1)
  9622. messageLabel = "explicitly with messages";
  9623. break;
  9624. // These cases are here to prevent compiler warnings
  9625. case ResultWas::Unknown:
  9626. case ResultWas::FailureBit:
  9627. case ResultWas::Exception:
  9628. passOrFail = "** internal error **";
  9629. colour = Colour::Error;
  9630. break;
  9631. }
  9632. }
  9633. void print() const {
  9634. printSourceInfo();
  9635. if (stats.totals.assertions.total() > 0) {
  9636. if (result.isOk())
  9637. stream << '\n';
  9638. printResultType();
  9639. printOriginalExpression();
  9640. printReconstructedExpression();
  9641. } else {
  9642. stream << '\n';
  9643. }
  9644. printMessage();
  9645. }
  9646. private:
  9647. void printResultType() const {
  9648. if (!passOrFail.empty()) {
  9649. Colour colourGuard(colour);
  9650. stream << passOrFail << ":\n";
  9651. }
  9652. }
  9653. void printOriginalExpression() const {
  9654. if (result.hasExpression()) {
  9655. Colour colourGuard(Colour::OriginalExpression);
  9656. stream << " ";
  9657. stream << result.getExpressionInMacro();
  9658. stream << '\n';
  9659. }
  9660. }
  9661. void printReconstructedExpression() const {
  9662. if (result.hasExpandedExpression()) {
  9663. stream << "with expansion:\n";
  9664. Colour colourGuard(Colour::ReconstructedExpression);
  9665. stream << Column(result.getExpandedExpression()).indent(2) << '\n';
  9666. }
  9667. }
  9668. void printMessage() const {
  9669. if (!messageLabel.empty())
  9670. stream << messageLabel << ':' << '\n';
  9671. for (auto const& msg : messages) {
  9672. // If this assertion is a warning ignore any INFO messages
  9673. if (printInfoMessages || msg.type != ResultWas::Info)
  9674. stream << Column(msg.message).indent(2) << '\n';
  9675. }
  9676. }
  9677. void printSourceInfo() const {
  9678. Colour colourGuard(Colour::FileName);
  9679. stream << result.getSourceInfo() << ": ";
  9680. }
  9681. std::ostream& stream;
  9682. AssertionStats const& stats;
  9683. AssertionResult const& result;
  9684. Colour::Code colour;
  9685. std::string passOrFail;
  9686. std::string messageLabel;
  9687. std::string message;
  9688. std::vector<MessageInfo> messages;
  9689. bool printInfoMessages;
  9690. };
  9691. std::size_t makeRatio(std::size_t number, std::size_t total) {
  9692. std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0;
  9693. return (ratio == 0 && number > 0) ? 1 : ratio;
  9694. }
  9695. std::size_t& findMax(std::size_t& i, std::size_t& j, std::size_t& k) {
  9696. if (i > j && i > k)
  9697. return i;
  9698. else if (j > k)
  9699. return j;
  9700. else
  9701. return k;
  9702. }
  9703. struct ColumnInfo {
  9704. enum Justification { Left, Right };
  9705. std::string name;
  9706. int width;
  9707. Justification justification;
  9708. };
  9709. struct ColumnBreak {};
  9710. struct RowBreak {};
  9711. class Duration {
  9712. enum class Unit {
  9713. Auto,
  9714. Nanoseconds,
  9715. Microseconds,
  9716. Milliseconds,
  9717. Seconds,
  9718. Minutes
  9719. };
  9720. static const uint64_t s_nanosecondsInAMicrosecond = 1000;
  9721. static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond;
  9722. static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond;
  9723. static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond;
  9724. uint64_t m_inNanoseconds;
  9725. Unit m_units;
  9726. public:
  9727. explicit Duration(uint64_t inNanoseconds, Unit units = Unit::Auto)
  9728. : m_inNanoseconds(inNanoseconds),
  9729. m_units(units) {
  9730. if (m_units == Unit::Auto) {
  9731. if (m_inNanoseconds < s_nanosecondsInAMicrosecond)
  9732. m_units = Unit::Nanoseconds;
  9733. else if (m_inNanoseconds < s_nanosecondsInAMillisecond)
  9734. m_units = Unit::Microseconds;
  9735. else if (m_inNanoseconds < s_nanosecondsInASecond)
  9736. m_units = Unit::Milliseconds;
  9737. else if (m_inNanoseconds < s_nanosecondsInAMinute)
  9738. m_units = Unit::Seconds;
  9739. else
  9740. m_units = Unit::Minutes;
  9741. }
  9742. }
  9743. auto value() const -> double {
  9744. switch (m_units) {
  9745. case Unit::Microseconds:
  9746. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMicrosecond);
  9747. case Unit::Milliseconds:
  9748. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMillisecond);
  9749. case Unit::Seconds:
  9750. return m_inNanoseconds / static_cast<double>(s_nanosecondsInASecond);
  9751. case Unit::Minutes:
  9752. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMinute);
  9753. default:
  9754. return static_cast<double>(m_inNanoseconds);
  9755. }
  9756. }
  9757. auto unitsAsString() const -> std::string {
  9758. switch (m_units) {
  9759. case Unit::Nanoseconds:
  9760. return "ns";
  9761. case Unit::Microseconds:
  9762. return "µs";
  9763. case Unit::Milliseconds:
  9764. return "ms";
  9765. case Unit::Seconds:
  9766. return "s";
  9767. case Unit::Minutes:
  9768. return "m";
  9769. default:
  9770. return "** internal error **";
  9771. }
  9772. }
  9773. friend auto operator << (std::ostream& os, Duration const& duration) -> std::ostream& {
  9774. return os << duration.value() << " " << duration.unitsAsString();
  9775. }
  9776. };
  9777. } // end anon namespace
  9778. class TablePrinter {
  9779. std::ostream& m_os;
  9780. std::vector<ColumnInfo> m_columnInfos;
  9781. std::ostringstream m_oss;
  9782. int m_currentColumn = -1;
  9783. bool m_isOpen = false;
  9784. public:
  9785. TablePrinter( std::ostream& os, std::vector<ColumnInfo> columnInfos )
  9786. : m_os( os ),
  9787. m_columnInfos( std::move( columnInfos ) ) {}
  9788. auto columnInfos() const -> std::vector<ColumnInfo> const& {
  9789. return m_columnInfos;
  9790. }
  9791. void open() {
  9792. if (!m_isOpen) {
  9793. m_isOpen = true;
  9794. *this << RowBreak();
  9795. for (auto const& info : m_columnInfos)
  9796. *this << info.name << ColumnBreak();
  9797. *this << RowBreak();
  9798. m_os << Catch::getLineOfChars<'-'>() << "\n";
  9799. }
  9800. }
  9801. void close() {
  9802. if (m_isOpen) {
  9803. *this << RowBreak();
  9804. m_os << std::endl;
  9805. m_isOpen = false;
  9806. }
  9807. }
  9808. template<typename T>
  9809. friend TablePrinter& operator << (TablePrinter& tp, T const& value) {
  9810. tp.m_oss << value;
  9811. return tp;
  9812. }
  9813. friend TablePrinter& operator << (TablePrinter& tp, ColumnBreak) {
  9814. auto colStr = tp.m_oss.str();
  9815. // This takes account of utf8 encodings
  9816. auto strSize = Catch::StringRef(colStr).numberOfCharacters();
  9817. tp.m_oss.str("");
  9818. tp.open();
  9819. if (tp.m_currentColumn == static_cast<int>(tp.m_columnInfos.size() - 1)) {
  9820. tp.m_currentColumn = -1;
  9821. tp.m_os << "\n";
  9822. }
  9823. tp.m_currentColumn++;
  9824. auto colInfo = tp.m_columnInfos[tp.m_currentColumn];
  9825. auto padding = (strSize + 2 < static_cast<std::size_t>(colInfo.width))
  9826. ? std::string(colInfo.width - (strSize + 2), ' ')
  9827. : std::string();
  9828. if (colInfo.justification == ColumnInfo::Left)
  9829. tp.m_os << colStr << padding << " ";
  9830. else
  9831. tp.m_os << padding << colStr << " ";
  9832. return tp;
  9833. }
  9834. friend TablePrinter& operator << (TablePrinter& tp, RowBreak) {
  9835. if (tp.m_currentColumn > 0) {
  9836. tp.m_os << "\n";
  9837. tp.m_currentColumn = -1;
  9838. }
  9839. return tp;
  9840. }
  9841. };
  9842. ConsoleReporter::ConsoleReporter(ReporterConfig const& config)
  9843. : StreamingReporterBase(config),
  9844. m_tablePrinter(new TablePrinter(config.stream(),
  9845. {
  9846. { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 32, ColumnInfo::Left },
  9847. { "iters", 8, ColumnInfo::Right },
  9848. { "elapsed ns", 14, ColumnInfo::Right },
  9849. { "average", 14, ColumnInfo::Right }
  9850. })) {}
  9851. ConsoleReporter::~ConsoleReporter() = default;
  9852. std::string ConsoleReporter::getDescription() {
  9853. return "Reports test results as plain lines of text";
  9854. }
  9855. void ConsoleReporter::noMatchingTestCases(std::string const& spec) {
  9856. stream << "No test cases matched '" << spec << '\'' << std::endl;
  9857. }
  9858. void ConsoleReporter::assertionStarting(AssertionInfo const&) {}
  9859. bool ConsoleReporter::assertionEnded(AssertionStats const& _assertionStats) {
  9860. AssertionResult const& result = _assertionStats.assertionResult;
  9861. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  9862. // Drop out if result was successful but we're not printing them.
  9863. if (!includeResults && result.getResultType() != ResultWas::Warning)
  9864. return false;
  9865. lazyPrint();
  9866. ConsoleAssertionPrinter printer(stream, _assertionStats, includeResults);
  9867. printer.print();
  9868. stream << std::endl;
  9869. return true;
  9870. }
  9871. void ConsoleReporter::sectionStarting(SectionInfo const& _sectionInfo) {
  9872. m_headerPrinted = false;
  9873. StreamingReporterBase::sectionStarting(_sectionInfo);
  9874. }
  9875. void ConsoleReporter::sectionEnded(SectionStats const& _sectionStats) {
  9876. m_tablePrinter->close();
  9877. if (_sectionStats.missingAssertions) {
  9878. lazyPrint();
  9879. Colour colour(Colour::ResultError);
  9880. if (m_sectionStack.size() > 1)
  9881. stream << "\nNo assertions in section";
  9882. else
  9883. stream << "\nNo assertions in test case";
  9884. stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl;
  9885. }
  9886. if (m_config->showDurations() == ShowDurations::Always) {
  9887. stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  9888. }
  9889. if (m_headerPrinted) {
  9890. m_headerPrinted = false;
  9891. }
  9892. StreamingReporterBase::sectionEnded(_sectionStats);
  9893. }
  9894. void ConsoleReporter::benchmarkStarting(BenchmarkInfo const& info) {
  9895. lazyPrintWithoutClosingBenchmarkTable();
  9896. auto nameCol = Column( info.name ).width( static_cast<std::size_t>( m_tablePrinter->columnInfos()[0].width - 2 ) );
  9897. bool firstLine = true;
  9898. for (auto line : nameCol) {
  9899. if (!firstLine)
  9900. (*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak();
  9901. else
  9902. firstLine = false;
  9903. (*m_tablePrinter) << line << ColumnBreak();
  9904. }
  9905. }
  9906. void ConsoleReporter::benchmarkEnded(BenchmarkStats const& stats) {
  9907. Duration average(stats.elapsedTimeInNanoseconds / stats.iterations);
  9908. (*m_tablePrinter)
  9909. << stats.iterations << ColumnBreak()
  9910. << stats.elapsedTimeInNanoseconds << ColumnBreak()
  9911. << average << ColumnBreak();
  9912. }
  9913. void ConsoleReporter::testCaseEnded(TestCaseStats const& _testCaseStats) {
  9914. m_tablePrinter->close();
  9915. StreamingReporterBase::testCaseEnded(_testCaseStats);
  9916. m_headerPrinted = false;
  9917. }
  9918. void ConsoleReporter::testGroupEnded(TestGroupStats const& _testGroupStats) {
  9919. if (currentGroupInfo.used) {
  9920. printSummaryDivider();
  9921. stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n";
  9922. printTotals(_testGroupStats.totals);
  9923. stream << '\n' << std::endl;
  9924. }
  9925. StreamingReporterBase::testGroupEnded(_testGroupStats);
  9926. }
  9927. void ConsoleReporter::testRunEnded(TestRunStats const& _testRunStats) {
  9928. printTotalsDivider(_testRunStats.totals);
  9929. printTotals(_testRunStats.totals);
  9930. stream << std::endl;
  9931. StreamingReporterBase::testRunEnded(_testRunStats);
  9932. }
  9933. void ConsoleReporter::lazyPrint() {
  9934. m_tablePrinter->close();
  9935. lazyPrintWithoutClosingBenchmarkTable();
  9936. }
  9937. void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() {
  9938. if (!currentTestRunInfo.used)
  9939. lazyPrintRunInfo();
  9940. if (!currentGroupInfo.used)
  9941. lazyPrintGroupInfo();
  9942. if (!m_headerPrinted) {
  9943. printTestCaseAndSectionHeader();
  9944. m_headerPrinted = true;
  9945. }
  9946. }
  9947. void ConsoleReporter::lazyPrintRunInfo() {
  9948. stream << '\n' << getLineOfChars<'~'>() << '\n';
  9949. Colour colour(Colour::SecondaryText);
  9950. stream << currentTestRunInfo->name
  9951. << " is a Catch v" << libraryVersion() << " host application.\n"
  9952. << "Run with -? for options\n\n";
  9953. if (m_config->rngSeed() != 0)
  9954. stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n";
  9955. currentTestRunInfo.used = true;
  9956. }
  9957. void ConsoleReporter::lazyPrintGroupInfo() {
  9958. if (!currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1) {
  9959. printClosedHeader("Group: " + currentGroupInfo->name);
  9960. currentGroupInfo.used = true;
  9961. }
  9962. }
  9963. void ConsoleReporter::printTestCaseAndSectionHeader() {
  9964. assert(!m_sectionStack.empty());
  9965. printOpenHeader(currentTestCaseInfo->name);
  9966. if (m_sectionStack.size() > 1) {
  9967. Colour colourGuard(Colour::Headers);
  9968. auto
  9969. it = m_sectionStack.begin() + 1, // Skip first section (test case)
  9970. itEnd = m_sectionStack.end();
  9971. for (; it != itEnd; ++it)
  9972. printHeaderString(it->name, 2);
  9973. }
  9974. SourceLineInfo lineInfo = m_sectionStack.back().lineInfo;
  9975. if (!lineInfo.empty()) {
  9976. stream << getLineOfChars<'-'>() << '\n';
  9977. Colour colourGuard(Colour::FileName);
  9978. stream << lineInfo << '\n';
  9979. }
  9980. stream << getLineOfChars<'.'>() << '\n' << std::endl;
  9981. }
  9982. void ConsoleReporter::printClosedHeader(std::string const& _name) {
  9983. printOpenHeader(_name);
  9984. stream << getLineOfChars<'.'>() << '\n';
  9985. }
  9986. void ConsoleReporter::printOpenHeader(std::string const& _name) {
  9987. stream << getLineOfChars<'-'>() << '\n';
  9988. {
  9989. Colour colourGuard(Colour::Headers);
  9990. printHeaderString(_name);
  9991. }
  9992. }
  9993. // if string has a : in first line will set indent to follow it on
  9994. // subsequent lines
  9995. void ConsoleReporter::printHeaderString(std::string const& _string, std::size_t indent) {
  9996. std::size_t i = _string.find(": ");
  9997. if (i != std::string::npos)
  9998. i += 2;
  9999. else
  10000. i = 0;
  10001. stream << Column(_string).indent(indent + i).initialIndent(indent) << '\n';
  10002. }
  10003. struct SummaryColumn {
  10004. SummaryColumn( std::string _label, Colour::Code _colour )
  10005. : label( std::move( _label ) ),
  10006. colour( _colour ) {}
  10007. SummaryColumn addRow( std::size_t count ) {
  10008. ReusableStringStream rss;
  10009. rss << count;
  10010. std::string row = rss.str();
  10011. for (auto& oldRow : rows) {
  10012. while (oldRow.size() < row.size())
  10013. oldRow = ' ' + oldRow;
  10014. while (oldRow.size() > row.size())
  10015. row = ' ' + row;
  10016. }
  10017. rows.push_back(row);
  10018. return *this;
  10019. }
  10020. std::string label;
  10021. Colour::Code colour;
  10022. std::vector<std::string> rows;
  10023. };
  10024. void ConsoleReporter::printTotals( Totals const& totals ) {
  10025. if (totals.testCases.total() == 0) {
  10026. stream << Colour(Colour::Warning) << "No tests ran\n";
  10027. } else if (totals.assertions.total() > 0 && totals.testCases.allPassed()) {
  10028. stream << Colour(Colour::ResultSuccess) << "All tests passed";
  10029. stream << " ("
  10030. << pluralise(totals.assertions.passed, "assertion") << " in "
  10031. << pluralise(totals.testCases.passed, "test case") << ')'
  10032. << '\n';
  10033. } else {
  10034. std::vector<SummaryColumn> columns;
  10035. columns.push_back(SummaryColumn("", Colour::None)
  10036. .addRow(totals.testCases.total())
  10037. .addRow(totals.assertions.total()));
  10038. columns.push_back(SummaryColumn("passed", Colour::Success)
  10039. .addRow(totals.testCases.passed)
  10040. .addRow(totals.assertions.passed));
  10041. columns.push_back(SummaryColumn("failed", Colour::ResultError)
  10042. .addRow(totals.testCases.failed)
  10043. .addRow(totals.assertions.failed));
  10044. columns.push_back(SummaryColumn("failed as expected", Colour::ResultExpectedFailure)
  10045. .addRow(totals.testCases.failedButOk)
  10046. .addRow(totals.assertions.failedButOk));
  10047. printSummaryRow("test cases", columns, 0);
  10048. printSummaryRow("assertions", columns, 1);
  10049. }
  10050. }
  10051. void ConsoleReporter::printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row) {
  10052. for (auto col : cols) {
  10053. std::string value = col.rows[row];
  10054. if (col.label.empty()) {
  10055. stream << label << ": ";
  10056. if (value != "0")
  10057. stream << value;
  10058. else
  10059. stream << Colour(Colour::Warning) << "- none -";
  10060. } else if (value != "0") {
  10061. stream << Colour(Colour::LightGrey) << " | ";
  10062. stream << Colour(col.colour)
  10063. << value << ' ' << col.label;
  10064. }
  10065. }
  10066. stream << '\n';
  10067. }
  10068. void ConsoleReporter::printTotalsDivider(Totals const& totals) {
  10069. if (totals.testCases.total() > 0) {
  10070. std::size_t failedRatio = makeRatio(totals.testCases.failed, totals.testCases.total());
  10071. std::size_t failedButOkRatio = makeRatio(totals.testCases.failedButOk, totals.testCases.total());
  10072. std::size_t passedRatio = makeRatio(totals.testCases.passed, totals.testCases.total());
  10073. while (failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1)
  10074. findMax(failedRatio, failedButOkRatio, passedRatio)++;
  10075. while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1)
  10076. findMax(failedRatio, failedButOkRatio, passedRatio)--;
  10077. stream << Colour(Colour::Error) << std::string(failedRatio, '=');
  10078. stream << Colour(Colour::ResultExpectedFailure) << std::string(failedButOkRatio, '=');
  10079. if (totals.testCases.allPassed())
  10080. stream << Colour(Colour::ResultSuccess) << std::string(passedRatio, '=');
  10081. else
  10082. stream << Colour(Colour::Success) << std::string(passedRatio, '=');
  10083. } else {
  10084. stream << Colour(Colour::Warning) << std::string(CATCH_CONFIG_CONSOLE_WIDTH - 1, '=');
  10085. }
  10086. stream << '\n';
  10087. }
  10088. void ConsoleReporter::printSummaryDivider() {
  10089. stream << getLineOfChars<'-'>() << '\n';
  10090. }
  10091. CATCH_REGISTER_REPORTER("console", ConsoleReporter)
  10092. } // end namespace Catch
  10093. #if defined(_MSC_VER)
  10094. #pragma warning(pop)
  10095. #endif
  10096. // end catch_reporter_console.cpp
  10097. // start catch_reporter_junit.cpp
  10098. #include <cassert>
  10099. #include <sstream>
  10100. #include <ctime>
  10101. #include <algorithm>
  10102. namespace Catch {
  10103. namespace {
  10104. std::string getCurrentTimestamp() {
  10105. // Beware, this is not reentrant because of backward compatibility issues
  10106. // Also, UTC only, again because of backward compatibility (%z is C++11)
  10107. time_t rawtime;
  10108. std::time(&rawtime);
  10109. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  10110. #ifdef _MSC_VER
  10111. std::tm timeInfo = {};
  10112. gmtime_s(&timeInfo, &rawtime);
  10113. #else
  10114. std::tm* timeInfo;
  10115. timeInfo = std::gmtime(&rawtime);
  10116. #endif
  10117. char timeStamp[timeStampSize];
  10118. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  10119. #ifdef _MSC_VER
  10120. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  10121. #else
  10122. std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
  10123. #endif
  10124. return std::string(timeStamp);
  10125. }
  10126. std::string fileNameTag(const std::vector<std::string> &tags) {
  10127. auto it = std::find_if(begin(tags),
  10128. end(tags),
  10129. [] (std::string const& tag) {return tag.front() == '#'; });
  10130. if (it != tags.end())
  10131. return it->substr(1);
  10132. return std::string();
  10133. }
  10134. } // anonymous namespace
  10135. JunitReporter::JunitReporter( ReporterConfig const& _config )
  10136. : CumulativeReporterBase( _config ),
  10137. xml( _config.stream() )
  10138. {
  10139. m_reporterPrefs.shouldRedirectStdOut = true;
  10140. }
  10141. JunitReporter::~JunitReporter() {}
  10142. std::string JunitReporter::getDescription() {
  10143. return "Reports test results in an XML format that looks like Ant's junitreport target";
  10144. }
  10145. void JunitReporter::noMatchingTestCases( std::string const& /*spec*/ ) {}
  10146. void JunitReporter::testRunStarting( TestRunInfo const& runInfo ) {
  10147. CumulativeReporterBase::testRunStarting( runInfo );
  10148. xml.startElement( "testsuites" );
  10149. }
  10150. void JunitReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  10151. suiteTimer.start();
  10152. stdOutForSuite.clear();
  10153. stdErrForSuite.clear();
  10154. unexpectedExceptions = 0;
  10155. CumulativeReporterBase::testGroupStarting( groupInfo );
  10156. }
  10157. void JunitReporter::testCaseStarting( TestCaseInfo const& testCaseInfo ) {
  10158. m_okToFail = testCaseInfo.okToFail();
  10159. }
  10160. bool JunitReporter::assertionEnded( AssertionStats const& assertionStats ) {
  10161. if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail )
  10162. unexpectedExceptions++;
  10163. return CumulativeReporterBase::assertionEnded( assertionStats );
  10164. }
  10165. void JunitReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  10166. stdOutForSuite += testCaseStats.stdOut;
  10167. stdErrForSuite += testCaseStats.stdErr;
  10168. CumulativeReporterBase::testCaseEnded( testCaseStats );
  10169. }
  10170. void JunitReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  10171. double suiteTime = suiteTimer.getElapsedSeconds();
  10172. CumulativeReporterBase::testGroupEnded( testGroupStats );
  10173. writeGroup( *m_testGroups.back(), suiteTime );
  10174. }
  10175. void JunitReporter::testRunEndedCumulative() {
  10176. xml.endElement();
  10177. }
  10178. void JunitReporter::writeGroup( TestGroupNode const& groupNode, double suiteTime ) {
  10179. XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" );
  10180. TestGroupStats const& stats = groupNode.value;
  10181. xml.writeAttribute( "name", stats.groupInfo.name );
  10182. xml.writeAttribute( "errors", unexpectedExceptions );
  10183. xml.writeAttribute( "failures", stats.totals.assertions.failed-unexpectedExceptions );
  10184. xml.writeAttribute( "tests", stats.totals.assertions.total() );
  10185. xml.writeAttribute( "hostname", "tbd" ); // !TBD
  10186. if( m_config->showDurations() == ShowDurations::Never )
  10187. xml.writeAttribute( "time", "" );
  10188. else
  10189. xml.writeAttribute( "time", suiteTime );
  10190. xml.writeAttribute( "timestamp", getCurrentTimestamp() );
  10191. // Write test cases
  10192. for( auto const& child : groupNode.children )
  10193. writeTestCase( *child );
  10194. xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite ), false );
  10195. xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite ), false );
  10196. }
  10197. void JunitReporter::writeTestCase( TestCaseNode const& testCaseNode ) {
  10198. TestCaseStats const& stats = testCaseNode.value;
  10199. // All test cases have exactly one section - which represents the
  10200. // test case itself. That section may have 0-n nested sections
  10201. assert( testCaseNode.children.size() == 1 );
  10202. SectionNode const& rootSection = *testCaseNode.children.front();
  10203. std::string className = stats.testInfo.className;
  10204. if( className.empty() ) {
  10205. className = fileNameTag(stats.testInfo.tags);
  10206. if ( className.empty() )
  10207. className = "global";
  10208. }
  10209. if ( !m_config->name().empty() )
  10210. className = m_config->name() + "." + className;
  10211. writeSection( className, "", rootSection );
  10212. }
  10213. void JunitReporter::writeSection( std::string const& className,
  10214. std::string const& rootName,
  10215. SectionNode const& sectionNode ) {
  10216. std::string name = trim( sectionNode.stats.sectionInfo.name );
  10217. if( !rootName.empty() )
  10218. name = rootName + '/' + name;
  10219. if( !sectionNode.assertions.empty() ||
  10220. !sectionNode.stdOut.empty() ||
  10221. !sectionNode.stdErr.empty() ) {
  10222. XmlWriter::ScopedElement e = xml.scopedElement( "testcase" );
  10223. if( className.empty() ) {
  10224. xml.writeAttribute( "classname", name );
  10225. xml.writeAttribute( "name", "root" );
  10226. }
  10227. else {
  10228. xml.writeAttribute( "classname", className );
  10229. xml.writeAttribute( "name", name );
  10230. }
  10231. xml.writeAttribute( "time", ::Catch::Detail::stringify( sectionNode.stats.durationInSeconds ) );
  10232. writeAssertions( sectionNode );
  10233. if( !sectionNode.stdOut.empty() )
  10234. xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), false );
  10235. if( !sectionNode.stdErr.empty() )
  10236. xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), false );
  10237. }
  10238. for( auto const& childNode : sectionNode.childSections )
  10239. if( className.empty() )
  10240. writeSection( name, "", *childNode );
  10241. else
  10242. writeSection( className, name, *childNode );
  10243. }
  10244. void JunitReporter::writeAssertions( SectionNode const& sectionNode ) {
  10245. for( auto const& assertion : sectionNode.assertions )
  10246. writeAssertion( assertion );
  10247. }
  10248. void JunitReporter::writeAssertion( AssertionStats const& stats ) {
  10249. AssertionResult const& result = stats.assertionResult;
  10250. if( !result.isOk() ) {
  10251. std::string elementName;
  10252. switch( result.getResultType() ) {
  10253. case ResultWas::ThrewException:
  10254. case ResultWas::FatalErrorCondition:
  10255. elementName = "error";
  10256. break;
  10257. case ResultWas::ExplicitFailure:
  10258. elementName = "failure";
  10259. break;
  10260. case ResultWas::ExpressionFailed:
  10261. elementName = "failure";
  10262. break;
  10263. case ResultWas::DidntThrowException:
  10264. elementName = "failure";
  10265. break;
  10266. // We should never see these here:
  10267. case ResultWas::Info:
  10268. case ResultWas::Warning:
  10269. case ResultWas::Ok:
  10270. case ResultWas::Unknown:
  10271. case ResultWas::FailureBit:
  10272. case ResultWas::Exception:
  10273. elementName = "internalError";
  10274. break;
  10275. }
  10276. XmlWriter::ScopedElement e = xml.scopedElement( elementName );
  10277. xml.writeAttribute( "message", result.getExpandedExpression() );
  10278. xml.writeAttribute( "type", result.getTestMacroName() );
  10279. ReusableStringStream rss;
  10280. if( !result.getMessage().empty() )
  10281. rss << result.getMessage() << '\n';
  10282. for( auto const& msg : stats.infoMessages )
  10283. if( msg.type == ResultWas::Info )
  10284. rss << msg.message << '\n';
  10285. rss << "at " << result.getSourceInfo();
  10286. xml.writeText( rss.str(), false );
  10287. }
  10288. }
  10289. CATCH_REGISTER_REPORTER( "junit", JunitReporter )
  10290. } // end namespace Catch
  10291. // end catch_reporter_junit.cpp
  10292. // start catch_reporter_listening.cpp
  10293. #include <cassert>
  10294. namespace Catch {
  10295. void ListeningReporter::addListener( IStreamingReporterPtr&& listener ) {
  10296. m_listeners.push_back( std::move( listener ) );
  10297. }
  10298. void ListeningReporter::addReporter(IStreamingReporterPtr&& reporter) {
  10299. assert(!m_reporter && "Listening reporter can wrap only 1 real reporter");
  10300. m_reporter = std::move( reporter );
  10301. }
  10302. ReporterPreferences ListeningReporter::getPreferences() const {
  10303. return m_reporter->getPreferences();
  10304. }
  10305. std::set<Verbosity> ListeningReporter::getSupportedVerbosities() {
  10306. return std::set<Verbosity>{ };
  10307. }
  10308. void ListeningReporter::noMatchingTestCases( std::string const& spec ) {
  10309. for ( auto const& listener : m_listeners ) {
  10310. listener->noMatchingTestCases( spec );
  10311. }
  10312. m_reporter->noMatchingTestCases( spec );
  10313. }
  10314. void ListeningReporter::benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) {
  10315. for ( auto const& listener : m_listeners ) {
  10316. listener->benchmarkStarting( benchmarkInfo );
  10317. }
  10318. m_reporter->benchmarkStarting( benchmarkInfo );
  10319. }
  10320. void ListeningReporter::benchmarkEnded( BenchmarkStats const& benchmarkStats ) {
  10321. for ( auto const& listener : m_listeners ) {
  10322. listener->benchmarkEnded( benchmarkStats );
  10323. }
  10324. m_reporter->benchmarkEnded( benchmarkStats );
  10325. }
  10326. void ListeningReporter::testRunStarting( TestRunInfo const& testRunInfo ) {
  10327. for ( auto const& listener : m_listeners ) {
  10328. listener->testRunStarting( testRunInfo );
  10329. }
  10330. m_reporter->testRunStarting( testRunInfo );
  10331. }
  10332. void ListeningReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  10333. for ( auto const& listener : m_listeners ) {
  10334. listener->testGroupStarting( groupInfo );
  10335. }
  10336. m_reporter->testGroupStarting( groupInfo );
  10337. }
  10338. void ListeningReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
  10339. for ( auto const& listener : m_listeners ) {
  10340. listener->testCaseStarting( testInfo );
  10341. }
  10342. m_reporter->testCaseStarting( testInfo );
  10343. }
  10344. void ListeningReporter::sectionStarting( SectionInfo const& sectionInfo ) {
  10345. for ( auto const& listener : m_listeners ) {
  10346. listener->sectionStarting( sectionInfo );
  10347. }
  10348. m_reporter->sectionStarting( sectionInfo );
  10349. }
  10350. void ListeningReporter::assertionStarting( AssertionInfo const& assertionInfo ) {
  10351. for ( auto const& listener : m_listeners ) {
  10352. listener->assertionStarting( assertionInfo );
  10353. }
  10354. m_reporter->assertionStarting( assertionInfo );
  10355. }
  10356. // The return value indicates if the messages buffer should be cleared:
  10357. bool ListeningReporter::assertionEnded( AssertionStats const& assertionStats ) {
  10358. for( auto const& listener : m_listeners ) {
  10359. static_cast<void>( listener->assertionEnded( assertionStats ) );
  10360. }
  10361. return m_reporter->assertionEnded( assertionStats );
  10362. }
  10363. void ListeningReporter::sectionEnded( SectionStats const& sectionStats ) {
  10364. for ( auto const& listener : m_listeners ) {
  10365. listener->sectionEnded( sectionStats );
  10366. }
  10367. m_reporter->sectionEnded( sectionStats );
  10368. }
  10369. void ListeningReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  10370. for ( auto const& listener : m_listeners ) {
  10371. listener->testCaseEnded( testCaseStats );
  10372. }
  10373. m_reporter->testCaseEnded( testCaseStats );
  10374. }
  10375. void ListeningReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  10376. for ( auto const& listener : m_listeners ) {
  10377. listener->testGroupEnded( testGroupStats );
  10378. }
  10379. m_reporter->testGroupEnded( testGroupStats );
  10380. }
  10381. void ListeningReporter::testRunEnded( TestRunStats const& testRunStats ) {
  10382. for ( auto const& listener : m_listeners ) {
  10383. listener->testRunEnded( testRunStats );
  10384. }
  10385. m_reporter->testRunEnded( testRunStats );
  10386. }
  10387. void ListeningReporter::skipTest( TestCaseInfo const& testInfo ) {
  10388. for ( auto const& listener : m_listeners ) {
  10389. listener->skipTest( testInfo );
  10390. }
  10391. m_reporter->skipTest( testInfo );
  10392. }
  10393. bool ListeningReporter::isMulti() const {
  10394. return true;
  10395. }
  10396. } // end namespace Catch
  10397. // end catch_reporter_listening.cpp
  10398. // start catch_reporter_xml.cpp
  10399. #if defined(_MSC_VER)
  10400. #pragma warning(push)
  10401. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  10402. // Note that 4062 (not all labels are handled
  10403. // and default is missing) is enabled
  10404. #endif
  10405. namespace Catch {
  10406. XmlReporter::XmlReporter( ReporterConfig const& _config )
  10407. : StreamingReporterBase( _config ),
  10408. m_xml(_config.stream())
  10409. {
  10410. m_reporterPrefs.shouldRedirectStdOut = true;
  10411. }
  10412. XmlReporter::~XmlReporter() = default;
  10413. std::string XmlReporter::getDescription() {
  10414. return "Reports test results as an XML document";
  10415. }
  10416. std::string XmlReporter::getStylesheetRef() const {
  10417. return std::string();
  10418. }
  10419. void XmlReporter::writeSourceInfo( SourceLineInfo const& sourceInfo ) {
  10420. m_xml
  10421. .writeAttribute( "filename", sourceInfo.file )
  10422. .writeAttribute( "line", sourceInfo.line );
  10423. }
  10424. void XmlReporter::noMatchingTestCases( std::string const& s ) {
  10425. StreamingReporterBase::noMatchingTestCases( s );
  10426. }
  10427. void XmlReporter::testRunStarting( TestRunInfo const& testInfo ) {
  10428. StreamingReporterBase::testRunStarting( testInfo );
  10429. std::string stylesheetRef = getStylesheetRef();
  10430. if( !stylesheetRef.empty() )
  10431. m_xml.writeStylesheetRef( stylesheetRef );
  10432. m_xml.startElement( "Catch" );
  10433. if( !m_config->name().empty() )
  10434. m_xml.writeAttribute( "name", m_config->name() );
  10435. }
  10436. void XmlReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  10437. StreamingReporterBase::testGroupStarting( groupInfo );
  10438. m_xml.startElement( "Group" )
  10439. .writeAttribute( "name", groupInfo.name );
  10440. }
  10441. void XmlReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
  10442. StreamingReporterBase::testCaseStarting(testInfo);
  10443. m_xml.startElement( "TestCase" )
  10444. .writeAttribute( "name", trim( testInfo.name ) )
  10445. .writeAttribute( "description", testInfo.description )
  10446. .writeAttribute( "tags", testInfo.tagsAsString() );
  10447. writeSourceInfo( testInfo.lineInfo );
  10448. if ( m_config->showDurations() == ShowDurations::Always )
  10449. m_testCaseTimer.start();
  10450. m_xml.ensureTagClosed();
  10451. }
  10452. void XmlReporter::sectionStarting( SectionInfo const& sectionInfo ) {
  10453. StreamingReporterBase::sectionStarting( sectionInfo );
  10454. if( m_sectionDepth++ > 0 ) {
  10455. m_xml.startElement( "Section" )
  10456. .writeAttribute( "name", trim( sectionInfo.name ) )
  10457. .writeAttribute( "description", sectionInfo.description );
  10458. writeSourceInfo( sectionInfo.lineInfo );
  10459. m_xml.ensureTagClosed();
  10460. }
  10461. }
  10462. void XmlReporter::assertionStarting( AssertionInfo const& ) { }
  10463. bool XmlReporter::assertionEnded( AssertionStats const& assertionStats ) {
  10464. AssertionResult const& result = assertionStats.assertionResult;
  10465. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  10466. if( includeResults || result.getResultType() == ResultWas::Warning ) {
  10467. // Print any info messages in <Info> tags.
  10468. for( auto const& msg : assertionStats.infoMessages ) {
  10469. if( msg.type == ResultWas::Info && includeResults ) {
  10470. m_xml.scopedElement( "Info" )
  10471. .writeText( msg.message );
  10472. } else if ( msg.type == ResultWas::Warning ) {
  10473. m_xml.scopedElement( "Warning" )
  10474. .writeText( msg.message );
  10475. }
  10476. }
  10477. }
  10478. // Drop out if result was successful but we're not printing them.
  10479. if( !includeResults && result.getResultType() != ResultWas::Warning )
  10480. return true;
  10481. // Print the expression if there is one.
  10482. if( result.hasExpression() ) {
  10483. m_xml.startElement( "Expression" )
  10484. .writeAttribute( "success", result.succeeded() )
  10485. .writeAttribute( "type", result.getTestMacroName() );
  10486. writeSourceInfo( result.getSourceInfo() );
  10487. m_xml.scopedElement( "Original" )
  10488. .writeText( result.getExpression() );
  10489. m_xml.scopedElement( "Expanded" )
  10490. .writeText( result.getExpandedExpression() );
  10491. }
  10492. // And... Print a result applicable to each result type.
  10493. switch( result.getResultType() ) {
  10494. case ResultWas::ThrewException:
  10495. m_xml.startElement( "Exception" );
  10496. writeSourceInfo( result.getSourceInfo() );
  10497. m_xml.writeText( result.getMessage() );
  10498. m_xml.endElement();
  10499. break;
  10500. case ResultWas::FatalErrorCondition:
  10501. m_xml.startElement( "FatalErrorCondition" );
  10502. writeSourceInfo( result.getSourceInfo() );
  10503. m_xml.writeText( result.getMessage() );
  10504. m_xml.endElement();
  10505. break;
  10506. case ResultWas::Info:
  10507. m_xml.scopedElement( "Info" )
  10508. .writeText( result.getMessage() );
  10509. break;
  10510. case ResultWas::Warning:
  10511. // Warning will already have been written
  10512. break;
  10513. case ResultWas::ExplicitFailure:
  10514. m_xml.startElement( "Failure" );
  10515. writeSourceInfo( result.getSourceInfo() );
  10516. m_xml.writeText( result.getMessage() );
  10517. m_xml.endElement();
  10518. break;
  10519. default:
  10520. break;
  10521. }
  10522. if( result.hasExpression() )
  10523. m_xml.endElement();
  10524. return true;
  10525. }
  10526. void XmlReporter::sectionEnded( SectionStats const& sectionStats ) {
  10527. StreamingReporterBase::sectionEnded( sectionStats );
  10528. if( --m_sectionDepth > 0 ) {
  10529. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResults" );
  10530. e.writeAttribute( "successes", sectionStats.assertions.passed );
  10531. e.writeAttribute( "failures", sectionStats.assertions.failed );
  10532. e.writeAttribute( "expectedFailures", sectionStats.assertions.failedButOk );
  10533. if ( m_config->showDurations() == ShowDurations::Always )
  10534. e.writeAttribute( "durationInSeconds", sectionStats.durationInSeconds );
  10535. m_xml.endElement();
  10536. }
  10537. }
  10538. void XmlReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  10539. StreamingReporterBase::testCaseEnded( testCaseStats );
  10540. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResult" );
  10541. e.writeAttribute( "success", testCaseStats.totals.assertions.allOk() );
  10542. if ( m_config->showDurations() == ShowDurations::Always )
  10543. e.writeAttribute( "durationInSeconds", m_testCaseTimer.getElapsedSeconds() );
  10544. if( !testCaseStats.stdOut.empty() )
  10545. m_xml.scopedElement( "StdOut" ).writeText( trim( testCaseStats.stdOut ), false );
  10546. if( !testCaseStats.stdErr.empty() )
  10547. m_xml.scopedElement( "StdErr" ).writeText( trim( testCaseStats.stdErr ), false );
  10548. m_xml.endElement();
  10549. }
  10550. void XmlReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  10551. StreamingReporterBase::testGroupEnded( testGroupStats );
  10552. // TODO: Check testGroupStats.aborting and act accordingly.
  10553. m_xml.scopedElement( "OverallResults" )
  10554. .writeAttribute( "successes", testGroupStats.totals.assertions.passed )
  10555. .writeAttribute( "failures", testGroupStats.totals.assertions.failed )
  10556. .writeAttribute( "expectedFailures", testGroupStats.totals.assertions.failedButOk );
  10557. m_xml.endElement();
  10558. }
  10559. void XmlReporter::testRunEnded( TestRunStats const& testRunStats ) {
  10560. StreamingReporterBase::testRunEnded( testRunStats );
  10561. m_xml.scopedElement( "OverallResults" )
  10562. .writeAttribute( "successes", testRunStats.totals.assertions.passed )
  10563. .writeAttribute( "failures", testRunStats.totals.assertions.failed )
  10564. .writeAttribute( "expectedFailures", testRunStats.totals.assertions.failedButOk );
  10565. m_xml.endElement();
  10566. }
  10567. CATCH_REGISTER_REPORTER( "xml", XmlReporter )
  10568. } // end namespace Catch
  10569. #if defined(_MSC_VER)
  10570. #pragma warning(pop)
  10571. #endif
  10572. // end catch_reporter_xml.cpp
  10573. namespace Catch {
  10574. LeakDetector leakDetector;
  10575. }
  10576. #ifdef __clang__
  10577. #pragma clang diagnostic pop
  10578. #endif
  10579. // end catch_impl.hpp
  10580. #endif
  10581. #ifdef CATCH_CONFIG_MAIN
  10582. // start catch_default_main.hpp
  10583. #ifndef __OBJC__
  10584. #if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN)
  10585. // Standard C/C++ Win32 Unicode wmain entry point
  10586. extern "C" int wmain (int argc, wchar_t * argv[], wchar_t * []) {
  10587. #else
  10588. // Standard C/C++ main entry point
  10589. int main (int argc, char * argv[]) {
  10590. #endif
  10591. return Catch::Session().run( argc, argv );
  10592. }
  10593. #else // __OBJC__
  10594. // Objective-C entry point
  10595. int main (int argc, char * const argv[]) {
  10596. #if !CATCH_ARC_ENABLED
  10597. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  10598. #endif
  10599. Catch::registerTestMethods();
  10600. int result = Catch::Session().run( argc, (char**)argv );
  10601. #if !CATCH_ARC_ENABLED
  10602. [pool drain];
  10603. #endif
  10604. return result;
  10605. }
  10606. #endif // __OBJC__
  10607. // end catch_default_main.hpp
  10608. #endif
  10609. #if !defined(CATCH_CONFIG_IMPL_ONLY)
  10610. #ifdef CLARA_CONFIG_MAIN_NOT_DEFINED
  10611. # undef CLARA_CONFIG_MAIN
  10612. #endif
  10613. #if !defined(CATCH_CONFIG_DISABLE)
  10614. //////
  10615. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  10616. #ifdef CATCH_CONFIG_PREFIX_ALL
  10617. #define CATCH_REQUIRE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  10618. #define CATCH_REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  10619. #define CATCH_REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, "", __VA_ARGS__ )
  10620. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  10621. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  10622. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10623. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  10624. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  10625. #define CATCH_REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  10626. #define CATCH_CHECK( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10627. #define CATCH_CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  10628. #define CATCH_CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10629. #define CATCH_CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10630. #define CATCH_CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  10631. #define CATCH_CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, "", __VA_ARGS__ )
  10632. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  10633. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  10634. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10635. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  10636. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10637. #define CATCH_CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10638. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10639. #define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  10640. #define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  10641. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10642. #define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg )
  10643. #define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  10644. #define CATCH_CAPTURE( msg ) INTERNAL_CATCH_INFO( "CATCH_CAPTURE", #msg " := " << ::Catch::Detail::stringify(msg) )
  10645. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  10646. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  10647. #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  10648. #define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  10649. #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  10650. #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  10651. #define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10652. #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10653. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  10654. // "BDD-style" convenience wrappers
  10655. #define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ )
  10656. #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  10657. #define CATCH_GIVEN( desc ) CATCH_SECTION( std::string( "Given: ") + desc )
  10658. #define CATCH_WHEN( desc ) CATCH_SECTION( std::string( " When: ") + desc )
  10659. #define CATCH_AND_WHEN( desc ) CATCH_SECTION( std::string( " And: ") + desc )
  10660. #define CATCH_THEN( desc ) CATCH_SECTION( std::string( " Then: ") + desc )
  10661. #define CATCH_AND_THEN( desc ) CATCH_SECTION( std::string( " And: ") + desc )
  10662. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  10663. #else
  10664. #define REQUIRE( ... ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  10665. #define REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  10666. #define REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  10667. #define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  10668. #define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  10669. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10670. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  10671. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10672. #define REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  10673. #define CHECK( ... ) INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10674. #define CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  10675. #define CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10676. #define CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10677. #define CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  10678. #define CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10679. #define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  10680. #define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  10681. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10682. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  10683. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10684. #define CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10685. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10686. #define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  10687. #define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  10688. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10689. #define INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg )
  10690. #define WARN( msg ) INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  10691. #define CAPTURE( msg ) INTERNAL_CATCH_INFO( "CAPTURE", #msg " := " << ::Catch::Detail::stringify(msg) )
  10692. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  10693. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  10694. #define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  10695. #define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  10696. #define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  10697. #define FAIL( ... ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  10698. #define FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10699. #define SUCCEED( ... ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10700. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  10701. #endif
  10702. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature )
  10703. // "BDD-style" convenience wrappers
  10704. #define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ )
  10705. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  10706. #define GIVEN( desc ) SECTION( std::string(" Given: ") + desc )
  10707. #define WHEN( desc ) SECTION( std::string(" When: ") + desc )
  10708. #define AND_WHEN( desc ) SECTION( std::string("And when: ") + desc )
  10709. #define THEN( desc ) SECTION( std::string(" Then: ") + desc )
  10710. #define AND_THEN( desc ) SECTION( std::string(" And: ") + desc )
  10711. using Catch::Detail::Approx;
  10712. #else
  10713. //////
  10714. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  10715. #ifdef CATCH_CONFIG_PREFIX_ALL
  10716. #define CATCH_REQUIRE( ... ) (void)(0)
  10717. #define CATCH_REQUIRE_FALSE( ... ) (void)(0)
  10718. #define CATCH_REQUIRE_THROWS( ... ) (void)(0)
  10719. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  10720. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  10721. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10722. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  10723. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  10724. #define CATCH_REQUIRE_NOTHROW( ... ) (void)(0)
  10725. #define CATCH_CHECK( ... ) (void)(0)
  10726. #define CATCH_CHECK_FALSE( ... ) (void)(0)
  10727. #define CATCH_CHECKED_IF( ... ) if (__VA_ARGS__)
  10728. #define CATCH_CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  10729. #define CATCH_CHECK_NOFAIL( ... ) (void)(0)
  10730. #define CATCH_CHECK_THROWS( ... ) (void)(0)
  10731. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  10732. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  10733. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10734. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  10735. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10736. #define CATCH_CHECK_NOTHROW( ... ) (void)(0)
  10737. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10738. #define CATCH_CHECK_THAT( arg, matcher ) (void)(0)
  10739. #define CATCH_REQUIRE_THAT( arg, matcher ) (void)(0)
  10740. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10741. #define CATCH_INFO( msg ) (void)(0)
  10742. #define CATCH_WARN( msg ) (void)(0)
  10743. #define CATCH_CAPTURE( msg ) (void)(0)
  10744. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  10745. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  10746. #define CATCH_METHOD_AS_TEST_CASE( method, ... )
  10747. #define CATCH_REGISTER_TEST_CASE( Function, ... ) (void)(0)
  10748. #define CATCH_SECTION( ... )
  10749. #define CATCH_FAIL( ... ) (void)(0)
  10750. #define CATCH_FAIL_CHECK( ... ) (void)(0)
  10751. #define CATCH_SUCCEED( ... ) (void)(0)
  10752. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  10753. // "BDD-style" convenience wrappers
  10754. #define CATCH_SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  10755. #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 )
  10756. #define CATCH_GIVEN( desc )
  10757. #define CATCH_WHEN( desc )
  10758. #define CATCH_AND_WHEN( desc )
  10759. #define CATCH_THEN( desc )
  10760. #define CATCH_AND_THEN( desc )
  10761. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  10762. #else
  10763. #define REQUIRE( ... ) (void)(0)
  10764. #define REQUIRE_FALSE( ... ) (void)(0)
  10765. #define REQUIRE_THROWS( ... ) (void)(0)
  10766. #define REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  10767. #define REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  10768. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10769. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  10770. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10771. #define REQUIRE_NOTHROW( ... ) (void)(0)
  10772. #define CHECK( ... ) (void)(0)
  10773. #define CHECK_FALSE( ... ) (void)(0)
  10774. #define CHECKED_IF( ... ) if (__VA_ARGS__)
  10775. #define CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  10776. #define CHECK_NOFAIL( ... ) (void)(0)
  10777. #define CHECK_THROWS( ... ) (void)(0)
  10778. #define CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  10779. #define CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  10780. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10781. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  10782. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10783. #define CHECK_NOTHROW( ... ) (void)(0)
  10784. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10785. #define CHECK_THAT( arg, matcher ) (void)(0)
  10786. #define REQUIRE_THAT( arg, matcher ) (void)(0)
  10787. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10788. #define INFO( msg ) (void)(0)
  10789. #define WARN( msg ) (void)(0)
  10790. #define CAPTURE( msg ) (void)(0)
  10791. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  10792. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  10793. #define METHOD_AS_TEST_CASE( method, ... )
  10794. #define REGISTER_TEST_CASE( Function, ... ) (void)(0)
  10795. #define SECTION( ... )
  10796. #define FAIL( ... ) (void)(0)
  10797. #define FAIL_CHECK( ... ) (void)(0)
  10798. #define SUCCEED( ... ) (void)(0)
  10799. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  10800. #endif
  10801. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
  10802. // "BDD-style" convenience wrappers
  10803. #define SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) )
  10804. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className )
  10805. #define GIVEN( desc )
  10806. #define WHEN( desc )
  10807. #define AND_WHEN( desc )
  10808. #define THEN( desc )
  10809. #define AND_THEN( desc )
  10810. using Catch::Detail::Approx;
  10811. #endif
  10812. #endif // ! CATCH_CONFIG_IMPL_ONLY
  10813. // start catch_reenable_warnings.h
  10814. #ifdef __clang__
  10815. # ifdef __ICC // icpc defines the __clang__ macro
  10816. # pragma warning(pop)
  10817. # else
  10818. # pragma clang diagnostic pop
  10819. # endif
  10820. #elif defined __GNUC__
  10821. # pragma GCC diagnostic pop
  10822. #endif
  10823. // end catch_reenable_warnings.h
  10824. // end catch.hpp
  10825. #endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED