You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

пре 6 година
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012
  1. /*
  2. * Catch v2.0.1
  3. * Generated: 2017-11-03 11:53:39.642003
  4. * ----------------------------------------------------------
  5. * This file has been merged from multiple headers. Please don't edit it directly
  6. * Copyright (c) 2017 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. #ifdef __clang__
  15. # pragma clang system_header
  16. #elif defined __GNUC__
  17. # pragma GCC system_header
  18. #endif
  19. // start catch_suppress_warnings.h
  20. #ifdef __clang__
  21. # ifdef __ICC // icpc defines the __clang__ macro
  22. # pragma warning(push)
  23. # pragma warning(disable: 161 1682)
  24. # else // __ICC
  25. # pragma clang diagnostic ignored "-Wglobal-constructors"
  26. # pragma clang diagnostic ignored "-Wvariadic-macros"
  27. # pragma clang diagnostic ignored "-Wc99-extensions"
  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 "-Wvariadic-macros"
  36. # pragma GCC diagnostic ignored "-Wunused-variable"
  37. # pragma GCC diagnostic ignored "-Wparentheses"
  38. # pragma GCC diagnostic push
  39. # pragma GCC diagnostic ignored "-Wpadded"
  40. #endif
  41. // end catch_suppress_warnings.h
  42. #if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER)
  43. # define CATCH_IMPL
  44. # define CATCH_CONFIG_EXTERNAL_INTERFACES
  45. # if defined(CATCH_CONFIG_DISABLE_MATCHERS)
  46. # undef CATCH_CONFIG_DISABLE_MATCHERS
  47. # endif
  48. #endif
  49. // start catch_platform.h
  50. #ifdef __APPLE__
  51. # include <TargetConditionals.h>
  52. # if TARGET_OS_MAC == 1
  53. # define CATCH_PLATFORM_MAC
  54. # elif TARGET_OS_IPHONE == 1
  55. # define CATCH_PLATFORM_IPHONE
  56. # endif
  57. #elif defined(linux) || defined(__linux) || defined(__linux__)
  58. # define CATCH_PLATFORM_LINUX
  59. #elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER)
  60. # define CATCH_PLATFORM_WINDOWS
  61. #endif
  62. // end catch_platform.h
  63. #ifdef CATCH_IMPL
  64. # ifndef CLARA_CONFIG_MAIN
  65. # define CLARA_CONFIG_MAIN_NOT_DEFINED
  66. # define CLARA_CONFIG_MAIN
  67. # endif
  68. #endif
  69. // start catch_tag_alias_autoregistrar.h
  70. // start catch_common.h
  71. // start catch_compiler_capabilities.h
  72. // Detect a number of compiler features - by compiler
  73. // The following features are defined:
  74. //
  75. // CATCH_CONFIG_COUNTER : is the __COUNTER__ macro supported?
  76. // CATCH_CONFIG_WINDOWS_SEH : is Windows SEH supported?
  77. // CATCH_CONFIG_POSIX_SIGNALS : are POSIX signals supported?
  78. // ****************
  79. // Note to maintainers: if new toggles are added please document them
  80. // in configuration.md, too
  81. // ****************
  82. // In general each macro has a _NO_<feature name> form
  83. // (e.g. CATCH_CONFIG_NO_POSIX_SIGNALS) which disables the feature.
  84. // Many features, at point of detection, define an _INTERNAL_ macro, so they
  85. // can be combined, en-mass, with the _NO_ forms later.
  86. #ifdef __cplusplus
  87. # if __cplusplus >= 201402L
  88. # define CATCH_CPP14_OR_GREATER
  89. # endif
  90. #endif
  91. #ifdef __clang__
  92. # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  93. _Pragma( "clang diagnostic push" ) \
  94. _Pragma( "clang diagnostic ignored \"-Wexit-time-destructors\"" ) \
  95. _Pragma( "clang diagnostic ignored \"-Wglobal-constructors\"")
  96. # define CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  97. _Pragma( "clang diagnostic pop" )
  98. # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
  99. _Pragma( "clang diagnostic push" ) \
  100. _Pragma( "clang diagnostic ignored \"-Wparentheses\"" )
  101. # define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
  102. _Pragma( "clang diagnostic pop" )
  103. #endif // __clang__
  104. ////////////////////////////////////////////////////////////////////////////////
  105. // We know some environments not to support full POSIX signals
  106. #if defined(__CYGWIN__) || defined(__QNX__)
  107. # if !defined(CATCH_CONFIG_POSIX_SIGNALS)
  108. # define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
  109. # endif
  110. #endif
  111. #ifdef __OS400__
  112. # define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
  113. # define CATCH_CONFIG_COLOUR_NONE
  114. #endif
  115. ////////////////////////////////////////////////////////////////////////////////
  116. // Cygwin
  117. #ifdef __CYGWIN__
  118. // Required for some versions of Cygwin to declare gettimeofday
  119. // see: http://stackoverflow.com/questions/36901803/gettimeofday-not-declared-in-this-scope-cygwin
  120. # define _BSD_SOURCE
  121. #endif // __CYGWIN__
  122. ////////////////////////////////////////////////////////////////////////////////
  123. // Visual C++
  124. #ifdef _MSC_VER
  125. // Universal Windows platform does not support SEH
  126. // Or console colours (or console at all...)
  127. # if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP)
  128. # define CATCH_CONFIG_COLOUR_NONE
  129. # else
  130. # define CATCH_INTERNAL_CONFIG_WINDOWS_SEH
  131. # endif
  132. #endif // _MSC_VER
  133. ////////////////////////////////////////////////////////////////////////////////
  134. // Use of __COUNTER__ is suppressed during code analysis in
  135. // CLion/AppCode 2017.2.x and former, because __COUNTER__ is not properly
  136. // handled by it.
  137. // Otherwise all supported compilers support COUNTER macro,
  138. // but user still might want to turn it off
  139. #if ( !defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L )
  140. #define CATCH_INTERNAL_CONFIG_COUNTER
  141. #endif
  142. #if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER)
  143. # define CATCH_CONFIG_COUNTER
  144. #endif
  145. #if defined(CATCH_INTERNAL_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_NO_WINDOWS_SEH) && !defined(CATCH_CONFIG_WINDOWS_SEH)
  146. # define CATCH_CONFIG_WINDOWS_SEH
  147. #endif
  148. // This is set by default, because we assume that unix compilers are posix-signal-compatible by default.
  149. #if !defined(CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_POSIX_SIGNALS)
  150. # define CATCH_CONFIG_POSIX_SIGNALS
  151. #endif
  152. #if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS)
  153. # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS
  154. # define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS
  155. #endif
  156. #if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS)
  157. # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  158. # define CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  159. #endif
  160. // end catch_compiler_capabilities.h
  161. #define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line
  162. #define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line )
  163. #ifdef CATCH_CONFIG_COUNTER
  164. # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ )
  165. #else
  166. # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ )
  167. #endif
  168. #include <iosfwd>
  169. #include <string>
  170. #include <cstdint>
  171. namespace Catch {
  172. struct CaseSensitive { enum Choice {
  173. Yes,
  174. No
  175. }; };
  176. class NonCopyable {
  177. NonCopyable( NonCopyable const& ) = delete;
  178. NonCopyable( NonCopyable && ) = delete;
  179. NonCopyable& operator = ( NonCopyable const& ) = delete;
  180. NonCopyable& operator = ( NonCopyable && ) = delete;
  181. protected:
  182. NonCopyable();
  183. virtual ~NonCopyable();
  184. };
  185. struct SourceLineInfo {
  186. SourceLineInfo() = delete;
  187. SourceLineInfo( char const* _file, std::size_t _line ) noexcept;
  188. SourceLineInfo( SourceLineInfo const& other ) = default;
  189. SourceLineInfo( SourceLineInfo && ) = default;
  190. SourceLineInfo& operator = ( SourceLineInfo const& ) = default;
  191. SourceLineInfo& operator = ( SourceLineInfo && ) = default;
  192. bool empty() const noexcept;
  193. bool operator == ( SourceLineInfo const& other ) const noexcept;
  194. bool operator < ( SourceLineInfo const& other ) const noexcept;
  195. char const* file;
  196. std::size_t line;
  197. };
  198. std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info );
  199. // This is just here to avoid compiler warnings with macro constants and boolean literals
  200. bool isTrue( bool value );
  201. bool alwaysTrue();
  202. bool alwaysFalse();
  203. // Use this in variadic streaming macros to allow
  204. // >> +StreamEndStop
  205. // as well as
  206. // >> stuff +StreamEndStop
  207. struct StreamEndStop {
  208. std::string operator+() const;
  209. };
  210. template<typename T>
  211. T const& operator + ( T const& value, StreamEndStop ) {
  212. return value;
  213. }
  214. }
  215. #define CATCH_INTERNAL_LINEINFO \
  216. ::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) )
  217. // end catch_common.h
  218. namespace Catch {
  219. struct RegistrarForTagAliases {
  220. RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo );
  221. };
  222. } // end namespace Catch
  223. #define CATCH_REGISTER_TAG_ALIAS( alias, spec ) namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); }
  224. // end catch_tag_alias_autoregistrar.h
  225. // start catch_test_registry.h
  226. // start catch_interfaces_testcase.h
  227. #include <vector>
  228. #include <memory>
  229. namespace Catch {
  230. class TestSpec;
  231. struct ITestInvoker {
  232. virtual void invoke () const = 0;
  233. virtual ~ITestInvoker();
  234. };
  235. using ITestCasePtr = std::shared_ptr<ITestInvoker>;
  236. class TestCase;
  237. struct IConfig;
  238. struct ITestCaseRegistry {
  239. virtual ~ITestCaseRegistry();
  240. virtual std::vector<TestCase> const& getAllTests() const = 0;
  241. virtual std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const = 0;
  242. };
  243. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
  244. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
  245. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
  246. }
  247. // end catch_interfaces_testcase.h
  248. // start catch_stringref.h
  249. #include <cstddef>
  250. #include <string>
  251. #include <iosfwd>
  252. namespace Catch {
  253. class StringData;
  254. /// A non-owning string class (similar to the forthcoming std::string_view)
  255. /// Note that, because a StringRef may be a substring of another string,
  256. /// it may not be null terminated. c_str() must return a null terminated
  257. /// string, however, and so the StringRef will internally take ownership
  258. /// (taking a copy), if necessary. In theory this ownership is not externally
  259. /// visible - but it does mean (substring) StringRefs should not be shared between
  260. /// threads.
  261. class StringRef {
  262. friend struct StringRefTestAccess;
  263. using size_type = std::size_t;
  264. char const* m_start;
  265. size_type m_size;
  266. char* m_data = nullptr;
  267. void takeOwnership();
  268. public: // construction/ assignment
  269. StringRef() noexcept;
  270. StringRef( StringRef const& other ) noexcept;
  271. StringRef( StringRef&& other ) noexcept;
  272. StringRef( char const* rawChars ) noexcept;
  273. StringRef( char const* rawChars, size_type size ) noexcept;
  274. StringRef( std::string const& stdString ) noexcept;
  275. ~StringRef() noexcept;
  276. auto operator = ( StringRef other ) noexcept -> StringRef&;
  277. operator std::string() const;
  278. void swap( StringRef& other ) noexcept;
  279. public: // operators
  280. auto operator == ( StringRef const& other ) const noexcept -> bool;
  281. auto operator != ( StringRef const& other ) const noexcept -> bool;
  282. auto operator[] ( size_type index ) const noexcept -> char;
  283. public: // named queries
  284. auto empty() const noexcept -> bool;
  285. auto size() const noexcept -> size_type;
  286. auto numberOfCharacters() const noexcept -> size_type;
  287. auto c_str() const -> char const*;
  288. public: // substrings and searches
  289. auto substr( size_type start, size_type size ) const noexcept -> StringRef;
  290. private: // ownership queries - may not be consistent between calls
  291. auto isOwned() const noexcept -> bool;
  292. auto isSubstring() const noexcept -> bool;
  293. auto data() const noexcept -> char const*;
  294. };
  295. auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string;
  296. auto operator + ( StringRef const& lhs, char const* rhs ) -> std::string;
  297. auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string;
  298. auto operator << ( std::ostream& os, StringRef const& sr ) -> std::ostream&;
  299. } // namespace Catch
  300. // end catch_stringref.h
  301. namespace Catch {
  302. template<typename C>
  303. class TestInvokerAsMethod : public ITestInvoker {
  304. void (C::*m_testAsMethod)();
  305. public:
  306. TestInvokerAsMethod( void (C::*testAsMethod)() ) noexcept : m_testAsMethod( testAsMethod ) {}
  307. void invoke() const override {
  308. C obj;
  309. (obj.*m_testAsMethod)();
  310. }
  311. };
  312. auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker*;
  313. template<typename C>
  314. auto makeTestInvoker( void (C::*testAsMethod)() ) noexcept -> ITestInvoker* {
  315. return new(std::nothrow) TestInvokerAsMethod<C>( testAsMethod );
  316. }
  317. struct NameAndTags {
  318. NameAndTags( StringRef name_ = "", StringRef tags_ = "" ) noexcept;
  319. StringRef name;
  320. StringRef tags;
  321. };
  322. struct AutoReg : NonCopyable {
  323. AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef classOrMethod, NameAndTags const& nameAndTags ) noexcept;
  324. ~AutoReg();
  325. };
  326. } // end namespace Catch
  327. #if defined(CATCH_CONFIG_DISABLE)
  328. #define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( TestName, ... ) \
  329. static void TestName()
  330. #define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( TestName, ClassName, ... ) \
  331. namespace{ \
  332. struct TestName : ClassName { \
  333. void test(); \
  334. }; \
  335. } \
  336. void TestName::test()
  337. #endif
  338. ///////////////////////////////////////////////////////////////////////////////
  339. #define INTERNAL_CATCH_TESTCASE2( TestName, ... ) \
  340. static void TestName(); \
  341. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  342. namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &TestName ), CATCH_INTERNAL_LINEINFO, "", Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
  343. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  344. static void TestName()
  345. #define INTERNAL_CATCH_TESTCASE( ... ) \
  346. INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), __VA_ARGS__ )
  347. ///////////////////////////////////////////////////////////////////////////////
  348. #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \
  349. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  350. namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &QualifiedMethod ), CATCH_INTERNAL_LINEINFO, "&" #QualifiedMethod, Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
  351. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  352. ///////////////////////////////////////////////////////////////////////////////
  353. #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestName, ClassName, ... )\
  354. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  355. namespace{ \
  356. struct TestName : ClassName{ \
  357. void test(); \
  358. }; \
  359. Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( Catch::makeTestInvoker( &TestName::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
  360. } \
  361. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  362. void TestName::test()
  363. #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \
  364. INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, __VA_ARGS__ )
  365. ///////////////////////////////////////////////////////////////////////////////
  366. #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \
  367. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  368. Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( Function ), CATCH_INTERNAL_LINEINFO, "", Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
  369. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  370. // end catch_test_registry.h
  371. // start catch_capture.hpp
  372. // start catch_assertionhandler.h
  373. // start catch_decomposer.h
  374. // start catch_tostring.h
  375. #include <sstream>
  376. #include <vector>
  377. #include <cstddef>
  378. #include <type_traits>
  379. #include <string>
  380. #ifdef __OBJC__
  381. // start catch_objc_arc.hpp
  382. #import <Foundation/Foundation.h>
  383. #ifdef __has_feature
  384. #define CATCH_ARC_ENABLED __has_feature(objc_arc)
  385. #else
  386. #define CATCH_ARC_ENABLED 0
  387. #endif
  388. void arcSafeRelease( NSObject* obj );
  389. id performOptionalSelector( id obj, SEL sel );
  390. #if !CATCH_ARC_ENABLED
  391. inline void arcSafeRelease( NSObject* obj ) {
  392. [obj release];
  393. }
  394. inline id performOptionalSelector( id obj, SEL sel ) {
  395. if( [obj respondsToSelector: sel] )
  396. return [obj performSelector: sel];
  397. return nil;
  398. }
  399. #define CATCH_UNSAFE_UNRETAINED
  400. #define CATCH_ARC_STRONG
  401. #else
  402. inline void arcSafeRelease( NSObject* ){}
  403. inline id performOptionalSelector( id obj, SEL sel ) {
  404. #ifdef __clang__
  405. #pragma clang diagnostic push
  406. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  407. #endif
  408. if( [obj respondsToSelector: sel] )
  409. return [obj performSelector: sel];
  410. #ifdef __clang__
  411. #pragma clang diagnostic pop
  412. #endif
  413. return nil;
  414. }
  415. #define CATCH_UNSAFE_UNRETAINED __unsafe_unretained
  416. #define CATCH_ARC_STRONG __strong
  417. #endif
  418. // end catch_objc_arc.hpp
  419. #endif
  420. #ifdef _MSC_VER
  421. #pragma warning(push)
  422. #pragma warning(disable:4180) // We attempt to stream a function (address) by const&, which MSVC complains about but is harmless
  423. #endif
  424. // We need a dummy global operator<< so we can bring it into Catch namespace later
  425. struct Catch_global_namespace_dummy;
  426. std::ostream& operator<<(std::ostream&, Catch_global_namespace_dummy);
  427. namespace Catch {
  428. // Bring in operator<< from global namespace into Catch namespace
  429. using ::operator<<;
  430. namespace Detail {
  431. extern const std::string unprintableString;
  432. std::string rawMemoryToString( const void *object, std::size_t size );
  433. template<typename T>
  434. std::string rawMemoryToString( const T& object ) {
  435. return rawMemoryToString( &object, sizeof(object) );
  436. }
  437. template<typename T>
  438. class IsStreamInsertable {
  439. template<typename SS, typename TT>
  440. static auto test(int)
  441. -> decltype(std::declval<SS&>() << std::declval<TT>(), std::true_type());
  442. template<typename, typename>
  443. static auto test(...)->std::false_type;
  444. public:
  445. static const bool value = decltype(test<std::ostream, const T&>(0))::value;
  446. };
  447. } // namespace Detail
  448. // If we decide for C++14, change these to enable_if_ts
  449. template <typename T>
  450. struct StringMaker {
  451. template <typename Fake = T>
  452. static
  453. typename std::enable_if<::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
  454. convert(const Fake& t) {
  455. std::ostringstream sstr;
  456. sstr << t;
  457. return sstr.str();
  458. }
  459. template <typename Fake = T>
  460. static
  461. typename std::enable_if<!::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
  462. convert(const Fake&) {
  463. return Detail::unprintableString;
  464. }
  465. };
  466. namespace Detail {
  467. // This function dispatches all stringification requests inside of Catch.
  468. // Should be preferably called fully qualified, like ::Catch::Detail::stringify
  469. template <typename T>
  470. std::string stringify(const T& e) {
  471. return ::Catch::StringMaker<typename std::remove_cv<typename std::remove_reference<T>::type>::type>::convert(e);
  472. }
  473. } // namespace Detail
  474. // Some predefined specializations
  475. template<>
  476. struct StringMaker<std::string> {
  477. static std::string convert(const std::string& str);
  478. };
  479. template<>
  480. struct StringMaker<std::wstring> {
  481. static std::string convert(const std::wstring& wstr);
  482. };
  483. template<>
  484. struct StringMaker<char const *> {
  485. static std::string convert(char const * str);
  486. };
  487. template<>
  488. struct StringMaker<char *> {
  489. static std::string convert(char * str);
  490. };
  491. template<>
  492. struct StringMaker<wchar_t const *> {
  493. static std::string convert(wchar_t const * str);
  494. };
  495. template<>
  496. struct StringMaker<wchar_t *> {
  497. static std::string convert(wchar_t * str);
  498. };
  499. template<int SZ>
  500. struct StringMaker<char[SZ]> {
  501. static std::string convert(const char* str) {
  502. return ::Catch::Detail::stringify(std::string{ str });
  503. }
  504. };
  505. template<int SZ>
  506. struct StringMaker<signed char[SZ]> {
  507. static std::string convert(const char* str) {
  508. return ::Catch::Detail::stringify(std::string{ str });
  509. }
  510. };
  511. template<int SZ>
  512. struct StringMaker<unsigned char[SZ]> {
  513. static std::string convert(const char* str) {
  514. return ::Catch::Detail::stringify(std::string{ str });
  515. }
  516. };
  517. template<>
  518. struct StringMaker<int> {
  519. static std::string convert(int value);
  520. };
  521. template<>
  522. struct StringMaker<long> {
  523. static std::string convert(long value);
  524. };
  525. template<>
  526. struct StringMaker<long long> {
  527. static std::string convert(long long value);
  528. };
  529. template<>
  530. struct StringMaker<unsigned int> {
  531. static std::string convert(unsigned int value);
  532. };
  533. template<>
  534. struct StringMaker<unsigned long> {
  535. static std::string convert(unsigned long value);
  536. };
  537. template<>
  538. struct StringMaker<unsigned long long> {
  539. static std::string convert(unsigned long long value);
  540. };
  541. template<>
  542. struct StringMaker<bool> {
  543. static std::string convert(bool b);
  544. };
  545. template<>
  546. struct StringMaker<char> {
  547. static std::string convert(char c);
  548. };
  549. template<>
  550. struct StringMaker<signed char> {
  551. static std::string convert(signed char c);
  552. };
  553. template<>
  554. struct StringMaker<unsigned char> {
  555. static std::string convert(unsigned char c);
  556. };
  557. template<>
  558. struct StringMaker<std::nullptr_t> {
  559. static std::string convert(std::nullptr_t);
  560. };
  561. template<>
  562. struct StringMaker<float> {
  563. static std::string convert(float value);
  564. };
  565. template<>
  566. struct StringMaker<double> {
  567. static std::string convert(double value);
  568. };
  569. template <typename T>
  570. struct StringMaker<T*> {
  571. template <typename U>
  572. static std::string convert(U* p) {
  573. if (p) {
  574. return ::Catch::Detail::rawMemoryToString(p);
  575. } else {
  576. return "nullptr";
  577. }
  578. }
  579. };
  580. template <typename R, typename C>
  581. struct StringMaker<R C::*> {
  582. static std::string convert(R C::* p) {
  583. if (p) {
  584. return ::Catch::Detail::rawMemoryToString(p);
  585. } else {
  586. return "nullptr";
  587. }
  588. }
  589. };
  590. namespace Detail {
  591. template<typename InputIterator>
  592. std::string rangeToString(InputIterator first, InputIterator last) {
  593. std::ostringstream oss;
  594. oss << "{ ";
  595. if (first != last) {
  596. oss << ::Catch::Detail::stringify(*first);
  597. for (++first; first != last; ++first)
  598. oss << ", " << ::Catch::Detail::stringify(*first);
  599. }
  600. oss << " }";
  601. return oss.str();
  602. }
  603. }
  604. template<typename T, typename Allocator>
  605. struct StringMaker<std::vector<T, Allocator> > {
  606. static std::string convert( std::vector<T,Allocator> const& v ) {
  607. return ::Catch::Detail::rangeToString( v.begin(), v.end() );
  608. }
  609. };
  610. template<typename T>
  611. struct EnumStringMaker {
  612. static std::string convert(const T& t) {
  613. return ::Catch::Detail::stringify(static_cast<typename std::underlying_type<T>::type>(t));
  614. }
  615. };
  616. #ifdef __OBJC__
  617. template<>
  618. struct StringMaker<NSString*> {
  619. static std::string convert(NSString * nsstring) {
  620. if (!nsstring)
  621. return "nil";
  622. return std::string("@") + [nsstring UTF8String];
  623. }
  624. };
  625. template<>
  626. struct StringMaker<NSObject*> {
  627. static std::string convert(NSObject* nsObject) {
  628. return ::Catch::Detail::stringify([nsObject description]);
  629. }
  630. };
  631. namespace Detail {
  632. inline std::string stringify( NSString* nsstring ) {
  633. return StringMaker<NSString*>::convert( nsstring );
  634. }
  635. } // namespace Detail
  636. #endif // __OBJC__
  637. } // namespace Catch
  638. //////////////////////////////////////////////////////
  639. // Separate std-lib types stringification, so it can be selectively enabled
  640. // This means that we do not bring in
  641. #if defined(CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS)
  642. # define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
  643. # define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
  644. # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  645. #endif
  646. // Separate std::pair specialization
  647. #if defined(CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER)
  648. #include <utility>
  649. namespace Catch {
  650. template<typename T1, typename T2>
  651. struct StringMaker<std::pair<T1, T2> > {
  652. static std::string convert(const std::pair<T1, T2>& pair) {
  653. std::ostringstream oss;
  654. oss << "{ "
  655. << ::Catch::Detail::stringify(pair.first)
  656. << ", "
  657. << ::Catch::Detail::stringify(pair.second)
  658. << " }";
  659. return oss.str();
  660. }
  661. };
  662. }
  663. #endif // CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
  664. // Separate std::tuple specialization
  665. #if defined(CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER)
  666. #include <tuple>
  667. namespace Catch {
  668. namespace Detail {
  669. template<
  670. typename Tuple,
  671. std::size_t N = 0,
  672. bool = (N < std::tuple_size<Tuple>::value)
  673. >
  674. struct TupleElementPrinter {
  675. static void print(const Tuple& tuple, std::ostream& os) {
  676. os << (N ? ", " : " ")
  677. << ::Catch::Detail::stringify(std::get<N>(tuple));
  678. TupleElementPrinter<Tuple, N + 1>::print(tuple, os);
  679. }
  680. };
  681. template<
  682. typename Tuple,
  683. std::size_t N
  684. >
  685. struct TupleElementPrinter<Tuple, N, false> {
  686. static void print(const Tuple&, std::ostream&) {}
  687. };
  688. }
  689. template<typename ...Types>
  690. struct StringMaker<std::tuple<Types...>> {
  691. static std::string convert(const std::tuple<Types...>& tuple) {
  692. std::ostringstream os;
  693. os << '{';
  694. Detail::TupleElementPrinter<std::tuple<Types...>>::print(tuple, os);
  695. os << " }";
  696. return os.str();
  697. }
  698. };
  699. }
  700. #endif // CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
  701. // Separate std::chrono::duration specialization
  702. #if defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  703. #include <ctime>
  704. #include <ratio>
  705. #include <chrono>
  706. template <class Ratio>
  707. struct ratio_string {
  708. static std::string symbol();
  709. };
  710. template <class Ratio>
  711. std::string ratio_string<Ratio>::symbol() {
  712. std::ostringstream oss;
  713. oss << '[' << Ratio::num << '/'
  714. << Ratio::den << ']';
  715. return oss.str();
  716. }
  717. template <>
  718. struct ratio_string<std::atto> {
  719. static std::string symbol() { return "a"; }
  720. };
  721. template <>
  722. struct ratio_string<std::femto> {
  723. static std::string symbol() { return "f"; }
  724. };
  725. template <>
  726. struct ratio_string<std::pico> {
  727. static std::string symbol() { return "p"; }
  728. };
  729. template <>
  730. struct ratio_string<std::nano> {
  731. static std::string symbol() { return "n"; }
  732. };
  733. template <>
  734. struct ratio_string<std::micro> {
  735. static std::string symbol() { return "u"; }
  736. };
  737. template <>
  738. struct ratio_string<std::milli> {
  739. static std::string symbol() { return "m"; }
  740. };
  741. namespace Catch {
  742. ////////////
  743. // std::chrono::duration specializations
  744. template<typename Value, typename Ratio>
  745. struct StringMaker<std::chrono::duration<Value, Ratio>> {
  746. static std::string convert(std::chrono::duration<Value, Ratio> const& duration) {
  747. std::ostringstream oss;
  748. oss << duration.count() << ' ' << ratio_string<Ratio>::symbol() << 's';
  749. return oss.str();
  750. }
  751. };
  752. template<typename Value>
  753. struct StringMaker<std::chrono::duration<Value, std::ratio<1>>> {
  754. static std::string convert(std::chrono::duration<Value, std::ratio<1>> const& duration) {
  755. std::ostringstream oss;
  756. oss << duration.count() << " s";
  757. return oss.str();
  758. }
  759. };
  760. template<typename Value>
  761. struct StringMaker<std::chrono::duration<Value, std::ratio<60>>> {
  762. static std::string convert(std::chrono::duration<Value, std::ratio<60>> const& duration) {
  763. std::ostringstream oss;
  764. oss << duration.count() << " m";
  765. return oss.str();
  766. }
  767. };
  768. template<typename Value>
  769. struct StringMaker<std::chrono::duration<Value, std::ratio<3600>>> {
  770. static std::string convert(std::chrono::duration<Value, std::ratio<3600>> const& duration) {
  771. std::ostringstream oss;
  772. oss << duration.count() << " h";
  773. return oss.str();
  774. }
  775. };
  776. ////////////
  777. // std::chrono::time_point specialization
  778. // Generic time_point cannot be specialized, only std::chrono::time_point<system_clock>
  779. template<typename Clock, typename Duration>
  780. struct StringMaker<std::chrono::time_point<Clock, Duration>> {
  781. static std::string convert(std::chrono::time_point<Clock, Duration> const& time_point) {
  782. return ::Catch::Detail::stringify(time_point.time_since_epoch()) + " since epoch";
  783. }
  784. };
  785. // std::chrono::time_point<system_clock> specialization
  786. template<typename Duration>
  787. struct StringMaker<std::chrono::time_point<std::chrono::system_clock, Duration>> {
  788. static std::string convert(std::chrono::time_point<std::chrono::system_clock, Duration> const& time_point) {
  789. auto converted = std::chrono::system_clock::to_time_t(time_point);
  790. #ifdef _MSC_VER
  791. std::tm timeInfo = {};
  792. gmtime_s(&timeInfo, &converted);
  793. #else
  794. std::tm* timeInfo = std::gmtime(&converted);
  795. #endif
  796. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  797. char timeStamp[timeStampSize];
  798. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  799. #ifdef _MSC_VER
  800. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  801. #else
  802. std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
  803. #endif
  804. return std::string(timeStamp);
  805. }
  806. };
  807. }
  808. #endif // CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  809. #ifdef _MSC_VER
  810. #pragma warning(pop)
  811. #endif
  812. // end catch_tostring.h
  813. #include <ostream>
  814. #ifdef _MSC_VER
  815. #pragma warning(push)
  816. #pragma warning(disable:4389) // '==' : signed/unsigned mismatch
  817. #pragma warning(disable:4018) // more "signed/unsigned mismatch"
  818. #pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform)
  819. #pragma warning(disable:4180) // qualifier applied to function type has no meaning
  820. #endif
  821. namespace Catch {
  822. struct ITransientExpression {
  823. virtual auto isBinaryExpression() const -> bool = 0;
  824. virtual auto getResult() const -> bool = 0;
  825. virtual void streamReconstructedExpression( std::ostream &os ) const = 0;
  826. // We don't actually need a virtual destructore, but many static analysers
  827. // complain if it's not here :-(
  828. virtual ~ITransientExpression();
  829. };
  830. void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs );
  831. template<typename LhsT, typename RhsT>
  832. class BinaryExpr : public ITransientExpression {
  833. bool m_result;
  834. LhsT m_lhs;
  835. StringRef m_op;
  836. RhsT m_rhs;
  837. auto isBinaryExpression() const -> bool override { return true; }
  838. auto getResult() const -> bool override { return m_result; }
  839. void streamReconstructedExpression( std::ostream &os ) const override {
  840. formatReconstructedExpression
  841. ( os, Catch::Detail::stringify( m_lhs ), m_op, Catch::Detail::stringify( m_rhs ) );
  842. }
  843. public:
  844. BinaryExpr( bool comparisonResult, LhsT lhs, StringRef op, RhsT rhs )
  845. : m_result( comparisonResult ),
  846. m_lhs( lhs ),
  847. m_op( op ),
  848. m_rhs( rhs )
  849. {}
  850. };
  851. template<typename LhsT>
  852. class UnaryExpr : public ITransientExpression {
  853. LhsT m_lhs;
  854. auto isBinaryExpression() const -> bool override { return false; }
  855. auto getResult() const -> bool override { return m_lhs ? true : false; }
  856. void streamReconstructedExpression( std::ostream &os ) const override {
  857. os << Catch::Detail::stringify( m_lhs );
  858. }
  859. public:
  860. UnaryExpr( LhsT lhs ) : m_lhs( lhs ) {}
  861. };
  862. // Specialised comparison functions to handle equality comparisons between ints and pointers (NULL deduces as an int)
  863. template<typename LhsT, typename RhsT>
  864. auto compareEqual( LhsT const& lhs, RhsT const& rhs ) -> bool { return lhs == rhs; };
  865. template<typename T>
  866. auto compareEqual( T* const& lhs, int rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
  867. template<typename T>
  868. auto compareEqual( T* const& lhs, long rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
  869. template<typename T>
  870. auto compareEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
  871. template<typename T>
  872. auto compareEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
  873. template<typename LhsT, typename RhsT>
  874. auto compareNotEqual( LhsT const& lhs, RhsT&& rhs ) -> bool { return lhs != rhs; };
  875. template<typename T>
  876. auto compareNotEqual( T* const& lhs, int rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
  877. template<typename T>
  878. auto compareNotEqual( T* const& lhs, long rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
  879. template<typename T>
  880. auto compareNotEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
  881. template<typename T>
  882. auto compareNotEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
  883. template<typename LhsT>
  884. class ExprLhs {
  885. LhsT m_lhs;
  886. public:
  887. ExprLhs( LhsT lhs ) : m_lhs( lhs ) {}
  888. template<typename RhsT>
  889. auto operator == ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  890. return BinaryExpr<LhsT, RhsT const&>( compareEqual( m_lhs, rhs ), m_lhs, "==", rhs );
  891. }
  892. auto operator == ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
  893. return BinaryExpr<LhsT, bool>( m_lhs == rhs, m_lhs, "==", rhs );
  894. }
  895. template<typename RhsT>
  896. auto operator != ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  897. return BinaryExpr<LhsT, RhsT const&>( compareNotEqual( m_lhs, rhs ), m_lhs, "!=", rhs );
  898. }
  899. auto operator != ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
  900. return BinaryExpr<LhsT, bool>( m_lhs != rhs, m_lhs, "!=", rhs );
  901. }
  902. template<typename RhsT>
  903. auto operator > ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  904. return BinaryExpr<LhsT, RhsT const&>( m_lhs > rhs, m_lhs, ">", rhs );
  905. }
  906. template<typename RhsT>
  907. auto operator < ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  908. return BinaryExpr<LhsT, RhsT const&>( m_lhs < rhs, m_lhs, "<", rhs );
  909. }
  910. template<typename RhsT>
  911. auto operator >= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  912. return BinaryExpr<LhsT, RhsT const&>( m_lhs >= rhs, m_lhs, ">=", rhs );
  913. }
  914. template<typename RhsT>
  915. auto operator <= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  916. return BinaryExpr<LhsT, RhsT const&>( m_lhs <= rhs, m_lhs, "<=", rhs );
  917. }
  918. auto makeUnaryExpr() const -> UnaryExpr<LhsT> {
  919. return UnaryExpr<LhsT>( m_lhs );
  920. }
  921. };
  922. void handleExpression( ITransientExpression const& expr );
  923. template<typename T>
  924. void handleExpression( ExprLhs<T> const& expr ) {
  925. handleExpression( expr.makeUnaryExpr() );
  926. }
  927. struct Decomposer {
  928. template<typename T>
  929. auto operator <= ( T const& lhs ) -> ExprLhs<T const&> {
  930. return ExprLhs<T const&>( lhs );
  931. }
  932. auto operator <=( bool value ) -> ExprLhs<bool> {
  933. return ExprLhs<bool>( value );
  934. }
  935. };
  936. } // end namespace Catch
  937. #ifdef _MSC_VER
  938. #pragma warning(pop)
  939. #endif
  940. // end catch_decomposer.h
  941. // start catch_assertioninfo.h
  942. // start catch_result_type.h
  943. namespace Catch {
  944. // ResultWas::OfType enum
  945. struct ResultWas { enum OfType {
  946. Unknown = -1,
  947. Ok = 0,
  948. Info = 1,
  949. Warning = 2,
  950. FailureBit = 0x10,
  951. ExpressionFailed = FailureBit | 1,
  952. ExplicitFailure = FailureBit | 2,
  953. Exception = 0x100 | FailureBit,
  954. ThrewException = Exception | 1,
  955. DidntThrowException = Exception | 2,
  956. FatalErrorCondition = 0x200 | FailureBit
  957. }; };
  958. bool isOk( ResultWas::OfType resultType );
  959. bool isJustInfo( int flags );
  960. // ResultDisposition::Flags enum
  961. struct ResultDisposition { enum Flags {
  962. Normal = 0x01,
  963. ContinueOnFailure = 0x02, // Failures fail test, but execution continues
  964. FalseTest = 0x04, // Prefix expression with !
  965. SuppressFail = 0x08 // Failures are reported but do not fail the test
  966. }; };
  967. ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs );
  968. bool shouldContinueOnFailure( int flags );
  969. bool isFalseTest( int flags );
  970. bool shouldSuppressFailure( int flags );
  971. } // end namespace Catch
  972. // end catch_result_type.h
  973. namespace Catch {
  974. struct AssertionInfo
  975. {
  976. StringRef macroName;
  977. SourceLineInfo lineInfo;
  978. StringRef capturedExpression;
  979. ResultDisposition::Flags resultDisposition;
  980. // We want to delete this constructor but a compiler bug in 4.8 means
  981. // the struct is then treated as non-aggregate
  982. //AssertionInfo() = delete;
  983. };
  984. } // end namespace Catch
  985. // end catch_assertioninfo.h
  986. namespace Catch {
  987. struct TestFailureException{};
  988. struct AssertionResultData;
  989. class LazyExpression {
  990. friend class AssertionHandler;
  991. friend struct AssertionStats;
  992. ITransientExpression const* m_transientExpression = nullptr;
  993. bool m_isNegated;
  994. public:
  995. LazyExpression( bool isNegated );
  996. LazyExpression( LazyExpression const& other );
  997. LazyExpression& operator = ( LazyExpression const& ) = delete;
  998. explicit operator bool() const;
  999. friend auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream&;
  1000. };
  1001. class AssertionHandler {
  1002. AssertionInfo m_assertionInfo;
  1003. bool m_shouldDebugBreak = false;
  1004. bool m_shouldThrow = false;
  1005. bool m_inExceptionGuard = false;
  1006. public:
  1007. AssertionHandler
  1008. ( StringRef macroName,
  1009. SourceLineInfo const& lineInfo,
  1010. StringRef capturedExpression,
  1011. ResultDisposition::Flags resultDisposition );
  1012. ~AssertionHandler();
  1013. void handle( ITransientExpression const& expr );
  1014. template<typename T>
  1015. void handle( ExprLhs<T> const& expr ) {
  1016. handle( expr.makeUnaryExpr() );
  1017. }
  1018. void handle( ResultWas::OfType resultType );
  1019. void handle( ResultWas::OfType resultType, StringRef const& message );
  1020. void handle( ResultWas::OfType resultType, ITransientExpression const* expr, bool negated );
  1021. void handle( AssertionResultData const& resultData, ITransientExpression const* expr );
  1022. auto shouldDebugBreak() const -> bool;
  1023. auto allowThrows() const -> bool;
  1024. void reactWithDebugBreak() const;
  1025. void reactWithoutDebugBreak() const;
  1026. void useActiveException();
  1027. void setExceptionGuard();
  1028. void unsetExceptionGuard();
  1029. };
  1030. void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef matcherString );
  1031. } // namespace Catch
  1032. // end catch_assertionhandler.h
  1033. // start catch_message.h
  1034. #include <string>
  1035. #include <sstream>
  1036. namespace Catch {
  1037. struct MessageInfo {
  1038. MessageInfo( std::string const& _macroName,
  1039. SourceLineInfo const& _lineInfo,
  1040. ResultWas::OfType _type );
  1041. std::string macroName;
  1042. std::string message;
  1043. SourceLineInfo lineInfo;
  1044. ResultWas::OfType type;
  1045. unsigned int sequence;
  1046. bool operator == ( MessageInfo const& other ) const;
  1047. bool operator < ( MessageInfo const& other ) const;
  1048. private:
  1049. static unsigned int globalCount;
  1050. };
  1051. struct MessageStream {
  1052. template<typename T>
  1053. MessageStream& operator << ( T const& value ) {
  1054. m_stream << value;
  1055. return *this;
  1056. }
  1057. // !TBD reuse a global/ thread-local stream
  1058. std::ostringstream m_stream;
  1059. };
  1060. struct MessageBuilder : MessageStream {
  1061. MessageBuilder( std::string const& macroName,
  1062. SourceLineInfo const& lineInfo,
  1063. ResultWas::OfType type );
  1064. template<typename T>
  1065. MessageBuilder& operator << ( T const& value ) {
  1066. m_stream << value;
  1067. return *this;
  1068. }
  1069. MessageInfo m_info;
  1070. };
  1071. class ScopedMessage {
  1072. public:
  1073. ScopedMessage( MessageBuilder const& builder );
  1074. ~ScopedMessage();
  1075. MessageInfo m_info;
  1076. };
  1077. } // end namespace Catch
  1078. // end catch_message.h
  1079. // start catch_interfaces_capture.h
  1080. #include <string>
  1081. namespace Catch {
  1082. class AssertionResult;
  1083. struct AssertionInfo;
  1084. struct SectionInfo;
  1085. struct SectionEndInfo;
  1086. struct MessageInfo;
  1087. struct Counts;
  1088. struct BenchmarkInfo;
  1089. struct BenchmarkStats;
  1090. struct IResultCapture {
  1091. virtual ~IResultCapture();
  1092. virtual void assertionStarting( AssertionInfo const& info ) = 0;
  1093. virtual void assertionEnded( AssertionResult const& result ) = 0;
  1094. virtual bool sectionStarted( SectionInfo const& sectionInfo,
  1095. Counts& assertions ) = 0;
  1096. virtual void sectionEnded( SectionEndInfo const& endInfo ) = 0;
  1097. virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) = 0;
  1098. virtual void benchmarkStarting( BenchmarkInfo const& info ) = 0;
  1099. virtual void benchmarkEnded( BenchmarkStats const& stats ) = 0;
  1100. virtual void pushScopedMessage( MessageInfo const& message ) = 0;
  1101. virtual void popScopedMessage( MessageInfo const& message ) = 0;
  1102. virtual std::string getCurrentTestName() const = 0;
  1103. virtual const AssertionResult* getLastResult() const = 0;
  1104. virtual void exceptionEarlyReported() = 0;
  1105. virtual void handleFatalErrorCondition( StringRef message ) = 0;
  1106. virtual bool lastAssertionPassed() = 0;
  1107. virtual void assertionPassed() = 0;
  1108. virtual void assertionRun() = 0;
  1109. };
  1110. IResultCapture& getResultCapture();
  1111. }
  1112. // end catch_interfaces_capture.h
  1113. // start catch_debugger.h
  1114. namespace Catch {
  1115. bool isDebuggerActive();
  1116. }
  1117. #ifdef CATCH_PLATFORM_MAC
  1118. #define CATCH_TRAP() __asm__("int $3\n" : : ) /* NOLINT */
  1119. #elif defined(CATCH_PLATFORM_LINUX)
  1120. // If we can use inline assembler, do it because this allows us to break
  1121. // directly at the location of the failing check instead of breaking inside
  1122. // raise() called from it, i.e. one stack frame below.
  1123. #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64))
  1124. #define CATCH_TRAP() asm volatile ("int $3") /* NOLINT */
  1125. #else // Fall back to the generic way.
  1126. #include <signal.h>
  1127. #define CATCH_TRAP() raise(SIGTRAP)
  1128. #endif
  1129. #elif defined(_MSC_VER)
  1130. #define CATCH_TRAP() __debugbreak()
  1131. #elif defined(__MINGW32__)
  1132. extern "C" __declspec(dllimport) void __stdcall DebugBreak();
  1133. #define CATCH_TRAP() DebugBreak()
  1134. #endif
  1135. #ifdef CATCH_TRAP
  1136. #define CATCH_BREAK_INTO_DEBUGGER() if( Catch::isDebuggerActive() ) { CATCH_TRAP(); }
  1137. #else
  1138. #define CATCH_BREAK_INTO_DEBUGGER() Catch::alwaysTrue();
  1139. #endif
  1140. // end catch_debugger.h
  1141. #if !defined(CATCH_CONFIG_DISABLE)
  1142. #if !defined(CATCH_CONFIG_DISABLE_STRINGIFICATION)
  1143. #define CATCH_INTERNAL_STRINGIFY(...) #__VA_ARGS__
  1144. #else
  1145. #define CATCH_INTERNAL_STRINGIFY(...) "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION"
  1146. #endif
  1147. #if defined(CATCH_CONFIG_FAST_COMPILE)
  1148. ///////////////////////////////////////////////////////////////////////////////
  1149. // We can speedup compilation significantly by breaking into debugger lower in
  1150. // the callstack, because then we don't have to expand CATCH_BREAK_INTO_DEBUGGER
  1151. // macro in each assertion
  1152. #define INTERNAL_CATCH_REACT( handler ) \
  1153. handler.reactWithDebugBreak();
  1154. ///////////////////////////////////////////////////////////////////////////////
  1155. // Another way to speed-up compilation is to omit local try-catch for REQUIRE*
  1156. // macros.
  1157. // This can potentially cause false negative, if the test code catches
  1158. // the exception before it propagates back up to the runner.
  1159. #define INTERNAL_CATCH_TRY( capturer ) capturer.setExceptionGuard();
  1160. #define INTERNAL_CATCH_CATCH( capturer ) capturer.unsetExceptionGuard();
  1161. #else // CATCH_CONFIG_FAST_COMPILE
  1162. ///////////////////////////////////////////////////////////////////////////////
  1163. // In the event of a failure works out if the debugger needs to be invoked
  1164. // and/or an exception thrown and takes appropriate action.
  1165. // This needs to be done as a macro so the debugger will stop in the user
  1166. // source code rather than in Catch library code
  1167. #define INTERNAL_CATCH_REACT( handler ) \
  1168. if( handler.shouldDebugBreak() ) CATCH_BREAK_INTO_DEBUGGER(); \
  1169. handler.reactWithoutDebugBreak();
  1170. #define INTERNAL_CATCH_TRY( capturer ) try
  1171. #define INTERNAL_CATCH_CATCH( capturer ) catch(...) { capturer.useActiveException(); }
  1172. #endif
  1173. ///////////////////////////////////////////////////////////////////////////////
  1174. #define INTERNAL_CATCH_TEST( macroName, resultDisposition, ... ) \
  1175. do { \
  1176. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
  1177. INTERNAL_CATCH_TRY( catchAssertionHandler ) { \
  1178. CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
  1179. catchAssertionHandler.handle( Catch::Decomposer() <= __VA_ARGS__ ); \
  1180. CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
  1181. } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
  1182. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1183. } while( Catch::isTrue( false && static_cast<bool>( !!(__VA_ARGS__) ) ) ) // the expression here is never evaluated at runtime but it forces the compiler to give it a look
  1184. // The double negation silences MSVC's C4800 warning, the static_cast forces short-circuit evaluation if the type has overloaded &&.
  1185. ///////////////////////////////////////////////////////////////////////////////
  1186. #define INTERNAL_CATCH_IF( macroName, resultDisposition, ... ) \
  1187. INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
  1188. if( Catch::getResultCapture().lastAssertionPassed() )
  1189. ///////////////////////////////////////////////////////////////////////////////
  1190. #define INTERNAL_CATCH_ELSE( macroName, resultDisposition, ... ) \
  1191. INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
  1192. if( !Catch::getResultCapture().lastAssertionPassed() )
  1193. ///////////////////////////////////////////////////////////////////////////////
  1194. #define INTERNAL_CATCH_NO_THROW( macroName, resultDisposition, ... ) \
  1195. do { \
  1196. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
  1197. try { \
  1198. static_cast<void>(__VA_ARGS__); \
  1199. catchAssertionHandler.handle( Catch::ResultWas::Ok ); \
  1200. } \
  1201. catch( ... ) { \
  1202. catchAssertionHandler.useActiveException(); \
  1203. } \
  1204. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1205. } while( Catch::alwaysFalse() )
  1206. ///////////////////////////////////////////////////////////////////////////////
  1207. #define INTERNAL_CATCH_THROWS( macroName, resultDisposition, ... ) \
  1208. do { \
  1209. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition); \
  1210. if( catchAssertionHandler.allowThrows() ) \
  1211. try { \
  1212. static_cast<void>(__VA_ARGS__); \
  1213. catchAssertionHandler.handle( Catch::ResultWas::DidntThrowException ); \
  1214. } \
  1215. catch( ... ) { \
  1216. catchAssertionHandler.handle( Catch::ResultWas::Ok ); \
  1217. } \
  1218. else \
  1219. catchAssertionHandler.handle( Catch::ResultWas::Ok ); \
  1220. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1221. } while( Catch::alwaysFalse() )
  1222. ///////////////////////////////////////////////////////////////////////////////
  1223. #define INTERNAL_CATCH_THROWS_AS( macroName, exceptionType, resultDisposition, expr ) \
  1224. do { \
  1225. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType), resultDisposition ); \
  1226. if( catchAssertionHandler.allowThrows() ) \
  1227. try { \
  1228. static_cast<void>(expr); \
  1229. catchAssertionHandler.handle( Catch::ResultWas::DidntThrowException ); \
  1230. } \
  1231. catch( exceptionType const& ) { \
  1232. catchAssertionHandler.handle( Catch::ResultWas::Ok ); \
  1233. } \
  1234. catch( ... ) { \
  1235. catchAssertionHandler.useActiveException(); \
  1236. } \
  1237. else \
  1238. catchAssertionHandler.handle( Catch::ResultWas::Ok ); \
  1239. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1240. } while( Catch::alwaysFalse() )
  1241. ///////////////////////////////////////////////////////////////////////////////
  1242. #define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, ... ) \
  1243. do { \
  1244. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, "", resultDisposition ); \
  1245. catchAssertionHandler.handle( messageType, ( Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop() ).m_stream.str() ); \
  1246. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1247. } while( Catch::alwaysFalse() )
  1248. ///////////////////////////////////////////////////////////////////////////////
  1249. #define INTERNAL_CATCH_INFO( macroName, log ) \
  1250. Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage ) = Catch::MessageBuilder( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log;
  1251. ///////////////////////////////////////////////////////////////////////////////
  1252. // Although this is matcher-based, it can be used with just a string
  1253. #define INTERNAL_CATCH_THROWS_STR_MATCHES( macroName, resultDisposition, matcher, ... ) \
  1254. do { \
  1255. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  1256. if( catchAssertionHandler.allowThrows() ) \
  1257. try { \
  1258. static_cast<void>(__VA_ARGS__); \
  1259. catchAssertionHandler.handle( Catch::ResultWas::DidntThrowException ); \
  1260. } \
  1261. catch( ... ) { \
  1262. handleExceptionMatchExpr( catchAssertionHandler, matcher, #matcher ); \
  1263. } \
  1264. else \
  1265. catchAssertionHandler.handle( Catch::ResultWas::Ok ); \
  1266. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1267. } while( Catch::alwaysFalse() )
  1268. #endif // CATCH_CONFIG_DISABLE
  1269. // end catch_capture.hpp
  1270. // start catch_section.h
  1271. // start catch_section_info.h
  1272. // start catch_totals.h
  1273. #include <cstddef>
  1274. namespace Catch {
  1275. struct Counts {
  1276. Counts operator - ( Counts const& other ) const;
  1277. Counts& operator += ( Counts const& other );
  1278. std::size_t total() const;
  1279. bool allPassed() const;
  1280. bool allOk() const;
  1281. std::size_t passed = 0;
  1282. std::size_t failed = 0;
  1283. std::size_t failedButOk = 0;
  1284. };
  1285. struct Totals {
  1286. Totals operator - ( Totals const& other ) const;
  1287. Totals& operator += ( Totals const& other );
  1288. Totals delta( Totals const& prevTotals ) const;
  1289. Counts assertions;
  1290. Counts testCases;
  1291. };
  1292. }
  1293. // end catch_totals.h
  1294. #include <string>
  1295. namespace Catch {
  1296. struct SectionInfo {
  1297. SectionInfo
  1298. ( SourceLineInfo const& _lineInfo,
  1299. std::string const& _name,
  1300. std::string const& _description = std::string() );
  1301. std::string name;
  1302. std::string description;
  1303. SourceLineInfo lineInfo;
  1304. };
  1305. struct SectionEndInfo {
  1306. SectionEndInfo( SectionInfo const& _sectionInfo, Counts const& _prevAssertions, double _durationInSeconds );
  1307. SectionInfo sectionInfo;
  1308. Counts prevAssertions;
  1309. double durationInSeconds;
  1310. };
  1311. } // end namespace Catch
  1312. // end catch_section_info.h
  1313. // start catch_timer.h
  1314. #include <cstdint>
  1315. namespace Catch {
  1316. auto getCurrentNanosecondsSinceEpoch() -> uint64_t;
  1317. auto getEstimatedClockResolution() -> uint64_t;
  1318. class Timer {
  1319. uint64_t m_nanoseconds = 0;
  1320. public:
  1321. void start();
  1322. auto getElapsedNanoseconds() const -> unsigned int;
  1323. auto getElapsedMicroseconds() const -> unsigned int;
  1324. auto getElapsedMilliseconds() const -> unsigned int;
  1325. auto getElapsedSeconds() const -> double;
  1326. };
  1327. } // namespace Catch
  1328. // end catch_timer.h
  1329. #include <string>
  1330. namespace Catch {
  1331. class Section : NonCopyable {
  1332. public:
  1333. Section( SectionInfo const& info );
  1334. ~Section();
  1335. // This indicates whether the section should be executed or not
  1336. explicit operator bool() const;
  1337. private:
  1338. SectionInfo m_info;
  1339. std::string m_name;
  1340. Counts m_assertions;
  1341. bool m_sectionIncluded;
  1342. Timer m_timer;
  1343. };
  1344. } // end namespace Catch
  1345. #define INTERNAL_CATCH_SECTION( ... ) \
  1346. if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) )
  1347. // end catch_section.h
  1348. // start catch_benchmark.h
  1349. #include <cstdint>
  1350. #include <string>
  1351. namespace Catch {
  1352. class BenchmarkLooper {
  1353. std::string m_name;
  1354. std::size_t m_count = 0;
  1355. std::size_t m_iterationsToRun = 1;
  1356. uint64_t m_resolution;
  1357. Timer m_timer;
  1358. static auto getResolution() -> uint64_t;
  1359. public:
  1360. // Keep most of this inline as it's on the code path that is being timed
  1361. BenchmarkLooper( StringRef name )
  1362. : m_name( name ),
  1363. m_resolution( getResolution() )
  1364. {
  1365. reportStart();
  1366. m_timer.start();
  1367. }
  1368. explicit operator bool() {
  1369. if( m_count < m_iterationsToRun )
  1370. return true;
  1371. return needsMoreIterations();
  1372. }
  1373. void increment() {
  1374. ++m_count;
  1375. }
  1376. void reportStart();
  1377. auto needsMoreIterations() -> bool;
  1378. };
  1379. } // end namespace Catch
  1380. #define BENCHMARK( name ) \
  1381. for( Catch::BenchmarkLooper looper( name ); looper; looper.increment() )
  1382. // end catch_benchmark.h
  1383. // start catch_interfaces_exception.h
  1384. // start catch_interfaces_registry_hub.h
  1385. #include <string>
  1386. #include <memory>
  1387. namespace Catch {
  1388. class TestCase;
  1389. struct ITestCaseRegistry;
  1390. struct IExceptionTranslatorRegistry;
  1391. struct IExceptionTranslator;
  1392. struct IReporterRegistry;
  1393. struct IReporterFactory;
  1394. struct ITagAliasRegistry;
  1395. class StartupExceptionRegistry;
  1396. using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
  1397. struct IRegistryHub {
  1398. virtual ~IRegistryHub();
  1399. virtual IReporterRegistry const& getReporterRegistry() const = 0;
  1400. virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0;
  1401. virtual ITagAliasRegistry const& getTagAliasRegistry() const = 0;
  1402. virtual IExceptionTranslatorRegistry& getExceptionTranslatorRegistry() = 0;
  1403. virtual StartupExceptionRegistry const& getStartupExceptionRegistry() const = 0;
  1404. };
  1405. struct IMutableRegistryHub {
  1406. virtual ~IMutableRegistryHub();
  1407. virtual void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) = 0;
  1408. virtual void registerListener( IReporterFactoryPtr const& factory ) = 0;
  1409. virtual void registerTest( TestCase const& testInfo ) = 0;
  1410. virtual void registerTranslator( const IExceptionTranslator* translator ) = 0;
  1411. virtual void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) = 0;
  1412. virtual void registerStartupException() noexcept = 0;
  1413. };
  1414. IRegistryHub& getRegistryHub();
  1415. IMutableRegistryHub& getMutableRegistryHub();
  1416. void cleanUp();
  1417. std::string translateActiveException();
  1418. }
  1419. // end catch_interfaces_registry_hub.h
  1420. #if defined(CATCH_CONFIG_DISABLE)
  1421. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( translatorName, signature) \
  1422. static std::string translatorName( signature )
  1423. #endif
  1424. #include <exception>
  1425. #include <string>
  1426. #include <vector>
  1427. namespace Catch {
  1428. using exceptionTranslateFunction = std::string(*)();
  1429. struct IExceptionTranslator;
  1430. using ExceptionTranslators = std::vector<std::unique_ptr<IExceptionTranslator const>>;
  1431. struct IExceptionTranslator {
  1432. virtual ~IExceptionTranslator();
  1433. virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const = 0;
  1434. };
  1435. struct IExceptionTranslatorRegistry {
  1436. virtual ~IExceptionTranslatorRegistry();
  1437. virtual std::string translateActiveException() const = 0;
  1438. };
  1439. class ExceptionTranslatorRegistrar {
  1440. template<typename T>
  1441. class ExceptionTranslator : public IExceptionTranslator {
  1442. public:
  1443. ExceptionTranslator( std::string(*translateFunction)( T& ) )
  1444. : m_translateFunction( translateFunction )
  1445. {}
  1446. std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const override {
  1447. try {
  1448. if( it == itEnd )
  1449. std::rethrow_exception(std::current_exception());
  1450. else
  1451. return (*it)->translate( it+1, itEnd );
  1452. }
  1453. catch( T& ex ) {
  1454. return m_translateFunction( ex );
  1455. }
  1456. }
  1457. protected:
  1458. std::string(*m_translateFunction)( T& );
  1459. };
  1460. public:
  1461. template<typename T>
  1462. ExceptionTranslatorRegistrar( std::string(*translateFunction)( T& ) ) {
  1463. getMutableRegistryHub().registerTranslator
  1464. ( new ExceptionTranslator<T>( translateFunction ) );
  1465. }
  1466. };
  1467. }
  1468. ///////////////////////////////////////////////////////////////////////////////
  1469. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION2( translatorName, signature ) \
  1470. static std::string translatorName( signature ); \
  1471. namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &translatorName ); }\
  1472. static std::string translatorName( signature )
  1473. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
  1474. // end catch_interfaces_exception.h
  1475. // start catch_approx.h
  1476. // start catch_enforce.h
  1477. #include <sstream>
  1478. #include <stdexcept>
  1479. #define CATCH_PREPARE_EXCEPTION( type, msg ) \
  1480. type( static_cast<std::ostringstream&&>( std::ostringstream() << msg ).str() )
  1481. #define CATCH_INTERNAL_ERROR( msg ) \
  1482. throw CATCH_PREPARE_EXCEPTION( std::logic_error, CATCH_INTERNAL_LINEINFO << ": Internal Catch error: " << msg);
  1483. #define CATCH_ERROR( msg ) \
  1484. throw CATCH_PREPARE_EXCEPTION( std::domain_error, msg )
  1485. #define CATCH_ENFORCE( condition, msg ) \
  1486. do{ if( !(condition) ) CATCH_ERROR( msg ); } while(false)
  1487. // end catch_enforce.h
  1488. #include <type_traits>
  1489. namespace Catch {
  1490. namespace Detail {
  1491. class Approx {
  1492. private:
  1493. bool equalityComparisonImpl(double other) const;
  1494. public:
  1495. explicit Approx ( double value );
  1496. static Approx custom();
  1497. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1498. Approx operator()( T const& value ) {
  1499. Approx approx( static_cast<double>(value) );
  1500. approx.epsilon( m_epsilon );
  1501. approx.margin( m_margin );
  1502. approx.scale( m_scale );
  1503. return approx;
  1504. }
  1505. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1506. explicit Approx( T const& value ): Approx(static_cast<double>(value))
  1507. {}
  1508. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1509. friend bool operator == ( const T& lhs, Approx const& rhs ) {
  1510. auto lhs_v = static_cast<double>(lhs);
  1511. return rhs.equalityComparisonImpl(lhs_v);
  1512. }
  1513. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1514. friend bool operator == ( Approx const& lhs, const T& rhs ) {
  1515. return operator==( rhs, lhs );
  1516. }
  1517. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1518. friend bool operator != ( T const& lhs, Approx const& rhs ) {
  1519. return !operator==( lhs, rhs );
  1520. }
  1521. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1522. friend bool operator != ( Approx const& lhs, T const& rhs ) {
  1523. return !operator==( rhs, lhs );
  1524. }
  1525. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1526. friend bool operator <= ( T const& lhs, Approx const& rhs ) {
  1527. return static_cast<double>(lhs) < rhs.m_value || lhs == rhs;
  1528. }
  1529. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1530. friend bool operator <= ( Approx const& lhs, T const& rhs ) {
  1531. return lhs.m_value < static_cast<double>(rhs) || lhs == rhs;
  1532. }
  1533. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1534. friend bool operator >= ( T const& lhs, Approx const& rhs ) {
  1535. return static_cast<double>(lhs) > rhs.m_value || lhs == rhs;
  1536. }
  1537. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1538. friend bool operator >= ( Approx const& lhs, T const& rhs ) {
  1539. return lhs.m_value > static_cast<double>(rhs) || lhs == rhs;
  1540. }
  1541. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1542. Approx& epsilon( T const& newEpsilon ) {
  1543. double epsilonAsDouble = static_cast<double>(newEpsilon);
  1544. CATCH_ENFORCE(epsilonAsDouble >= 0 && epsilonAsDouble <= 1.0,
  1545. "Invalid Approx::epsilon: " << epsilonAsDouble
  1546. << ", Approx::epsilon has to be between 0 and 1");
  1547. m_epsilon = epsilonAsDouble;
  1548. return *this;
  1549. }
  1550. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1551. Approx& margin( T const& newMargin ) {
  1552. double marginAsDouble = static_cast<double>(newMargin);
  1553. CATCH_ENFORCE(marginAsDouble >= 0,
  1554. "Invalid Approx::margin: " << marginAsDouble
  1555. << ", Approx::Margin has to be non-negative.");
  1556. m_margin = marginAsDouble;
  1557. return *this;
  1558. }
  1559. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1560. Approx& scale( T const& newScale ) {
  1561. m_scale = static_cast<double>(newScale);
  1562. return *this;
  1563. }
  1564. std::string toString() const;
  1565. private:
  1566. double m_epsilon;
  1567. double m_margin;
  1568. double m_scale;
  1569. double m_value;
  1570. };
  1571. }
  1572. template<>
  1573. struct StringMaker<Catch::Detail::Approx> {
  1574. static std::string convert(Catch::Detail::Approx const& value);
  1575. };
  1576. } // end namespace Catch
  1577. // end catch_approx.h
  1578. // start catch_string_manip.h
  1579. #include <string>
  1580. #include <iosfwd>
  1581. namespace Catch {
  1582. bool startsWith( std::string const& s, std::string const& prefix );
  1583. bool startsWith( std::string const& s, char prefix );
  1584. bool endsWith( std::string const& s, std::string const& suffix );
  1585. bool endsWith( std::string const& s, char suffix );
  1586. bool contains( std::string const& s, std::string const& infix );
  1587. void toLowerInPlace( std::string& s );
  1588. std::string toLower( std::string const& s );
  1589. std::string trim( std::string const& str );
  1590. bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis );
  1591. struct pluralise {
  1592. pluralise( std::size_t count, std::string const& label );
  1593. friend std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser );
  1594. std::size_t m_count;
  1595. std::string m_label;
  1596. };
  1597. }
  1598. // end catch_string_manip.h
  1599. #ifndef CATCH_CONFIG_DISABLE_MATCHERS
  1600. // start catch_capture_matchers.h
  1601. // start catch_matchers.h
  1602. #include <string>
  1603. #include <vector>
  1604. namespace Catch {
  1605. namespace Matchers {
  1606. namespace Impl {
  1607. template<typename ArgT> struct MatchAllOf;
  1608. template<typename ArgT> struct MatchAnyOf;
  1609. template<typename ArgT> struct MatchNotOf;
  1610. class MatcherUntypedBase {
  1611. public:
  1612. MatcherUntypedBase() = default;
  1613. MatcherUntypedBase ( MatcherUntypedBase const& ) = default;
  1614. MatcherUntypedBase& operator = ( MatcherUntypedBase const& ) = delete;
  1615. std::string toString() const;
  1616. protected:
  1617. virtual ~MatcherUntypedBase();
  1618. virtual std::string describe() const = 0;
  1619. mutable std::string m_cachedToString;
  1620. };
  1621. template<typename ObjectT>
  1622. struct MatcherMethod {
  1623. virtual bool match( ObjectT const& arg ) const = 0;
  1624. };
  1625. template<typename PtrT>
  1626. struct MatcherMethod<PtrT*> {
  1627. virtual bool match( PtrT* arg ) const = 0;
  1628. };
  1629. template<typename ObjectT, typename ComparatorT = ObjectT>
  1630. struct MatcherBase : MatcherUntypedBase, MatcherMethod<ObjectT> {
  1631. MatchAllOf<ComparatorT> operator && ( MatcherBase const& other ) const;
  1632. MatchAnyOf<ComparatorT> operator || ( MatcherBase const& other ) const;
  1633. MatchNotOf<ComparatorT> operator ! () const;
  1634. };
  1635. template<typename ArgT>
  1636. struct MatchAllOf : MatcherBase<ArgT> {
  1637. bool match( ArgT const& arg ) const override {
  1638. for( auto matcher : m_matchers ) {
  1639. if (!matcher->match(arg))
  1640. return false;
  1641. }
  1642. return true;
  1643. }
  1644. std::string describe() const override {
  1645. std::string description;
  1646. description.reserve( 4 + m_matchers.size()*32 );
  1647. description += "( ";
  1648. bool first = true;
  1649. for( auto matcher : m_matchers ) {
  1650. if( first )
  1651. first = false;
  1652. else
  1653. description += " and ";
  1654. description += matcher->toString();
  1655. }
  1656. description += " )";
  1657. return description;
  1658. }
  1659. MatchAllOf<ArgT>& operator && ( MatcherBase<ArgT> const& other ) {
  1660. m_matchers.push_back( &other );
  1661. return *this;
  1662. }
  1663. std::vector<MatcherBase<ArgT> const*> m_matchers;
  1664. };
  1665. template<typename ArgT>
  1666. struct MatchAnyOf : MatcherBase<ArgT> {
  1667. bool match( ArgT const& arg ) const override {
  1668. for( auto matcher : m_matchers ) {
  1669. if (matcher->match(arg))
  1670. return true;
  1671. }
  1672. return false;
  1673. }
  1674. std::string describe() const override {
  1675. std::string description;
  1676. description.reserve( 4 + m_matchers.size()*32 );
  1677. description += "( ";
  1678. bool first = true;
  1679. for( auto matcher : m_matchers ) {
  1680. if( first )
  1681. first = false;
  1682. else
  1683. description += " or ";
  1684. description += matcher->toString();
  1685. }
  1686. description += " )";
  1687. return description;
  1688. }
  1689. MatchAnyOf<ArgT>& operator || ( MatcherBase<ArgT> const& other ) {
  1690. m_matchers.push_back( &other );
  1691. return *this;
  1692. }
  1693. std::vector<MatcherBase<ArgT> const*> m_matchers;
  1694. };
  1695. template<typename ArgT>
  1696. struct MatchNotOf : MatcherBase<ArgT> {
  1697. MatchNotOf( MatcherBase<ArgT> const& underlyingMatcher ) : m_underlyingMatcher( underlyingMatcher ) {}
  1698. bool match( ArgT const& arg ) const override {
  1699. return !m_underlyingMatcher.match( arg );
  1700. }
  1701. std::string describe() const override {
  1702. return "not " + m_underlyingMatcher.toString();
  1703. }
  1704. MatcherBase<ArgT> const& m_underlyingMatcher;
  1705. };
  1706. template<typename ObjectT, typename ComparatorT>
  1707. MatchAllOf<ComparatorT> MatcherBase<ObjectT, ComparatorT>::operator && ( MatcherBase const& other ) const {
  1708. return MatchAllOf<ComparatorT>() && *this && other;
  1709. }
  1710. template<typename ObjectT, typename ComparatorT>
  1711. MatchAnyOf<ComparatorT> MatcherBase<ObjectT, ComparatorT>::operator || ( MatcherBase const& other ) const {
  1712. return MatchAnyOf<ComparatorT>() || *this || other;
  1713. }
  1714. template<typename ObjectT, typename ComparatorT>
  1715. MatchNotOf<ComparatorT> MatcherBase<ObjectT, ComparatorT>::operator ! () const {
  1716. return MatchNotOf<ComparatorT>( *this );
  1717. }
  1718. } // namespace Impl
  1719. } // namespace Matchers
  1720. using namespace Matchers;
  1721. using Matchers::Impl::MatcherBase;
  1722. } // namespace Catch
  1723. // end catch_matchers.h
  1724. // start catch_matchers_string.h
  1725. #include <string>
  1726. namespace Catch {
  1727. namespace Matchers {
  1728. namespace StdString {
  1729. struct CasedString
  1730. {
  1731. CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity );
  1732. std::string adjustString( std::string const& str ) const;
  1733. std::string caseSensitivitySuffix() const;
  1734. CaseSensitive::Choice m_caseSensitivity;
  1735. std::string m_str;
  1736. };
  1737. struct StringMatcherBase : MatcherBase<std::string> {
  1738. StringMatcherBase( std::string const& operation, CasedString const& comparator );
  1739. std::string describe() const override;
  1740. CasedString m_comparator;
  1741. std::string m_operation;
  1742. };
  1743. struct EqualsMatcher : StringMatcherBase {
  1744. EqualsMatcher( CasedString const& comparator );
  1745. bool match( std::string const& source ) const override;
  1746. };
  1747. struct ContainsMatcher : StringMatcherBase {
  1748. ContainsMatcher( CasedString const& comparator );
  1749. bool match( std::string const& source ) const override;
  1750. };
  1751. struct StartsWithMatcher : StringMatcherBase {
  1752. StartsWithMatcher( CasedString const& comparator );
  1753. bool match( std::string const& source ) const override;
  1754. };
  1755. struct EndsWithMatcher : StringMatcherBase {
  1756. EndsWithMatcher( CasedString const& comparator );
  1757. bool match( std::string const& source ) const override;
  1758. };
  1759. } // namespace StdString
  1760. // The following functions create the actual matcher objects.
  1761. // This allows the types to be inferred
  1762. StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  1763. StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  1764. StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  1765. StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  1766. } // namespace Matchers
  1767. } // namespace Catch
  1768. // end catch_matchers_string.h
  1769. // start catch_matchers_vector.h
  1770. namespace Catch {
  1771. namespace Matchers {
  1772. namespace Vector {
  1773. template<typename T>
  1774. struct ContainsElementMatcher : MatcherBase<std::vector<T>, T> {
  1775. ContainsElementMatcher(T const &comparator) : m_comparator( comparator) {}
  1776. bool match(std::vector<T> const &v) const override {
  1777. for (auto const& el : v) {
  1778. if (el == m_comparator) {
  1779. return true;
  1780. }
  1781. }
  1782. return false;
  1783. }
  1784. std::string describe() const override {
  1785. return "Contains: " + ::Catch::Detail::stringify( m_comparator );
  1786. }
  1787. T const& m_comparator;
  1788. };
  1789. template<typename T>
  1790. struct ContainsMatcher : MatcherBase<std::vector<T>, std::vector<T> > {
  1791. ContainsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}
  1792. bool match(std::vector<T> const &v) const override {
  1793. // !TBD: see note in EqualsMatcher
  1794. if (m_comparator.size() > v.size())
  1795. return false;
  1796. for (auto const& comparator : m_comparator) {
  1797. auto present = false;
  1798. for (const auto& el : v) {
  1799. if (el == comparator) {
  1800. present = true;
  1801. break;
  1802. }
  1803. }
  1804. if (!present) {
  1805. return false;
  1806. }
  1807. }
  1808. return true;
  1809. }
  1810. std::string describe() const override {
  1811. return "Contains: " + ::Catch::Detail::stringify( m_comparator );
  1812. }
  1813. std::vector<T> const& m_comparator;
  1814. };
  1815. template<typename T>
  1816. struct EqualsMatcher : MatcherBase<std::vector<T>, std::vector<T> > {
  1817. EqualsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}
  1818. bool match(std::vector<T> const &v) const override {
  1819. // !TBD: This currently works if all elements can be compared using !=
  1820. // - a more general approach would be via a compare template that defaults
  1821. // to using !=. but could be specialised for, e.g. std::vector<T> etc
  1822. // - then just call that directly
  1823. if (m_comparator.size() != v.size())
  1824. return false;
  1825. for (std::size_t i = 0; i < v.size(); ++i)
  1826. if (m_comparator[i] != v[i])
  1827. return false;
  1828. return true;
  1829. }
  1830. std::string describe() const override {
  1831. return "Equals: " + ::Catch::Detail::stringify( m_comparator );
  1832. }
  1833. std::vector<T> const& m_comparator;
  1834. };
  1835. } // namespace Vector
  1836. // The following functions create the actual matcher objects.
  1837. // This allows the types to be inferred
  1838. template<typename T>
  1839. Vector::ContainsMatcher<T> Contains( std::vector<T> const& comparator ) {
  1840. return Vector::ContainsMatcher<T>( comparator );
  1841. }
  1842. template<typename T>
  1843. Vector::ContainsElementMatcher<T> VectorContains( T const& comparator ) {
  1844. return Vector::ContainsElementMatcher<T>( comparator );
  1845. }
  1846. template<typename T>
  1847. Vector::EqualsMatcher<T> Equals( std::vector<T> const& comparator ) {
  1848. return Vector::EqualsMatcher<T>( comparator );
  1849. }
  1850. } // namespace Matchers
  1851. } // namespace Catch
  1852. // end catch_matchers_vector.h
  1853. namespace Catch {
  1854. template<typename ArgT, typename MatcherT>
  1855. class MatchExpr : public ITransientExpression {
  1856. ArgT const& m_arg;
  1857. MatcherT m_matcher;
  1858. StringRef m_matcherString;
  1859. bool m_result;
  1860. public:
  1861. MatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef matcherString )
  1862. : m_arg( arg ),
  1863. m_matcher( matcher ),
  1864. m_matcherString( matcherString ),
  1865. m_result( matcher.match( arg ) )
  1866. {}
  1867. auto isBinaryExpression() const -> bool override { return true; }
  1868. auto getResult() const -> bool override { return m_result; }
  1869. void streamReconstructedExpression( std::ostream &os ) const override {
  1870. auto matcherAsString = m_matcher.toString();
  1871. os << Catch::Detail::stringify( m_arg ) << ' ';
  1872. if( matcherAsString == Detail::unprintableString )
  1873. os << m_matcherString;
  1874. else
  1875. os << matcherAsString;
  1876. }
  1877. };
  1878. using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
  1879. void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef matcherString );
  1880. template<typename ArgT, typename MatcherT>
  1881. auto makeMatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef matcherString ) -> MatchExpr<ArgT, MatcherT> {
  1882. return MatchExpr<ArgT, MatcherT>( arg, matcher, matcherString );
  1883. }
  1884. } // namespace Catch
  1885. ///////////////////////////////////////////////////////////////////////////////
  1886. #define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \
  1887. do { \
  1888. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  1889. INTERNAL_CATCH_TRY( catchAssertionHandler ) { \
  1890. catchAssertionHandler.handle( Catch::makeMatchExpr( arg, matcher, #matcher ) ); \
  1891. } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
  1892. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1893. } while( Catch::alwaysFalse() )
  1894. ///////////////////////////////////////////////////////////////////////////////
  1895. #define INTERNAL_CATCH_THROWS_MATCHES( macroName, exceptionType, resultDisposition, matcher, ... ) \
  1896. do { \
  1897. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(exceptionType) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  1898. if( catchAssertionHandler.allowThrows() ) \
  1899. try { \
  1900. static_cast<void>(__VA_ARGS__ ); \
  1901. catchAssertionHandler.handle( Catch::ResultWas::DidntThrowException ); \
  1902. } \
  1903. catch( exceptionType const& ex ) { \
  1904. catchAssertionHandler.handle( Catch::makeMatchExpr( ex, matcher, #matcher ) ); \
  1905. } \
  1906. catch( ... ) { \
  1907. catchAssertionHandler.useActiveException(); \
  1908. } \
  1909. else \
  1910. catchAssertionHandler.handle( Catch::ResultWas::Ok ); \
  1911. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1912. } while( Catch::alwaysFalse() )
  1913. // end catch_capture_matchers.h
  1914. #endif
  1915. // These files are included here so the single_include script doesn't put them
  1916. // in the conditionally compiled sections
  1917. // start catch_test_case_info.h
  1918. #include <string>
  1919. #include <vector>
  1920. #include <memory>
  1921. #ifdef __clang__
  1922. #pragma clang diagnostic push
  1923. #pragma clang diagnostic ignored "-Wpadded"
  1924. #endif
  1925. namespace Catch {
  1926. struct ITestInvoker;
  1927. struct TestCaseInfo {
  1928. enum SpecialProperties{
  1929. None = 0,
  1930. IsHidden = 1 << 1,
  1931. ShouldFail = 1 << 2,
  1932. MayFail = 1 << 3,
  1933. Throws = 1 << 4,
  1934. NonPortable = 1 << 5,
  1935. Benchmark = 1 << 6
  1936. };
  1937. TestCaseInfo( std::string const& _name,
  1938. std::string const& _className,
  1939. std::string const& _description,
  1940. std::vector<std::string> const& _tags,
  1941. SourceLineInfo const& _lineInfo );
  1942. friend void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags );
  1943. bool isHidden() const;
  1944. bool throws() const;
  1945. bool okToFail() const;
  1946. bool expectedToFail() const;
  1947. std::string tagsAsString() const;
  1948. std::string name;
  1949. std::string className;
  1950. std::string description;
  1951. std::vector<std::string> tags;
  1952. std::vector<std::string> lcaseTags;
  1953. SourceLineInfo lineInfo;
  1954. SpecialProperties properties;
  1955. };
  1956. class TestCase : public TestCaseInfo {
  1957. public:
  1958. TestCase( ITestInvoker* testCase, TestCaseInfo const& info );
  1959. TestCase withName( std::string const& _newName ) const;
  1960. void invoke() const;
  1961. TestCaseInfo const& getTestCaseInfo() const;
  1962. bool operator == ( TestCase const& other ) const;
  1963. bool operator < ( TestCase const& other ) const;
  1964. private:
  1965. std::shared_ptr<ITestInvoker> test;
  1966. };
  1967. TestCase makeTestCase( ITestInvoker* testCase,
  1968. std::string const& className,
  1969. std::string const& name,
  1970. std::string const& description,
  1971. SourceLineInfo const& lineInfo );
  1972. }
  1973. #ifdef __clang__
  1974. #pragma clang diagnostic pop
  1975. #endif
  1976. // end catch_test_case_info.h
  1977. // start catch_interfaces_runner.h
  1978. namespace Catch {
  1979. struct IRunner {
  1980. virtual ~IRunner();
  1981. virtual bool aborting() const = 0;
  1982. };
  1983. }
  1984. // end catch_interfaces_runner.h
  1985. #ifdef __OBJC__
  1986. // start catch_objc.hpp
  1987. #import <objc/runtime.h>
  1988. #include <string>
  1989. // NB. Any general catch headers included here must be included
  1990. // in catch.hpp first to make sure they are included by the single
  1991. // header for non obj-usage
  1992. ///////////////////////////////////////////////////////////////////////////////
  1993. // This protocol is really only here for (self) documenting purposes, since
  1994. // all its methods are optional.
  1995. @protocol OcFixture
  1996. @optional
  1997. -(void) setUp;
  1998. -(void) tearDown;
  1999. @end
  2000. namespace Catch {
  2001. class OcMethod : public ITestInvoker {
  2002. public:
  2003. OcMethod( Class cls, SEL sel ) : m_cls( cls ), m_sel( sel ) {}
  2004. virtual void invoke() const {
  2005. id obj = [[m_cls alloc] init];
  2006. performOptionalSelector( obj, @selector(setUp) );
  2007. performOptionalSelector( obj, m_sel );
  2008. performOptionalSelector( obj, @selector(tearDown) );
  2009. arcSafeRelease( obj );
  2010. }
  2011. private:
  2012. virtual ~OcMethod() {}
  2013. Class m_cls;
  2014. SEL m_sel;
  2015. };
  2016. namespace Detail{
  2017. inline std::string getAnnotation( Class cls,
  2018. std::string const& annotationName,
  2019. std::string const& testCaseName ) {
  2020. NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()];
  2021. SEL sel = NSSelectorFromString( selStr );
  2022. arcSafeRelease( selStr );
  2023. id value = performOptionalSelector( cls, sel );
  2024. if( value )
  2025. return [(NSString*)value UTF8String];
  2026. return "";
  2027. }
  2028. }
  2029. inline std::size_t registerTestMethods() {
  2030. std::size_t noTestMethods = 0;
  2031. int noClasses = objc_getClassList( nullptr, 0 );
  2032. Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc( sizeof(Class) * noClasses);
  2033. objc_getClassList( classes, noClasses );
  2034. for( int c = 0; c < noClasses; c++ ) {
  2035. Class cls = classes[c];
  2036. {
  2037. u_int count;
  2038. Method* methods = class_copyMethodList( cls, &count );
  2039. for( u_int m = 0; m < count ; m++ ) {
  2040. SEL selector = method_getName(methods[m]);
  2041. std::string methodName = sel_getName(selector);
  2042. if( startsWith( methodName, "Catch_TestCase_" ) ) {
  2043. std::string testCaseName = methodName.substr( 15 );
  2044. std::string name = Detail::getAnnotation( cls, "Name", testCaseName );
  2045. std::string desc = Detail::getAnnotation( cls, "Description", testCaseName );
  2046. const char* className = class_getName( cls );
  2047. getMutableRegistryHub().registerTest( makeTestCase( new OcMethod( cls, selector ), className, name.c_str(), desc.c_str(), SourceLineInfo("",0) ) );
  2048. noTestMethods++;
  2049. }
  2050. }
  2051. free(methods);
  2052. }
  2053. }
  2054. return noTestMethods;
  2055. }
  2056. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  2057. namespace Matchers {
  2058. namespace Impl {
  2059. namespace NSStringMatchers {
  2060. struct StringHolder : MatcherBase<NSString*>{
  2061. StringHolder( NSString* substr ) : m_substr( [substr copy] ){}
  2062. StringHolder( StringHolder const& other ) : m_substr( [other.m_substr copy] ){}
  2063. StringHolder() {
  2064. arcSafeRelease( m_substr );
  2065. }
  2066. bool match( NSString* arg ) const override {
  2067. return false;
  2068. }
  2069. NSString* CATCH_ARC_STRONG m_substr;
  2070. };
  2071. struct Equals : StringHolder {
  2072. Equals( NSString* substr ) : StringHolder( substr ){}
  2073. bool match( NSString* str ) const override {
  2074. return (str != nil || m_substr == nil ) &&
  2075. [str isEqualToString:m_substr];
  2076. }
  2077. std::string describe() const override {
  2078. return "equals string: " + Catch::Detail::stringify( m_substr );
  2079. }
  2080. };
  2081. struct Contains : StringHolder {
  2082. Contains( NSString* substr ) : StringHolder( substr ){}
  2083. bool match( NSString* str ) const {
  2084. return (str != nil || m_substr == nil ) &&
  2085. [str rangeOfString:m_substr].location != NSNotFound;
  2086. }
  2087. std::string describe() const override {
  2088. return "contains string: " + Catch::Detail::stringify( m_substr );
  2089. }
  2090. };
  2091. struct StartsWith : StringHolder {
  2092. StartsWith( NSString* substr ) : StringHolder( substr ){}
  2093. bool match( NSString* str ) const override {
  2094. return (str != nil || m_substr == nil ) &&
  2095. [str rangeOfString:m_substr].location == 0;
  2096. }
  2097. std::string describe() const override {
  2098. return "starts with: " + Catch::Detail::stringify( m_substr );
  2099. }
  2100. };
  2101. struct EndsWith : StringHolder {
  2102. EndsWith( NSString* substr ) : StringHolder( substr ){}
  2103. bool match( NSString* str ) const override {
  2104. return (str != nil || m_substr == nil ) &&
  2105. [str rangeOfString:m_substr].location == [str length] - [m_substr length];
  2106. }
  2107. std::string describe() const override {
  2108. return "ends with: " + Catch::Detail::stringify( m_substr );
  2109. }
  2110. };
  2111. } // namespace NSStringMatchers
  2112. } // namespace Impl
  2113. inline Impl::NSStringMatchers::Equals
  2114. Equals( NSString* substr ){ return Impl::NSStringMatchers::Equals( substr ); }
  2115. inline Impl::NSStringMatchers::Contains
  2116. Contains( NSString* substr ){ return Impl::NSStringMatchers::Contains( substr ); }
  2117. inline Impl::NSStringMatchers::StartsWith
  2118. StartsWith( NSString* substr ){ return Impl::NSStringMatchers::StartsWith( substr ); }
  2119. inline Impl::NSStringMatchers::EndsWith
  2120. EndsWith( NSString* substr ){ return Impl::NSStringMatchers::EndsWith( substr ); }
  2121. } // namespace Matchers
  2122. using namespace Matchers;
  2123. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  2124. } // namespace Catch
  2125. ///////////////////////////////////////////////////////////////////////////////
  2126. #define OC_MAKE_UNIQUE_NAME( root, uniqueSuffix ) root##uniqueSuffix
  2127. #define OC_TEST_CASE2( name, desc, uniqueSuffix ) \
  2128. +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Name_test_, uniqueSuffix ) \
  2129. { \
  2130. return @ name; \
  2131. } \
  2132. +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Description_test_, uniqueSuffix ) \
  2133. { \
  2134. return @ desc; \
  2135. } \
  2136. -(void) OC_MAKE_UNIQUE_NAME( Catch_TestCase_test_, uniqueSuffix )
  2137. #define OC_TEST_CASE( name, desc ) OC_TEST_CASE2( name, desc, __LINE__ )
  2138. // end catch_objc.hpp
  2139. #endif
  2140. #ifdef CATCH_CONFIG_EXTERNAL_INTERFACES
  2141. // start catch_external_interfaces.h
  2142. // start catch_reporter_bases.hpp
  2143. // start catch_interfaces_reporter.h
  2144. // start catch_config.hpp
  2145. // start catch_test_spec_parser.h
  2146. #ifdef __clang__
  2147. #pragma clang diagnostic push
  2148. #pragma clang diagnostic ignored "-Wpadded"
  2149. #endif
  2150. // start catch_test_spec.h
  2151. #ifdef __clang__
  2152. #pragma clang diagnostic push
  2153. #pragma clang diagnostic ignored "-Wpadded"
  2154. #endif
  2155. // start catch_wildcard_pattern.h
  2156. namespace Catch
  2157. {
  2158. class WildcardPattern {
  2159. enum WildcardPosition {
  2160. NoWildcard = 0,
  2161. WildcardAtStart = 1,
  2162. WildcardAtEnd = 2,
  2163. WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd
  2164. };
  2165. public:
  2166. WildcardPattern( std::string const& pattern, CaseSensitive::Choice caseSensitivity );
  2167. virtual ~WildcardPattern() = default;
  2168. virtual bool matches( std::string const& str ) const;
  2169. private:
  2170. std::string adjustCase( std::string const& str ) const;
  2171. CaseSensitive::Choice m_caseSensitivity;
  2172. WildcardPosition m_wildcard = NoWildcard;
  2173. std::string m_pattern;
  2174. };
  2175. }
  2176. // end catch_wildcard_pattern.h
  2177. #include <string>
  2178. #include <vector>
  2179. #include <memory>
  2180. namespace Catch {
  2181. class TestSpec {
  2182. struct Pattern {
  2183. virtual ~Pattern();
  2184. virtual bool matches( TestCaseInfo const& testCase ) const = 0;
  2185. };
  2186. using PatternPtr = std::shared_ptr<Pattern>;
  2187. class NamePattern : public Pattern {
  2188. public:
  2189. NamePattern( std::string const& name );
  2190. virtual ~NamePattern();
  2191. virtual bool matches( TestCaseInfo const& testCase ) const override;
  2192. private:
  2193. WildcardPattern m_wildcardPattern;
  2194. };
  2195. class TagPattern : public Pattern {
  2196. public:
  2197. TagPattern( std::string const& tag );
  2198. virtual ~TagPattern();
  2199. virtual bool matches( TestCaseInfo const& testCase ) const override;
  2200. private:
  2201. std::string m_tag;
  2202. };
  2203. class ExcludedPattern : public Pattern {
  2204. public:
  2205. ExcludedPattern( PatternPtr const& underlyingPattern );
  2206. virtual ~ExcludedPattern();
  2207. virtual bool matches( TestCaseInfo const& testCase ) const override;
  2208. private:
  2209. PatternPtr m_underlyingPattern;
  2210. };
  2211. struct Filter {
  2212. std::vector<PatternPtr> m_patterns;
  2213. bool matches( TestCaseInfo const& testCase ) const;
  2214. };
  2215. public:
  2216. bool hasFilters() const;
  2217. bool matches( TestCaseInfo const& testCase ) const;
  2218. private:
  2219. std::vector<Filter> m_filters;
  2220. friend class TestSpecParser;
  2221. };
  2222. }
  2223. #ifdef __clang__
  2224. #pragma clang diagnostic pop
  2225. #endif
  2226. // end catch_test_spec.h
  2227. // start catch_interfaces_tag_alias_registry.h
  2228. #include <string>
  2229. namespace Catch {
  2230. struct TagAlias;
  2231. struct ITagAliasRegistry {
  2232. virtual ~ITagAliasRegistry();
  2233. // Nullptr if not present
  2234. virtual TagAlias const* find( std::string const& alias ) const = 0;
  2235. virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const = 0;
  2236. static ITagAliasRegistry const& get();
  2237. };
  2238. } // end namespace Catch
  2239. // end catch_interfaces_tag_alias_registry.h
  2240. namespace Catch {
  2241. class TestSpecParser {
  2242. enum Mode{ None, Name, QuotedName, Tag, EscapedName };
  2243. Mode m_mode = None;
  2244. bool m_exclusion = false;
  2245. std::size_t m_start = std::string::npos, m_pos = 0;
  2246. std::string m_arg;
  2247. std::vector<std::size_t> m_escapeChars;
  2248. TestSpec::Filter m_currentFilter;
  2249. TestSpec m_testSpec;
  2250. ITagAliasRegistry const* m_tagAliases = nullptr;
  2251. public:
  2252. TestSpecParser( ITagAliasRegistry const& tagAliases );
  2253. TestSpecParser& parse( std::string const& arg );
  2254. TestSpec testSpec();
  2255. private:
  2256. void visitChar( char c );
  2257. void startNewMode( Mode mode, std::size_t start );
  2258. void escape();
  2259. std::string subString() const;
  2260. template<typename T>
  2261. void addPattern() {
  2262. std::string token = subString();
  2263. for( std::size_t i = 0; i < m_escapeChars.size(); ++i )
  2264. token = token.substr( 0, m_escapeChars[i]-m_start-i ) + token.substr( m_escapeChars[i]-m_start-i+1 );
  2265. m_escapeChars.clear();
  2266. if( startsWith( token, "exclude:" ) ) {
  2267. m_exclusion = true;
  2268. token = token.substr( 8 );
  2269. }
  2270. if( !token.empty() ) {
  2271. TestSpec::PatternPtr pattern = std::make_shared<T>( token );
  2272. if( m_exclusion )
  2273. pattern = std::make_shared<TestSpec::ExcludedPattern>( pattern );
  2274. m_currentFilter.m_patterns.push_back( pattern );
  2275. }
  2276. m_exclusion = false;
  2277. m_mode = None;
  2278. }
  2279. void addFilter();
  2280. };
  2281. TestSpec parseTestSpec( std::string const& arg );
  2282. } // namespace Catch
  2283. #ifdef __clang__
  2284. #pragma clang diagnostic pop
  2285. #endif
  2286. // end catch_test_spec_parser.h
  2287. // start catch_interfaces_config.h
  2288. #include <iosfwd>
  2289. #include <string>
  2290. #include <vector>
  2291. #include <memory>
  2292. namespace Catch {
  2293. enum class Verbosity {
  2294. Quiet = 0,
  2295. Normal,
  2296. High
  2297. };
  2298. struct WarnAbout { enum What {
  2299. Nothing = 0x00,
  2300. NoAssertions = 0x01
  2301. }; };
  2302. struct ShowDurations { enum OrNot {
  2303. DefaultForReporter,
  2304. Always,
  2305. Never
  2306. }; };
  2307. struct RunTests { enum InWhatOrder {
  2308. InDeclarationOrder,
  2309. InLexicographicalOrder,
  2310. InRandomOrder
  2311. }; };
  2312. struct UseColour { enum YesOrNo {
  2313. Auto,
  2314. Yes,
  2315. No
  2316. }; };
  2317. struct WaitForKeypress { enum When {
  2318. Never,
  2319. BeforeStart = 1,
  2320. BeforeExit = 2,
  2321. BeforeStartAndExit = BeforeStart | BeforeExit
  2322. }; };
  2323. class TestSpec;
  2324. struct IConfig : NonCopyable {
  2325. virtual ~IConfig();
  2326. virtual bool allowThrows() const = 0;
  2327. virtual std::ostream& stream() const = 0;
  2328. virtual std::string name() const = 0;
  2329. virtual bool includeSuccessfulResults() const = 0;
  2330. virtual bool shouldDebugBreak() const = 0;
  2331. virtual bool warnAboutMissingAssertions() const = 0;
  2332. virtual int abortAfter() const = 0;
  2333. virtual bool showInvisibles() const = 0;
  2334. virtual ShowDurations::OrNot showDurations() const = 0;
  2335. virtual TestSpec const& testSpec() const = 0;
  2336. virtual RunTests::InWhatOrder runOrder() const = 0;
  2337. virtual unsigned int rngSeed() const = 0;
  2338. virtual int benchmarkResolutionMultiple() const = 0;
  2339. virtual UseColour::YesOrNo useColour() const = 0;
  2340. virtual std::vector<std::string> const& getSectionsToRun() const = 0;
  2341. virtual Verbosity verbosity() const = 0;
  2342. };
  2343. using IConfigPtr = std::shared_ptr<IConfig const>;
  2344. }
  2345. // end catch_interfaces_config.h
  2346. // Libstdc++ doesn't like incomplete classes for unique_ptr
  2347. // start catch_stream.h
  2348. // start catch_streambuf.h
  2349. #include <streambuf>
  2350. namespace Catch {
  2351. class StreamBufBase : public std::streambuf {
  2352. public:
  2353. virtual ~StreamBufBase();
  2354. };
  2355. }
  2356. // end catch_streambuf.h
  2357. #include <streambuf>
  2358. #include <ostream>
  2359. #include <fstream>
  2360. #include <memory>
  2361. namespace Catch {
  2362. std::ostream& cout();
  2363. std::ostream& cerr();
  2364. std::ostream& clog();
  2365. struct IStream {
  2366. virtual ~IStream();
  2367. virtual std::ostream& stream() const = 0;
  2368. };
  2369. class FileStream : public IStream {
  2370. mutable std::ofstream m_ofs;
  2371. public:
  2372. FileStream( std::string const& filename );
  2373. ~FileStream() override = default;
  2374. public: // IStream
  2375. std::ostream& stream() const override;
  2376. };
  2377. class CoutStream : public IStream {
  2378. mutable std::ostream m_os;
  2379. public:
  2380. CoutStream();
  2381. ~CoutStream() override = default;
  2382. public: // IStream
  2383. std::ostream& stream() const override;
  2384. };
  2385. class DebugOutStream : public IStream {
  2386. std::unique_ptr<StreamBufBase> m_streamBuf;
  2387. mutable std::ostream m_os;
  2388. public:
  2389. DebugOutStream();
  2390. ~DebugOutStream() override = default;
  2391. public: // IStream
  2392. std::ostream& stream() const override;
  2393. };
  2394. }
  2395. // end catch_stream.h
  2396. #include <memory>
  2397. #include <vector>
  2398. #include <string>
  2399. #ifndef CATCH_CONFIG_CONSOLE_WIDTH
  2400. #define CATCH_CONFIG_CONSOLE_WIDTH 80
  2401. #endif
  2402. namespace Catch {
  2403. struct IStream;
  2404. struct ConfigData {
  2405. bool listTests = false;
  2406. bool listTags = false;
  2407. bool listReporters = false;
  2408. bool listTestNamesOnly = false;
  2409. bool showSuccessfulTests = false;
  2410. bool shouldDebugBreak = false;
  2411. bool noThrow = false;
  2412. bool showHelp = false;
  2413. bool showInvisibles = false;
  2414. bool filenamesAsTags = false;
  2415. bool libIdentify = false;
  2416. int abortAfter = -1;
  2417. unsigned int rngSeed = 0;
  2418. int benchmarkResolutionMultiple = 100;
  2419. Verbosity verbosity = Verbosity::Normal;
  2420. WarnAbout::What warnings = WarnAbout::Nothing;
  2421. ShowDurations::OrNot showDurations = ShowDurations::DefaultForReporter;
  2422. RunTests::InWhatOrder runOrder = RunTests::InDeclarationOrder;
  2423. UseColour::YesOrNo useColour = UseColour::Auto;
  2424. WaitForKeypress::When waitForKeypress = WaitForKeypress::Never;
  2425. std::string outputFilename;
  2426. std::string name;
  2427. std::string processName;
  2428. std::vector<std::string> reporterNames;
  2429. std::vector<std::string> testsOrTags;
  2430. std::vector<std::string> sectionsToRun;
  2431. };
  2432. class Config : public IConfig {
  2433. public:
  2434. Config() = default;
  2435. Config( ConfigData const& data );
  2436. virtual ~Config() = default;
  2437. std::string const& getFilename() const;
  2438. bool listTests() const;
  2439. bool listTestNamesOnly() const;
  2440. bool listTags() const;
  2441. bool listReporters() const;
  2442. std::string getProcessName() const;
  2443. std::vector<std::string> const& getReporterNames() const;
  2444. std::vector<std::string> const& getSectionsToRun() const override;
  2445. virtual TestSpec const& testSpec() const override;
  2446. bool showHelp() const;
  2447. // IConfig interface
  2448. bool allowThrows() const override;
  2449. std::ostream& stream() const override;
  2450. std::string name() const override;
  2451. bool includeSuccessfulResults() const override;
  2452. bool warnAboutMissingAssertions() const override;
  2453. ShowDurations::OrNot showDurations() const override;
  2454. RunTests::InWhatOrder runOrder() const override;
  2455. unsigned int rngSeed() const override;
  2456. int benchmarkResolutionMultiple() const override;
  2457. UseColour::YesOrNo useColour() const override;
  2458. bool shouldDebugBreak() const override;
  2459. int abortAfter() const override;
  2460. bool showInvisibles() const override;
  2461. Verbosity verbosity() const override;
  2462. private:
  2463. IStream const* openStream();
  2464. ConfigData m_data;
  2465. std::unique_ptr<IStream const> m_stream;
  2466. TestSpec m_testSpec;
  2467. };
  2468. } // end namespace Catch
  2469. // end catch_config.hpp
  2470. // start catch_assertionresult.h
  2471. #include <string>
  2472. namespace Catch {
  2473. struct AssertionResultData
  2474. {
  2475. AssertionResultData() = delete;
  2476. AssertionResultData( ResultWas::OfType _resultType, LazyExpression const& _lazyExpression );
  2477. std::string message;
  2478. mutable std::string reconstructedExpression;
  2479. LazyExpression lazyExpression;
  2480. ResultWas::OfType resultType;
  2481. std::string reconstructExpression() const;
  2482. };
  2483. class AssertionResult {
  2484. public:
  2485. AssertionResult() = delete;
  2486. AssertionResult( AssertionInfo const& info, AssertionResultData const& data );
  2487. bool isOk() const;
  2488. bool succeeded() const;
  2489. ResultWas::OfType getResultType() const;
  2490. bool hasExpression() const;
  2491. bool hasMessage() const;
  2492. std::string getExpression() const;
  2493. std::string getExpressionInMacro() const;
  2494. bool hasExpandedExpression() const;
  2495. std::string getExpandedExpression() const;
  2496. std::string getMessage() const;
  2497. SourceLineInfo getSourceInfo() const;
  2498. std::string getTestMacroName() const;
  2499. //protected:
  2500. AssertionInfo m_info;
  2501. AssertionResultData m_resultData;
  2502. };
  2503. } // end namespace Catch
  2504. // end catch_assertionresult.h
  2505. // start catch_option.hpp
  2506. namespace Catch {
  2507. // An optional type
  2508. template<typename T>
  2509. class Option {
  2510. public:
  2511. Option() : nullableValue( nullptr ) {}
  2512. Option( T const& _value )
  2513. : nullableValue( new( storage ) T( _value ) )
  2514. {}
  2515. Option( Option const& _other )
  2516. : nullableValue( _other ? new( storage ) T( *_other ) : nullptr )
  2517. {}
  2518. ~Option() {
  2519. reset();
  2520. }
  2521. Option& operator= ( Option const& _other ) {
  2522. if( &_other != this ) {
  2523. reset();
  2524. if( _other )
  2525. nullableValue = new( storage ) T( *_other );
  2526. }
  2527. return *this;
  2528. }
  2529. Option& operator = ( T const& _value ) {
  2530. reset();
  2531. nullableValue = new( storage ) T( _value );
  2532. return *this;
  2533. }
  2534. void reset() {
  2535. if( nullableValue )
  2536. nullableValue->~T();
  2537. nullableValue = nullptr;
  2538. }
  2539. T& operator*() { return *nullableValue; }
  2540. T const& operator*() const { return *nullableValue; }
  2541. T* operator->() { return nullableValue; }
  2542. const T* operator->() const { return nullableValue; }
  2543. T valueOr( T const& defaultValue ) const {
  2544. return nullableValue ? *nullableValue : defaultValue;
  2545. }
  2546. bool some() const { return nullableValue != nullptr; }
  2547. bool none() const { return nullableValue == nullptr; }
  2548. bool operator !() const { return nullableValue == nullptr; }
  2549. explicit operator bool() const {
  2550. return some();
  2551. }
  2552. private:
  2553. T *nullableValue;
  2554. alignas(alignof(T)) char storage[sizeof(T)];
  2555. };
  2556. } // end namespace Catch
  2557. // end catch_option.hpp
  2558. #include <string>
  2559. #include <iosfwd>
  2560. #include <map>
  2561. #include <set>
  2562. #include <memory>
  2563. namespace Catch {
  2564. struct ReporterConfig {
  2565. explicit ReporterConfig( IConfigPtr const& _fullConfig );
  2566. ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream );
  2567. std::ostream& stream() const;
  2568. IConfigPtr fullConfig() const;
  2569. private:
  2570. std::ostream* m_stream;
  2571. IConfigPtr m_fullConfig;
  2572. };
  2573. struct ReporterPreferences {
  2574. bool shouldRedirectStdOut = false;
  2575. };
  2576. template<typename T>
  2577. struct LazyStat : Option<T> {
  2578. LazyStat& operator=( T const& _value ) {
  2579. Option<T>::operator=( _value );
  2580. used = false;
  2581. return *this;
  2582. }
  2583. void reset() {
  2584. Option<T>::reset();
  2585. used = false;
  2586. }
  2587. bool used = false;
  2588. };
  2589. struct TestRunInfo {
  2590. TestRunInfo( std::string const& _name );
  2591. std::string name;
  2592. };
  2593. struct GroupInfo {
  2594. GroupInfo( std::string const& _name,
  2595. std::size_t _groupIndex,
  2596. std::size_t _groupsCount );
  2597. std::string name;
  2598. std::size_t groupIndex;
  2599. std::size_t groupsCounts;
  2600. };
  2601. struct AssertionStats {
  2602. AssertionStats( AssertionResult const& _assertionResult,
  2603. std::vector<MessageInfo> const& _infoMessages,
  2604. Totals const& _totals );
  2605. AssertionStats( AssertionStats const& ) = default;
  2606. AssertionStats( AssertionStats && ) = default;
  2607. AssertionStats& operator = ( AssertionStats const& ) = default;
  2608. AssertionStats& operator = ( AssertionStats && ) = default;
  2609. virtual ~AssertionStats();
  2610. AssertionResult assertionResult;
  2611. std::vector<MessageInfo> infoMessages;
  2612. Totals totals;
  2613. };
  2614. struct SectionStats {
  2615. SectionStats( SectionInfo const& _sectionInfo,
  2616. Counts const& _assertions,
  2617. double _durationInSeconds,
  2618. bool _missingAssertions );
  2619. SectionStats( SectionStats const& ) = default;
  2620. SectionStats( SectionStats && ) = default;
  2621. SectionStats& operator = ( SectionStats const& ) = default;
  2622. SectionStats& operator = ( SectionStats && ) = default;
  2623. virtual ~SectionStats();
  2624. SectionInfo sectionInfo;
  2625. Counts assertions;
  2626. double durationInSeconds;
  2627. bool missingAssertions;
  2628. };
  2629. struct TestCaseStats {
  2630. TestCaseStats( TestCaseInfo const& _testInfo,
  2631. Totals const& _totals,
  2632. std::string const& _stdOut,
  2633. std::string const& _stdErr,
  2634. bool _aborting );
  2635. TestCaseStats( TestCaseStats const& ) = default;
  2636. TestCaseStats( TestCaseStats && ) = default;
  2637. TestCaseStats& operator = ( TestCaseStats const& ) = default;
  2638. TestCaseStats& operator = ( TestCaseStats && ) = default;
  2639. virtual ~TestCaseStats();
  2640. TestCaseInfo testInfo;
  2641. Totals totals;
  2642. std::string stdOut;
  2643. std::string stdErr;
  2644. bool aborting;
  2645. };
  2646. struct TestGroupStats {
  2647. TestGroupStats( GroupInfo const& _groupInfo,
  2648. Totals const& _totals,
  2649. bool _aborting );
  2650. TestGroupStats( GroupInfo const& _groupInfo );
  2651. TestGroupStats( TestGroupStats const& ) = default;
  2652. TestGroupStats( TestGroupStats && ) = default;
  2653. TestGroupStats& operator = ( TestGroupStats const& ) = default;
  2654. TestGroupStats& operator = ( TestGroupStats && ) = default;
  2655. virtual ~TestGroupStats();
  2656. GroupInfo groupInfo;
  2657. Totals totals;
  2658. bool aborting;
  2659. };
  2660. struct TestRunStats {
  2661. TestRunStats( TestRunInfo const& _runInfo,
  2662. Totals const& _totals,
  2663. bool _aborting );
  2664. TestRunStats( TestRunStats const& ) = default;
  2665. TestRunStats( TestRunStats && ) = default;
  2666. TestRunStats& operator = ( TestRunStats const& ) = default;
  2667. TestRunStats& operator = ( TestRunStats && ) = default;
  2668. virtual ~TestRunStats();
  2669. TestRunInfo runInfo;
  2670. Totals totals;
  2671. bool aborting;
  2672. };
  2673. struct BenchmarkInfo {
  2674. std::string name;
  2675. };
  2676. struct BenchmarkStats {
  2677. BenchmarkInfo info;
  2678. std::size_t iterations;
  2679. uint64_t elapsedTimeInNanoseconds;
  2680. };
  2681. struct IStreamingReporter {
  2682. virtual ~IStreamingReporter() = default;
  2683. // Implementing class must also provide the following static methods:
  2684. // static std::string getDescription();
  2685. // static std::set<Verbosity> getSupportedVerbosities()
  2686. virtual ReporterPreferences getPreferences() const = 0;
  2687. virtual void noMatchingTestCases( std::string const& spec ) = 0;
  2688. virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0;
  2689. virtual void testGroupStarting( GroupInfo const& groupInfo ) = 0;
  2690. virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0;
  2691. virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0;
  2692. // *** experimental ***
  2693. virtual void benchmarkStarting( BenchmarkInfo const& ) {}
  2694. virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0;
  2695. // The return value indicates if the messages buffer should be cleared:
  2696. virtual bool assertionEnded( AssertionStats const& assertionStats ) = 0;
  2697. // *** experimental ***
  2698. virtual void benchmarkEnded( BenchmarkStats const& ) {}
  2699. virtual void sectionEnded( SectionStats const& sectionStats ) = 0;
  2700. virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0;
  2701. virtual void testGroupEnded( TestGroupStats const& testGroupStats ) = 0;
  2702. virtual void testRunEnded( TestRunStats const& testRunStats ) = 0;
  2703. virtual void skipTest( TestCaseInfo const& testInfo ) = 0;
  2704. // Default empty implementation provided
  2705. virtual void fatalErrorEncountered( StringRef name );
  2706. virtual bool isMulti() const;
  2707. };
  2708. using IStreamingReporterPtr = std::unique_ptr<IStreamingReporter>;
  2709. struct IReporterFactory {
  2710. virtual ~IReporterFactory();
  2711. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const = 0;
  2712. virtual std::string getDescription() const = 0;
  2713. };
  2714. using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
  2715. struct IReporterRegistry {
  2716. using FactoryMap = std::map<std::string, IReporterFactoryPtr>;
  2717. using Listeners = std::vector<IReporterFactoryPtr>;
  2718. virtual ~IReporterRegistry();
  2719. virtual IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const = 0;
  2720. virtual FactoryMap const& getFactories() const = 0;
  2721. virtual Listeners const& getListeners() const = 0;
  2722. };
  2723. void addReporter( IStreamingReporterPtr& existingReporter, IStreamingReporterPtr&& additionalReporter );
  2724. } // end namespace Catch
  2725. // end catch_interfaces_reporter.h
  2726. #include <algorithm>
  2727. #include <cstring>
  2728. #include <cfloat>
  2729. #include <cstdio>
  2730. #include <assert.h>
  2731. #include <memory>
  2732. namespace Catch {
  2733. void prepareExpandedExpression(AssertionResult& result);
  2734. // Returns double formatted as %.3f (format expected on output)
  2735. std::string getFormattedDuration( double duration );
  2736. template<typename DerivedT>
  2737. struct StreamingReporterBase : IStreamingReporter {
  2738. StreamingReporterBase( ReporterConfig const& _config )
  2739. : m_config( _config.fullConfig() ),
  2740. stream( _config.stream() )
  2741. {
  2742. m_reporterPrefs.shouldRedirectStdOut = false;
  2743. CATCH_ENFORCE( DerivedT::getSupportedVerbosities().count( m_config->verbosity() ), "Verbosity level not supported by this reporter" );
  2744. }
  2745. ReporterPreferences getPreferences() const override {
  2746. return m_reporterPrefs;
  2747. }
  2748. static std::set<Verbosity> getSupportedVerbosities() {
  2749. return { Verbosity::Normal };
  2750. }
  2751. ~StreamingReporterBase() override = default;
  2752. void noMatchingTestCases(std::string const&) override {}
  2753. void testRunStarting(TestRunInfo const& _testRunInfo) override {
  2754. currentTestRunInfo = _testRunInfo;
  2755. }
  2756. void testGroupStarting(GroupInfo const& _groupInfo) override {
  2757. currentGroupInfo = _groupInfo;
  2758. }
  2759. void testCaseStarting(TestCaseInfo const& _testInfo) override {
  2760. currentTestCaseInfo = _testInfo;
  2761. }
  2762. void sectionStarting(SectionInfo const& _sectionInfo) override {
  2763. m_sectionStack.push_back(_sectionInfo);
  2764. }
  2765. void sectionEnded(SectionStats const& /* _sectionStats */) override {
  2766. m_sectionStack.pop_back();
  2767. }
  2768. void testCaseEnded(TestCaseStats const& /* _testCaseStats */) override {
  2769. currentTestCaseInfo.reset();
  2770. }
  2771. void testGroupEnded(TestGroupStats const& /* _testGroupStats */) override {
  2772. currentGroupInfo.reset();
  2773. }
  2774. void testRunEnded(TestRunStats const& /* _testRunStats */) override {
  2775. currentTestCaseInfo.reset();
  2776. currentGroupInfo.reset();
  2777. currentTestRunInfo.reset();
  2778. }
  2779. void skipTest(TestCaseInfo const&) override {
  2780. // Don't do anything with this by default.
  2781. // It can optionally be overridden in the derived class.
  2782. }
  2783. IConfigPtr m_config;
  2784. std::ostream& stream;
  2785. LazyStat<TestRunInfo> currentTestRunInfo;
  2786. LazyStat<GroupInfo> currentGroupInfo;
  2787. LazyStat<TestCaseInfo> currentTestCaseInfo;
  2788. std::vector<SectionInfo> m_sectionStack;
  2789. ReporterPreferences m_reporterPrefs;
  2790. };
  2791. template<typename DerivedT>
  2792. struct CumulativeReporterBase : IStreamingReporter {
  2793. template<typename T, typename ChildNodeT>
  2794. struct Node {
  2795. explicit Node( T const& _value ) : value( _value ) {}
  2796. virtual ~Node() {}
  2797. using ChildNodes = std::vector<std::shared_ptr<ChildNodeT>>;
  2798. T value;
  2799. ChildNodes children;
  2800. };
  2801. struct SectionNode {
  2802. explicit SectionNode(SectionStats const& _stats) : stats(_stats) {}
  2803. virtual ~SectionNode() = default;
  2804. bool operator == (SectionNode const& other) const {
  2805. return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;
  2806. }
  2807. bool operator == (std::shared_ptr<SectionNode> const& other) const {
  2808. return operator==(*other);
  2809. }
  2810. SectionStats stats;
  2811. using ChildSections = std::vector<std::shared_ptr<SectionNode>>;
  2812. using Assertions = std::vector<AssertionStats>;
  2813. ChildSections childSections;
  2814. Assertions assertions;
  2815. std::string stdOut;
  2816. std::string stdErr;
  2817. };
  2818. struct BySectionInfo {
  2819. BySectionInfo( SectionInfo const& other ) : m_other( other ) {}
  2820. BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {}
  2821. bool operator() (std::shared_ptr<SectionNode> const& node) const {
  2822. return ((node->stats.sectionInfo.name == m_other.name) &&
  2823. (node->stats.sectionInfo.lineInfo == m_other.lineInfo));
  2824. }
  2825. void operator=(BySectionInfo const&) = delete;
  2826. private:
  2827. SectionInfo const& m_other;
  2828. };
  2829. using TestCaseNode = Node<TestCaseStats, SectionNode>;
  2830. using TestGroupNode = Node<TestGroupStats, TestCaseNode>;
  2831. using TestRunNode = Node<TestRunStats, TestGroupNode>;
  2832. CumulativeReporterBase( ReporterConfig const& _config )
  2833. : m_config( _config.fullConfig() ),
  2834. stream( _config.stream() )
  2835. {
  2836. m_reporterPrefs.shouldRedirectStdOut = false;
  2837. CATCH_ENFORCE( DerivedT::getSupportedVerbosities().count( m_config->verbosity() ), "Verbosity level not supported by this reporter" );
  2838. }
  2839. ~CumulativeReporterBase() override = default;
  2840. ReporterPreferences getPreferences() const override {
  2841. return m_reporterPrefs;
  2842. }
  2843. static std::set<Verbosity> getSupportedVerbosities() {
  2844. return { Verbosity::Normal };
  2845. }
  2846. void testRunStarting( TestRunInfo const& ) override {}
  2847. void testGroupStarting( GroupInfo const& ) override {}
  2848. void testCaseStarting( TestCaseInfo const& ) override {}
  2849. void sectionStarting( SectionInfo const& sectionInfo ) override {
  2850. SectionStats incompleteStats( sectionInfo, Counts(), 0, false );
  2851. std::shared_ptr<SectionNode> node;
  2852. if( m_sectionStack.empty() ) {
  2853. if( !m_rootSection )
  2854. m_rootSection = std::make_shared<SectionNode>( incompleteStats );
  2855. node = m_rootSection;
  2856. }
  2857. else {
  2858. SectionNode& parentNode = *m_sectionStack.back();
  2859. auto it =
  2860. std::find_if( parentNode.childSections.begin(),
  2861. parentNode.childSections.end(),
  2862. BySectionInfo( sectionInfo ) );
  2863. if( it == parentNode.childSections.end() ) {
  2864. node = std::make_shared<SectionNode>( incompleteStats );
  2865. parentNode.childSections.push_back( node );
  2866. }
  2867. else
  2868. node = *it;
  2869. }
  2870. m_sectionStack.push_back( node );
  2871. m_deepestSection = std::move(node);
  2872. }
  2873. void assertionStarting(AssertionInfo const&) override {}
  2874. bool assertionEnded(AssertionStats const& assertionStats) override {
  2875. assert(!m_sectionStack.empty());
  2876. // AssertionResult holds a pointer to a temporary DecomposedExpression,
  2877. // which getExpandedExpression() calls to build the expression string.
  2878. // Our section stack copy of the assertionResult will likely outlive the
  2879. // temporary, so it must be expanded or discarded now to avoid calling
  2880. // a destroyed object later.
  2881. prepareExpandedExpression(const_cast<AssertionResult&>( assertionStats.assertionResult ) );
  2882. SectionNode& sectionNode = *m_sectionStack.back();
  2883. sectionNode.assertions.push_back(assertionStats);
  2884. return true;
  2885. }
  2886. void sectionEnded(SectionStats const& sectionStats) override {
  2887. assert(!m_sectionStack.empty());
  2888. SectionNode& node = *m_sectionStack.back();
  2889. node.stats = sectionStats;
  2890. m_sectionStack.pop_back();
  2891. }
  2892. void testCaseEnded(TestCaseStats const& testCaseStats) override {
  2893. auto node = std::make_shared<TestCaseNode>(testCaseStats);
  2894. assert(m_sectionStack.size() == 0);
  2895. node->children.push_back(m_rootSection);
  2896. m_testCases.push_back(node);
  2897. m_rootSection.reset();
  2898. assert(m_deepestSection);
  2899. m_deepestSection->stdOut = testCaseStats.stdOut;
  2900. m_deepestSection->stdErr = testCaseStats.stdErr;
  2901. }
  2902. void testGroupEnded(TestGroupStats const& testGroupStats) override {
  2903. auto node = std::make_shared<TestGroupNode>(testGroupStats);
  2904. node->children.swap(m_testCases);
  2905. m_testGroups.push_back(node);
  2906. }
  2907. void testRunEnded(TestRunStats const& testRunStats) override {
  2908. auto node = std::make_shared<TestRunNode>(testRunStats);
  2909. node->children.swap(m_testGroups);
  2910. m_testRuns.push_back(node);
  2911. testRunEndedCumulative();
  2912. }
  2913. virtual void testRunEndedCumulative() = 0;
  2914. void skipTest(TestCaseInfo const&) override {}
  2915. IConfigPtr m_config;
  2916. std::ostream& stream;
  2917. std::vector<AssertionStats> m_assertions;
  2918. std::vector<std::vector<std::shared_ptr<SectionNode>>> m_sections;
  2919. std::vector<std::shared_ptr<TestCaseNode>> m_testCases;
  2920. std::vector<std::shared_ptr<TestGroupNode>> m_testGroups;
  2921. std::vector<std::shared_ptr<TestRunNode>> m_testRuns;
  2922. std::shared_ptr<SectionNode> m_rootSection;
  2923. std::shared_ptr<SectionNode> m_deepestSection;
  2924. std::vector<std::shared_ptr<SectionNode>> m_sectionStack;
  2925. ReporterPreferences m_reporterPrefs;
  2926. };
  2927. template<char C>
  2928. char const* getLineOfChars() {
  2929. static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
  2930. if( !*line ) {
  2931. std::memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 );
  2932. line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0;
  2933. }
  2934. return line;
  2935. }
  2936. struct TestEventListenerBase : StreamingReporterBase<TestEventListenerBase> {
  2937. TestEventListenerBase( ReporterConfig const& _config );
  2938. void assertionStarting(AssertionInfo const&) override;
  2939. bool assertionEnded(AssertionStats const&) override;
  2940. };
  2941. } // end namespace Catch
  2942. // end catch_reporter_bases.hpp
  2943. // start catch_console_colour.h
  2944. namespace Catch {
  2945. struct Colour {
  2946. enum Code {
  2947. None = 0,
  2948. White,
  2949. Red,
  2950. Green,
  2951. Blue,
  2952. Cyan,
  2953. Yellow,
  2954. Grey,
  2955. Bright = 0x10,
  2956. BrightRed = Bright | Red,
  2957. BrightGreen = Bright | Green,
  2958. LightGrey = Bright | Grey,
  2959. BrightWhite = Bright | White,
  2960. // By intention
  2961. FileName = LightGrey,
  2962. Warning = Yellow,
  2963. ResultError = BrightRed,
  2964. ResultSuccess = BrightGreen,
  2965. ResultExpectedFailure = Warning,
  2966. Error = BrightRed,
  2967. Success = Green,
  2968. OriginalExpression = Cyan,
  2969. ReconstructedExpression = Yellow,
  2970. SecondaryText = LightGrey,
  2971. Headers = White
  2972. };
  2973. // Use constructed object for RAII guard
  2974. Colour( Code _colourCode );
  2975. Colour( Colour&& other ) noexcept;
  2976. Colour& operator=( Colour&& other ) noexcept;
  2977. ~Colour();
  2978. // Use static method for one-shot changes
  2979. static void use( Code _colourCode );
  2980. private:
  2981. bool m_moved = false;
  2982. };
  2983. std::ostream& operator << ( std::ostream& os, Colour const& );
  2984. } // end namespace Catch
  2985. // end catch_console_colour.h
  2986. // start catch_reporter_registrars.hpp
  2987. namespace Catch {
  2988. template<typename T>
  2989. class ReporterRegistrar {
  2990. class ReporterFactory : public IReporterFactory {
  2991. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const override {
  2992. return std::unique_ptr<T>( new T( config ) );
  2993. }
  2994. virtual std::string getDescription() const override {
  2995. return T::getDescription();
  2996. }
  2997. };
  2998. public:
  2999. ReporterRegistrar( std::string const& name ) {
  3000. getMutableRegistryHub().registerReporter( name, std::make_shared<ReporterFactory>() );
  3001. }
  3002. };
  3003. template<typename T>
  3004. class ListenerRegistrar {
  3005. class ListenerFactory : public IReporterFactory {
  3006. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const override {
  3007. return std::unique_ptr<T>( new T( config ) );
  3008. }
  3009. virtual std::string getDescription() const override {
  3010. return std::string();
  3011. }
  3012. };
  3013. public:
  3014. ListenerRegistrar() {
  3015. getMutableRegistryHub().registerListener( std::make_shared<ListenerFactory>() );
  3016. }
  3017. };
  3018. }
  3019. #if !defined(CATCH_CONFIG_DISABLE)
  3020. #define CATCH_REGISTER_REPORTER( name, reporterType ) \
  3021. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  3022. namespace{ Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); } \
  3023. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  3024. #define CATCH_REGISTER_LISTENER( listenerType ) \
  3025. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  3026. namespace{ Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; } \
  3027. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  3028. #else // CATCH_CONFIG_DISABLE
  3029. #define CATCH_REGISTER_REPORTER(name, reporterType)
  3030. #define CATCH_REGISTER_LISTENER(listenerType)
  3031. #endif // CATCH_CONFIG_DISABLE
  3032. // end catch_reporter_registrars.hpp
  3033. // end catch_external_interfaces.h
  3034. #endif
  3035. #ifdef CATCH_IMPL
  3036. // start catch_impl.hpp
  3037. #ifdef __clang__
  3038. #pragma clang diagnostic push
  3039. #pragma clang diagnostic ignored "-Wweak-vtables"
  3040. #endif
  3041. // Keep these here for external reporters
  3042. // start catch_test_case_tracker.h
  3043. #include <string>
  3044. #include <vector>
  3045. #include <memory>
  3046. namespace Catch {
  3047. namespace TestCaseTracking {
  3048. struct NameAndLocation {
  3049. std::string name;
  3050. SourceLineInfo location;
  3051. NameAndLocation( std::string const& _name, SourceLineInfo const& _location );
  3052. };
  3053. struct ITracker;
  3054. using ITrackerPtr = std::shared_ptr<ITracker>;
  3055. struct ITracker {
  3056. virtual ~ITracker();
  3057. // static queries
  3058. virtual NameAndLocation const& nameAndLocation() const = 0;
  3059. // dynamic queries
  3060. virtual bool isComplete() const = 0; // Successfully completed or failed
  3061. virtual bool isSuccessfullyCompleted() const = 0;
  3062. virtual bool isOpen() const = 0; // Started but not complete
  3063. virtual bool hasChildren() const = 0;
  3064. virtual ITracker& parent() = 0;
  3065. // actions
  3066. virtual void close() = 0; // Successfully complete
  3067. virtual void fail() = 0;
  3068. virtual void markAsNeedingAnotherRun() = 0;
  3069. virtual void addChild( ITrackerPtr const& child ) = 0;
  3070. virtual ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) = 0;
  3071. virtual void openChild() = 0;
  3072. // Debug/ checking
  3073. virtual bool isSectionTracker() const = 0;
  3074. virtual bool isIndexTracker() const = 0;
  3075. };
  3076. class TrackerContext {
  3077. enum RunState {
  3078. NotStarted,
  3079. Executing,
  3080. CompletedCycle
  3081. };
  3082. ITrackerPtr m_rootTracker;
  3083. ITracker* m_currentTracker = nullptr;
  3084. RunState m_runState = NotStarted;
  3085. public:
  3086. static TrackerContext& instance();
  3087. ITracker& startRun();
  3088. void endRun();
  3089. void startCycle();
  3090. void completeCycle();
  3091. bool completedCycle() const;
  3092. ITracker& currentTracker();
  3093. void setCurrentTracker( ITracker* tracker );
  3094. };
  3095. class TrackerBase : public ITracker {
  3096. protected:
  3097. enum CycleState {
  3098. NotStarted,
  3099. Executing,
  3100. ExecutingChildren,
  3101. NeedsAnotherRun,
  3102. CompletedSuccessfully,
  3103. Failed
  3104. };
  3105. class TrackerHasName {
  3106. NameAndLocation m_nameAndLocation;
  3107. public:
  3108. TrackerHasName( NameAndLocation const& nameAndLocation );
  3109. bool operator ()( ITrackerPtr const& tracker ) const;
  3110. };
  3111. using Children = std::vector<ITrackerPtr>;
  3112. NameAndLocation m_nameAndLocation;
  3113. TrackerContext& m_ctx;
  3114. ITracker* m_parent;
  3115. Children m_children;
  3116. CycleState m_runState = NotStarted;
  3117. public:
  3118. TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  3119. NameAndLocation const& nameAndLocation() const override;
  3120. bool isComplete() const override;
  3121. bool isSuccessfullyCompleted() const override;
  3122. bool isOpen() const override;
  3123. bool hasChildren() const override;
  3124. void addChild( ITrackerPtr const& child ) override;
  3125. ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) override;
  3126. ITracker& parent() override;
  3127. void openChild() override;
  3128. bool isSectionTracker() const override;
  3129. bool isIndexTracker() const override;
  3130. void open();
  3131. void close() override;
  3132. void fail() override;
  3133. void markAsNeedingAnotherRun() override;
  3134. private:
  3135. void moveToParent();
  3136. void moveToThis();
  3137. };
  3138. class SectionTracker : public TrackerBase {
  3139. std::vector<std::string> m_filters;
  3140. public:
  3141. SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  3142. bool isSectionTracker() const override;
  3143. static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation );
  3144. void tryOpen();
  3145. void addInitialFilters( std::vector<std::string> const& filters );
  3146. void addNextFilters( std::vector<std::string> const& filters );
  3147. };
  3148. class IndexTracker : public TrackerBase {
  3149. int m_size;
  3150. int m_index = -1;
  3151. public:
  3152. IndexTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent, int size );
  3153. bool isIndexTracker() const override;
  3154. void close() override;
  3155. static IndexTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation, int size );
  3156. int index() const;
  3157. void moveNext();
  3158. };
  3159. } // namespace TestCaseTracking
  3160. using TestCaseTracking::ITracker;
  3161. using TestCaseTracking::TrackerContext;
  3162. using TestCaseTracking::SectionTracker;
  3163. using TestCaseTracking::IndexTracker;
  3164. } // namespace Catch
  3165. // end catch_test_case_tracker.h
  3166. // start catch_leak_detector.h
  3167. namespace Catch {
  3168. struct LeakDetector {
  3169. LeakDetector();
  3170. };
  3171. }
  3172. // end catch_leak_detector.h
  3173. // Cpp files will be included in the single-header file here
  3174. // start catch_approx.cpp
  3175. #include <cmath>
  3176. #include <limits>
  3177. namespace {
  3178. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  3179. // But without the subtraction to allow for INFINITY in comparison
  3180. bool marginComparison(double lhs, double rhs, double margin) {
  3181. return (lhs + margin >= rhs) && (rhs + margin >= lhs);
  3182. }
  3183. }
  3184. namespace Catch {
  3185. namespace Detail {
  3186. Approx::Approx ( double value )
  3187. : m_epsilon( std::numeric_limits<float>::epsilon()*100 ),
  3188. m_margin( 0.0 ),
  3189. m_scale( 0.0 ),
  3190. m_value( value )
  3191. {}
  3192. Approx Approx::custom() {
  3193. return Approx( 0 );
  3194. }
  3195. std::string Approx::toString() const {
  3196. std::ostringstream oss;
  3197. oss << "Approx( " << ::Catch::Detail::stringify( m_value ) << " )";
  3198. return oss.str();
  3199. }
  3200. bool Approx::equalityComparisonImpl(const double other) const {
  3201. // First try with fixed margin, then compute margin based on epsilon, scale and Approx's value
  3202. // Thanks to Richard Harris for his help refining the scaled margin value
  3203. return marginComparison(m_value, other, m_margin) || marginComparison(m_value, other, m_epsilon * (m_scale + std::fabs(m_value)));
  3204. }
  3205. } // end namespace Detail
  3206. std::string StringMaker<Catch::Detail::Approx>::convert(Catch::Detail::Approx const& value) {
  3207. return value.toString();
  3208. }
  3209. } // end namespace Catch
  3210. // end catch_approx.cpp
  3211. // start catch_assertionhandler.cpp
  3212. // start catch_context.h
  3213. #include <memory>
  3214. namespace Catch {
  3215. struct IResultCapture;
  3216. struct IRunner;
  3217. struct IConfig;
  3218. using IConfigPtr = std::shared_ptr<IConfig const>;
  3219. struct IContext
  3220. {
  3221. virtual ~IContext();
  3222. virtual IResultCapture* getResultCapture() = 0;
  3223. virtual IRunner* getRunner() = 0;
  3224. virtual IConfigPtr getConfig() const = 0;
  3225. };
  3226. struct IMutableContext : IContext
  3227. {
  3228. virtual ~IMutableContext();
  3229. virtual void setResultCapture( IResultCapture* resultCapture ) = 0;
  3230. virtual void setRunner( IRunner* runner ) = 0;
  3231. virtual void setConfig( IConfigPtr const& config ) = 0;
  3232. };
  3233. IContext& getCurrentContext();
  3234. IMutableContext& getCurrentMutableContext();
  3235. void cleanUpContext();
  3236. }
  3237. // end catch_context.h
  3238. #include <cassert>
  3239. namespace Catch {
  3240. auto operator <<( std::ostream& os, ITransientExpression const& expr ) -> std::ostream& {
  3241. expr.streamReconstructedExpression( os );
  3242. return os;
  3243. }
  3244. LazyExpression::LazyExpression( bool isNegated )
  3245. : m_isNegated( isNegated )
  3246. {}
  3247. LazyExpression::LazyExpression( LazyExpression const& other ) : m_isNegated( other.m_isNegated ) {}
  3248. LazyExpression::operator bool() const {
  3249. return m_transientExpression != nullptr;
  3250. }
  3251. auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream& {
  3252. if( lazyExpr.m_isNegated )
  3253. os << "!";
  3254. if( lazyExpr ) {
  3255. if( lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression() )
  3256. os << "(" << *lazyExpr.m_transientExpression << ")";
  3257. else
  3258. os << *lazyExpr.m_transientExpression;
  3259. }
  3260. else {
  3261. os << "{** error - unchecked empty expression requested **}";
  3262. }
  3263. return os;
  3264. }
  3265. AssertionHandler::AssertionHandler
  3266. ( StringRef macroName,
  3267. SourceLineInfo const& lineInfo,
  3268. StringRef capturedExpression,
  3269. ResultDisposition::Flags resultDisposition )
  3270. : m_assertionInfo{ macroName, lineInfo, capturedExpression, resultDisposition }
  3271. {
  3272. getCurrentContext().getResultCapture()->assertionStarting( m_assertionInfo );
  3273. }
  3274. AssertionHandler::~AssertionHandler() {
  3275. if ( m_inExceptionGuard ) {
  3276. handle( ResultWas::ThrewException, "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE" );
  3277. getCurrentContext().getResultCapture()->exceptionEarlyReported();
  3278. }
  3279. }
  3280. void AssertionHandler::handle( ITransientExpression const& expr ) {
  3281. bool negated = isFalseTest( m_assertionInfo.resultDisposition );
  3282. bool result = expr.getResult() != negated;
  3283. handle( result ? ResultWas::Ok : ResultWas::ExpressionFailed, &expr, negated );
  3284. }
  3285. void AssertionHandler::handle( ResultWas::OfType resultType ) {
  3286. handle( resultType, nullptr, false );
  3287. }
  3288. void AssertionHandler::handle( ResultWas::OfType resultType, StringRef const& message ) {
  3289. AssertionResultData data( resultType, LazyExpression( false ) );
  3290. data.message = message;
  3291. handle( data, nullptr );
  3292. }
  3293. void AssertionHandler::handle( ResultWas::OfType resultType, ITransientExpression const* expr, bool negated ) {
  3294. AssertionResultData data( resultType, LazyExpression( negated ) );
  3295. handle( data, expr );
  3296. }
  3297. void AssertionHandler::handle( AssertionResultData const& resultData, ITransientExpression const* expr ) {
  3298. getResultCapture().assertionRun();
  3299. AssertionResult assertionResult{ m_assertionInfo, resultData };
  3300. assertionResult.m_resultData.lazyExpression.m_transientExpression = expr;
  3301. getResultCapture().assertionEnded( assertionResult );
  3302. if( !assertionResult.isOk() ) {
  3303. m_shouldDebugBreak = getCurrentContext().getConfig()->shouldDebugBreak();
  3304. m_shouldThrow =
  3305. getCurrentContext().getRunner()->aborting() ||
  3306. (m_assertionInfo.resultDisposition & ResultDisposition::Normal);
  3307. }
  3308. }
  3309. auto AssertionHandler::allowThrows() const -> bool {
  3310. return getCurrentContext().getConfig()->allowThrows();
  3311. }
  3312. auto AssertionHandler::shouldDebugBreak() const -> bool {
  3313. return m_shouldDebugBreak;
  3314. }
  3315. void AssertionHandler::reactWithDebugBreak() const {
  3316. if (m_shouldDebugBreak) {
  3317. ///////////////////////////////////////////////////////////////////
  3318. // To inspect the state during test, you need to go one level up the callstack
  3319. // To go back to the test and change execution, jump over the reactWithoutDebugBreak() call
  3320. ///////////////////////////////////////////////////////////////////
  3321. CATCH_BREAK_INTO_DEBUGGER();
  3322. }
  3323. reactWithoutDebugBreak();
  3324. }
  3325. void AssertionHandler::reactWithoutDebugBreak() const {
  3326. if( m_shouldThrow )
  3327. throw Catch::TestFailureException();
  3328. }
  3329. void AssertionHandler::useActiveException() {
  3330. handle( ResultWas::ThrewException, Catch::translateActiveException() );
  3331. }
  3332. void AssertionHandler::setExceptionGuard() {
  3333. assert( m_inExceptionGuard == false );
  3334. m_inExceptionGuard = true;
  3335. }
  3336. void AssertionHandler::unsetExceptionGuard() {
  3337. assert( m_inExceptionGuard == true );
  3338. m_inExceptionGuard = false;
  3339. }
  3340. // This is the overload that takes a string and infers the Equals matcher from it
  3341. // The more general overload, that takes any string matcher, is in catch_capture_matchers.cpp
  3342. void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef matcherString ) {
  3343. handleExceptionMatchExpr( handler, Matchers::Equals( str ), matcherString );
  3344. }
  3345. } // namespace Catch
  3346. // end catch_assertionhandler.cpp
  3347. // start catch_assertionresult.cpp
  3348. namespace Catch {
  3349. AssertionResultData::AssertionResultData(ResultWas::OfType _resultType, LazyExpression const & _lazyExpression):
  3350. lazyExpression(_lazyExpression),
  3351. resultType(_resultType) {}
  3352. std::string AssertionResultData::reconstructExpression() const {
  3353. if( reconstructedExpression.empty() ) {
  3354. if( lazyExpression ) {
  3355. // !TBD Use stringstream for now, but rework above to pass stream in
  3356. std::ostringstream oss;
  3357. oss << lazyExpression;
  3358. reconstructedExpression = oss.str();
  3359. }
  3360. }
  3361. return reconstructedExpression;
  3362. }
  3363. AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data )
  3364. : m_info( info ),
  3365. m_resultData( data )
  3366. {}
  3367. // Result was a success
  3368. bool AssertionResult::succeeded() const {
  3369. return Catch::isOk( m_resultData.resultType );
  3370. }
  3371. // Result was a success, or failure is suppressed
  3372. bool AssertionResult::isOk() const {
  3373. return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition );
  3374. }
  3375. ResultWas::OfType AssertionResult::getResultType() const {
  3376. return m_resultData.resultType;
  3377. }
  3378. bool AssertionResult::hasExpression() const {
  3379. return m_info.capturedExpression[0] != 0;
  3380. }
  3381. bool AssertionResult::hasMessage() const {
  3382. return !m_resultData.message.empty();
  3383. }
  3384. std::string AssertionResult::getExpression() const {
  3385. if( isFalseTest( m_info.resultDisposition ) )
  3386. return "!(" + std::string(m_info.capturedExpression) + ")";
  3387. else
  3388. return m_info.capturedExpression;
  3389. }
  3390. std::string AssertionResult::getExpressionInMacro() const {
  3391. std::string expr;
  3392. if( m_info.macroName[0] == 0 )
  3393. expr = m_info.capturedExpression;
  3394. else {
  3395. expr.reserve( m_info.macroName.size() + m_info.capturedExpression.size() + 4 );
  3396. expr += m_info.macroName;
  3397. expr += "( ";
  3398. expr += m_info.capturedExpression;
  3399. expr += " )";
  3400. }
  3401. return expr;
  3402. }
  3403. bool AssertionResult::hasExpandedExpression() const {
  3404. return hasExpression() && getExpandedExpression() != getExpression();
  3405. }
  3406. std::string AssertionResult::getExpandedExpression() const {
  3407. std::string expr = m_resultData.reconstructExpression();
  3408. return expr.empty()
  3409. ? getExpression()
  3410. : expr;
  3411. }
  3412. std::string AssertionResult::getMessage() const {
  3413. return m_resultData.message;
  3414. }
  3415. SourceLineInfo AssertionResult::getSourceInfo() const {
  3416. return m_info.lineInfo;
  3417. }
  3418. std::string AssertionResult::getTestMacroName() const {
  3419. return m_info.macroName;
  3420. }
  3421. } // end namespace Catch
  3422. // end catch_assertionresult.cpp
  3423. // start catch_benchmark.cpp
  3424. namespace Catch {
  3425. auto BenchmarkLooper::getResolution() -> uint64_t {
  3426. return getEstimatedClockResolution() * getCurrentContext().getConfig()->benchmarkResolutionMultiple();
  3427. }
  3428. void BenchmarkLooper::reportStart() {
  3429. getResultCapture().benchmarkStarting( { m_name } );
  3430. }
  3431. auto BenchmarkLooper::needsMoreIterations() -> bool {
  3432. auto elapsed = m_timer.getElapsedNanoseconds();
  3433. // Exponentially increasing iterations until we're confident in our timer resolution
  3434. if( elapsed < m_resolution ) {
  3435. m_iterationsToRun *= 10;
  3436. return true;
  3437. }
  3438. getResultCapture().benchmarkEnded( { { m_name }, m_count, elapsed } );
  3439. return false;
  3440. }
  3441. } // end namespace Catch
  3442. // end catch_benchmark.cpp
  3443. // start catch_capture_matchers.cpp
  3444. namespace Catch {
  3445. using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
  3446. // This is the general overload that takes a any string matcher
  3447. // There is another overload, in catch_assertinhandler.h/.cpp, that only takes a string and infers
  3448. // the Equals matcher (so the header does not mention matchers)
  3449. void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef matcherString ) {
  3450. std::string exceptionMessage = Catch::translateActiveException();
  3451. MatchExpr<std::string, StringMatcher const&> expr( exceptionMessage, matcher, matcherString );
  3452. handler.handle( expr );
  3453. }
  3454. } // namespace Catch
  3455. // end catch_capture_matchers.cpp
  3456. // start catch_commandline.cpp
  3457. // start catch_commandline.h
  3458. // start catch_clara.h
  3459. // Use Catch's value for console width (store Clara's off to the side, if present)
  3460. #ifdef CLARA_CONFIG_CONSOLE_WIDTH
  3461. #define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  3462. #undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  3463. #endif
  3464. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH-1
  3465. #ifdef __clang__
  3466. #pragma clang diagnostic push
  3467. #pragma clang diagnostic ignored "-Wweak-vtables"
  3468. #pragma clang diagnostic ignored "-Wexit-time-destructors"
  3469. #pragma clang diagnostic ignored "-Wshadow"
  3470. #endif
  3471. // start clara.hpp
  3472. // v1.0-develop.2
  3473. // See https://github.com/philsquared/Clara
  3474. #ifndef CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  3475. #define CATCH_CLARA_CONFIG_CONSOLE_WIDTH 80
  3476. #endif
  3477. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  3478. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  3479. #endif
  3480. // ----------- #included from clara_textflow.hpp -----------
  3481. // TextFlowCpp
  3482. //
  3483. // A single-header library for wrapping and laying out basic text, by Phil Nash
  3484. //
  3485. // This work is licensed under the BSD 2-Clause license.
  3486. // See the accompanying LICENSE file, or the one at https://opensource.org/licenses/BSD-2-Clause
  3487. //
  3488. // This project is hosted at https://github.com/philsquared/textflowcpp
  3489. #include <cassert>
  3490. #include <ostream>
  3491. #include <sstream>
  3492. #include <vector>
  3493. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  3494. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80
  3495. #endif
  3496. namespace Catch { namespace clara { namespace TextFlow {
  3497. inline auto isWhitespace( char c ) -> bool {
  3498. static std::string chars = " \t\n\r";
  3499. return chars.find( c ) != std::string::npos;
  3500. }
  3501. inline auto isBreakableBefore( char c ) -> bool {
  3502. static std::string chars = "[({<|";
  3503. return chars.find( c ) != std::string::npos;
  3504. }
  3505. inline auto isBreakableAfter( char c ) -> bool {
  3506. static std::string chars = "])}>.,:;*+-=&/\\";
  3507. return chars.find( c ) != std::string::npos;
  3508. }
  3509. class Columns;
  3510. class Column {
  3511. std::vector<std::string> m_strings;
  3512. size_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH;
  3513. size_t m_indent = 0;
  3514. size_t m_initialIndent = std::string::npos;
  3515. public:
  3516. class iterator {
  3517. friend Column;
  3518. Column const& m_column;
  3519. size_t m_stringIndex = 0;
  3520. size_t m_pos = 0;
  3521. size_t m_len = 0;
  3522. size_t m_end = 0;
  3523. bool m_suffix = false;
  3524. iterator( Column const& column, size_t stringIndex )
  3525. : m_column( column ),
  3526. m_stringIndex( stringIndex )
  3527. {}
  3528. auto line() const -> std::string const& { return m_column.m_strings[m_stringIndex]; }
  3529. auto isBoundary( size_t at ) const -> bool {
  3530. assert( at > 0 );
  3531. assert( at <= line().size() );
  3532. return at == line().size() ||
  3533. ( isWhitespace( line()[at] ) && !isWhitespace( line()[at-1] ) ) ||
  3534. isBreakableBefore( line()[at] ) ||
  3535. isBreakableAfter( line()[at-1] );
  3536. }
  3537. void calcLength() {
  3538. assert( m_stringIndex < m_column.m_strings.size() );
  3539. m_suffix = false;
  3540. auto width = m_column.m_width-indent();
  3541. m_end = m_pos;
  3542. while( m_end < line().size() && line()[m_end] != '\n' )
  3543. ++m_end;
  3544. if( m_end < m_pos + width ) {
  3545. m_len = m_end - m_pos;
  3546. }
  3547. else {
  3548. size_t len = width;
  3549. while (len > 0 && !isBoundary(m_pos + len))
  3550. --len;
  3551. while (len > 0 && isWhitespace( line()[m_pos + len - 1] ))
  3552. --len;
  3553. if (len > 0) {
  3554. m_len = len;
  3555. } else {
  3556. m_suffix = true;
  3557. m_len = width - 1;
  3558. }
  3559. }
  3560. }
  3561. auto indent() const -> size_t {
  3562. auto initial = m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos;
  3563. return initial == std::string::npos ? m_column.m_indent : initial;
  3564. }
  3565. auto addIndentAndSuffix(std::string const &plain) const -> std::string {
  3566. return std::string( indent(), ' ' ) + (m_suffix ? plain + "-" : plain);
  3567. }
  3568. public:
  3569. explicit iterator( Column const& column ) : m_column( column ) {
  3570. assert( m_column.m_width > m_column.m_indent );
  3571. assert( m_column.m_initialIndent == std::string::npos || m_column.m_width > m_column.m_initialIndent );
  3572. calcLength();
  3573. if( m_len == 0 )
  3574. m_stringIndex++; // Empty string
  3575. }
  3576. auto operator *() const -> std::string {
  3577. assert( m_stringIndex < m_column.m_strings.size() );
  3578. assert( m_pos <= m_end );
  3579. if( m_pos + m_column.m_width < m_end )
  3580. return addIndentAndSuffix(line().substr(m_pos, m_len));
  3581. else
  3582. return addIndentAndSuffix(line().substr(m_pos, m_end - m_pos));
  3583. }
  3584. auto operator ++() -> iterator& {
  3585. m_pos += m_len;
  3586. if( m_pos < line().size() && line()[m_pos] == '\n' )
  3587. m_pos += 1;
  3588. else
  3589. while( m_pos < line().size() && isWhitespace( line()[m_pos] ) )
  3590. ++m_pos;
  3591. if( m_pos == line().size() ) {
  3592. m_pos = 0;
  3593. ++m_stringIndex;
  3594. }
  3595. if( m_stringIndex < m_column.m_strings.size() )
  3596. calcLength();
  3597. return *this;
  3598. }
  3599. auto operator ++(int) -> iterator {
  3600. iterator prev( *this );
  3601. operator++();
  3602. return prev;
  3603. }
  3604. auto operator ==( iterator const& other ) const -> bool {
  3605. return
  3606. m_pos == other.m_pos &&
  3607. m_stringIndex == other.m_stringIndex &&
  3608. &m_column == &other.m_column;
  3609. }
  3610. auto operator !=( iterator const& other ) const -> bool {
  3611. return !operator==( other );
  3612. }
  3613. };
  3614. using const_iterator = iterator;
  3615. explicit Column( std::string const& text ) { m_strings.push_back( text ); }
  3616. auto width( size_t newWidth ) -> Column& {
  3617. assert( newWidth > 0 );
  3618. m_width = newWidth;
  3619. return *this;
  3620. }
  3621. auto indent( size_t newIndent ) -> Column& {
  3622. m_indent = newIndent;
  3623. return *this;
  3624. }
  3625. auto initialIndent( size_t newIndent ) -> Column& {
  3626. m_initialIndent = newIndent;
  3627. return *this;
  3628. }
  3629. auto width() const -> size_t { return m_width; }
  3630. auto begin() const -> iterator { return iterator( *this ); }
  3631. auto end() const -> iterator { return { *this, m_strings.size() }; }
  3632. inline friend std::ostream& operator << ( std::ostream& os, Column const& col ) {
  3633. bool first = true;
  3634. for( auto line : col ) {
  3635. if( first )
  3636. first = false;
  3637. else
  3638. os << "\n";
  3639. os << line;
  3640. }
  3641. return os;
  3642. }
  3643. auto operator + ( Column const& other ) -> Columns;
  3644. auto toString() const -> std::string {
  3645. std::ostringstream oss;
  3646. oss << *this;
  3647. return oss.str();
  3648. }
  3649. };
  3650. class Spacer : public Column {
  3651. public:
  3652. explicit Spacer( size_t spaceWidth ) : Column( "" ) {
  3653. width( spaceWidth );
  3654. }
  3655. };
  3656. class Columns {
  3657. std::vector<Column> m_columns;
  3658. public:
  3659. class iterator {
  3660. friend Columns;
  3661. struct EndTag {};
  3662. std::vector<Column> const& m_columns;
  3663. std::vector<Column::iterator> m_iterators;
  3664. size_t m_activeIterators;
  3665. iterator( Columns const& columns, EndTag )
  3666. : m_columns( columns.m_columns ),
  3667. m_activeIterators( 0 )
  3668. {
  3669. m_iterators.reserve( m_columns.size() );
  3670. for( auto const& col : m_columns )
  3671. m_iterators.push_back( col.end() );
  3672. }
  3673. public:
  3674. explicit iterator( Columns const& columns )
  3675. : m_columns( columns.m_columns ),
  3676. m_activeIterators( m_columns.size() )
  3677. {
  3678. m_iterators.reserve( m_columns.size() );
  3679. for( auto const& col : m_columns )
  3680. m_iterators.push_back( col.begin() );
  3681. }
  3682. auto operator ==( iterator const& other ) const -> bool {
  3683. return m_iterators == other.m_iterators;
  3684. }
  3685. auto operator !=( iterator const& other ) const -> bool {
  3686. return m_iterators != other.m_iterators;
  3687. }
  3688. auto operator *() const -> std::string {
  3689. std::string row, padding;
  3690. for( size_t i = 0; i < m_columns.size(); ++i ) {
  3691. auto width = m_columns[i].width();
  3692. if( m_iterators[i] != m_columns[i].end() ) {
  3693. std::string col = *m_iterators[i];
  3694. row += padding + col;
  3695. if( col.size() < width )
  3696. padding = std::string( width - col.size(), ' ' );
  3697. else
  3698. padding = "";
  3699. }
  3700. else {
  3701. padding += std::string( width, ' ' );
  3702. }
  3703. }
  3704. return row;
  3705. }
  3706. auto operator ++() -> iterator& {
  3707. for( size_t i = 0; i < m_columns.size(); ++i ) {
  3708. if (m_iterators[i] != m_columns[i].end())
  3709. ++m_iterators[i];
  3710. }
  3711. return *this;
  3712. }
  3713. auto operator ++(int) -> iterator {
  3714. iterator prev( *this );
  3715. operator++();
  3716. return prev;
  3717. }
  3718. };
  3719. using const_iterator = iterator;
  3720. auto begin() const -> iterator { return iterator( *this ); }
  3721. auto end() const -> iterator { return { *this, iterator::EndTag() }; }
  3722. auto operator += ( Column const& col ) -> Columns& {
  3723. m_columns.push_back( col );
  3724. return *this;
  3725. }
  3726. auto operator + ( Column const& col ) -> Columns {
  3727. Columns combined = *this;
  3728. combined += col;
  3729. return combined;
  3730. }
  3731. inline friend std::ostream& operator << ( std::ostream& os, Columns const& cols ) {
  3732. bool first = true;
  3733. for( auto line : cols ) {
  3734. if( first )
  3735. first = false;
  3736. else
  3737. os << "\n";
  3738. os << line;
  3739. }
  3740. return os;
  3741. }
  3742. auto toString() const -> std::string {
  3743. std::ostringstream oss;
  3744. oss << *this;
  3745. return oss.str();
  3746. }
  3747. };
  3748. inline auto Column::operator + ( Column const& other ) -> Columns {
  3749. Columns cols;
  3750. cols += *this;
  3751. cols += other;
  3752. return cols;
  3753. }
  3754. }}} // namespace Catch::clara::TextFlow
  3755. // ----------- end of #include from clara_textflow.hpp -----------
  3756. // ........... back in clara.hpp
  3757. #include <memory>
  3758. #include <set>
  3759. #include <algorithm>
  3760. #if !defined(CATCH_PLATFORM_WINDOWS) && ( defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) )
  3761. #define CATCH_PLATFORM_WINDOWS
  3762. #endif
  3763. namespace Catch { namespace clara {
  3764. namespace detail {
  3765. // Traits for extracting arg and return type of lambdas (for single argument lambdas)
  3766. template<typename L>
  3767. struct UnaryLambdaTraits : UnaryLambdaTraits<decltype( &L::operator() )> {};
  3768. template<typename ClassT, typename ReturnT, typename... Args>
  3769. struct UnaryLambdaTraits<ReturnT( ClassT::* )( Args... ) const> {
  3770. static const bool isValid = false;
  3771. };
  3772. template<typename ClassT, typename ReturnT, typename ArgT>
  3773. struct UnaryLambdaTraits<ReturnT( ClassT::* )( ArgT ) const> {
  3774. static const bool isValid = true;
  3775. using ArgType = typename std::remove_const<typename std::remove_reference<ArgT>::type>::type;;
  3776. using ReturnType = ReturnT;
  3777. };
  3778. class TokenStream;
  3779. // Transport for raw args (copied from main args, or supplied via init list for testing)
  3780. class Args {
  3781. friend TokenStream;
  3782. std::string m_exeName;
  3783. std::vector<std::string> m_args;
  3784. public:
  3785. Args( int argc, char *argv[] ) {
  3786. m_exeName = argv[0];
  3787. for( int i = 1; i < argc; ++i )
  3788. m_args.push_back( argv[i] );
  3789. }
  3790. Args( std::initializer_list<std::string> args )
  3791. : m_exeName( *args.begin() ),
  3792. m_args( args.begin()+1, args.end() )
  3793. {}
  3794. auto exeName() const -> std::string {
  3795. return m_exeName;
  3796. }
  3797. };
  3798. // Wraps a token coming from a token stream. These may not directly correspond to strings as a single string
  3799. // may encode an option + its argument if the : or = form is used
  3800. enum class TokenType {
  3801. Option, Argument
  3802. };
  3803. struct Token {
  3804. TokenType type;
  3805. std::string token;
  3806. };
  3807. inline auto isOptPrefix( char c ) -> bool {
  3808. return c == '-'
  3809. #ifdef CATCH_PLATFORM_WINDOWS
  3810. || c == '/'
  3811. #endif
  3812. ;
  3813. }
  3814. // Abstracts iterators into args as a stream of tokens, with option arguments uniformly handled
  3815. class TokenStream {
  3816. using Iterator = std::vector<std::string>::const_iterator;
  3817. Iterator it;
  3818. Iterator itEnd;
  3819. std::vector<Token> m_tokenBuffer;
  3820. void loadBuffer() {
  3821. m_tokenBuffer.resize( 0 );
  3822. // Skip any empty strings
  3823. while( it != itEnd && it->empty() )
  3824. ++it;
  3825. if( it != itEnd ) {
  3826. auto const &next = *it;
  3827. if( isOptPrefix( next[0] ) ) {
  3828. auto delimiterPos = next.find_first_of( " :=" );
  3829. if( delimiterPos != std::string::npos ) {
  3830. m_tokenBuffer.push_back( { TokenType::Option, next.substr( 0, delimiterPos ) } );
  3831. m_tokenBuffer.push_back( { TokenType::Argument, next.substr( delimiterPos + 1 ) } );
  3832. } else {
  3833. if( next[1] != '-' && next.size() > 2 ) {
  3834. std::string opt = "- ";
  3835. for( size_t i = 1; i < next.size(); ++i ) {
  3836. opt[1] = next[i];
  3837. m_tokenBuffer.push_back( { TokenType::Option, opt } );
  3838. }
  3839. } else {
  3840. m_tokenBuffer.push_back( { TokenType::Option, next } );
  3841. }
  3842. }
  3843. } else {
  3844. m_tokenBuffer.push_back( { TokenType::Argument, next } );
  3845. }
  3846. }
  3847. }
  3848. public:
  3849. explicit TokenStream( Args const &args ) : TokenStream( args.m_args.begin(), args.m_args.end() ) {}
  3850. TokenStream( Iterator it, Iterator itEnd ) : it( it ), itEnd( itEnd ) {
  3851. loadBuffer();
  3852. }
  3853. explicit operator bool() const {
  3854. return !m_tokenBuffer.empty() || it != itEnd;
  3855. }
  3856. auto count() const -> size_t { return m_tokenBuffer.size() + (itEnd - it); }
  3857. auto operator*() const -> Token {
  3858. assert( !m_tokenBuffer.empty() );
  3859. return m_tokenBuffer.front();
  3860. }
  3861. auto operator->() const -> Token const * {
  3862. assert( !m_tokenBuffer.empty() );
  3863. return &m_tokenBuffer.front();
  3864. }
  3865. auto operator++() -> TokenStream & {
  3866. if( m_tokenBuffer.size() >= 2 ) {
  3867. m_tokenBuffer.erase( m_tokenBuffer.begin() );
  3868. } else {
  3869. if( it != itEnd )
  3870. ++it;
  3871. loadBuffer();
  3872. }
  3873. return *this;
  3874. }
  3875. };
  3876. class ResultBase {
  3877. public:
  3878. enum Type {
  3879. Ok, LogicError, RuntimeError
  3880. };
  3881. protected:
  3882. ResultBase( Type type ) : m_type( type ) {}
  3883. virtual ~ResultBase() = default;
  3884. virtual void enforceOk() const = 0;
  3885. Type m_type;
  3886. };
  3887. template<typename T>
  3888. class ResultValueBase : public ResultBase {
  3889. public:
  3890. auto value() const -> T const & {
  3891. enforceOk();
  3892. return m_value;
  3893. }
  3894. protected:
  3895. ResultValueBase( Type type ) : ResultBase( type ) {}
  3896. ResultValueBase( ResultValueBase const &other ) : ResultBase( other ) {
  3897. if( m_type == ResultBase::Ok )
  3898. new( &m_value ) T( other.m_value );
  3899. }
  3900. ResultValueBase( Type, T const &value ) : ResultBase( Ok ) {
  3901. new( &m_value ) T( value );
  3902. }
  3903. auto operator=( ResultValueBase const &other ) -> ResultValueBase & {
  3904. if( m_type == ResultBase::Ok )
  3905. m_value.~T();
  3906. ResultBase::operator=(other);
  3907. if( m_type == ResultBase::Ok )
  3908. new( &m_value ) T( other.m_value );
  3909. return *this;
  3910. }
  3911. ~ResultValueBase() {
  3912. if( m_type == Ok )
  3913. m_value.~T();
  3914. }
  3915. union {
  3916. T m_value;
  3917. };
  3918. };
  3919. template<>
  3920. class ResultValueBase<void> : public ResultBase {
  3921. protected:
  3922. using ResultBase::ResultBase;
  3923. };
  3924. template<typename T = void>
  3925. class BasicResult : public ResultValueBase<T> {
  3926. public:
  3927. template<typename U>
  3928. explicit BasicResult( BasicResult<U> const &other )
  3929. : ResultValueBase<T>( other.type() ),
  3930. m_errorMessage( other.errorMessage() )
  3931. {
  3932. assert( type() != ResultBase::Ok );
  3933. }
  3934. template<typename U>
  3935. static auto ok( U const &value ) -> BasicResult { return { ResultBase::Ok, value }; }
  3936. static auto ok() -> BasicResult { return { ResultBase::Ok }; }
  3937. static auto logicError( std::string const &message ) -> BasicResult { return { ResultBase::LogicError, message }; }
  3938. static auto runtimeError( std::string const &message ) -> BasicResult { return { ResultBase::RuntimeError, message }; }
  3939. explicit operator bool() const { return m_type == ResultBase::Ok; }
  3940. auto type() const -> ResultBase::Type { return m_type; }
  3941. auto errorMessage() const -> std::string { return m_errorMessage; }
  3942. protected:
  3943. virtual void enforceOk() const {
  3944. // !TBD: If no exceptions, std::terminate here or something
  3945. switch( m_type ) {
  3946. case ResultBase::LogicError:
  3947. throw std::logic_error( m_errorMessage );
  3948. case ResultBase::RuntimeError:
  3949. throw std::runtime_error( m_errorMessage );
  3950. case ResultBase::Ok:
  3951. break;
  3952. }
  3953. }
  3954. std::string m_errorMessage; // Only populated if resultType is an error
  3955. BasicResult( ResultBase::Type type, std::string const &message )
  3956. : ResultValueBase<T>(type),
  3957. m_errorMessage(message)
  3958. {
  3959. assert( m_type != ResultBase::Ok );
  3960. }
  3961. using ResultValueBase<T>::ResultValueBase;
  3962. using ResultBase::m_type;
  3963. };
  3964. enum class ParseResultType {
  3965. Matched, NoMatch, ShortCircuitAll, ShortCircuitSame
  3966. };
  3967. class ParseState {
  3968. public:
  3969. ParseState( ParseResultType type, TokenStream const &remainingTokens )
  3970. : m_type(type),
  3971. m_remainingTokens( remainingTokens )
  3972. {}
  3973. auto type() const -> ParseResultType { return m_type; }
  3974. auto remainingTokens() const -> TokenStream { return m_remainingTokens; }
  3975. private:
  3976. ParseResultType m_type;
  3977. TokenStream m_remainingTokens;
  3978. };
  3979. using Result = BasicResult<void>;
  3980. using ParserResult = BasicResult<ParseResultType>;
  3981. using InternalParseResult = BasicResult<ParseState>;
  3982. struct HelpColumns {
  3983. std::string left;
  3984. std::string right;
  3985. };
  3986. template<typename T>
  3987. inline auto convertInto( std::string const &source, T& target ) -> ParserResult {
  3988. std::stringstream ss;
  3989. ss << source;
  3990. ss >> target;
  3991. if( ss.fail() )
  3992. return ParserResult::runtimeError( "Unable to convert '" + source + "' to destination type" );
  3993. else
  3994. return ParserResult::ok( ParseResultType::Matched );
  3995. }
  3996. inline auto convertInto( std::string const &source, std::string& target ) -> ParserResult {
  3997. target = source;
  3998. return ParserResult::ok( ParseResultType::Matched );
  3999. }
  4000. inline auto convertInto( std::string const &source, bool &target ) -> ParserResult {
  4001. std::string srcLC = source;
  4002. std::transform( srcLC.begin(), srcLC.end(), srcLC.begin(), []( char c ) { return static_cast<char>( ::tolower(c) ); } );
  4003. if (srcLC == "y" || srcLC == "1" || srcLC == "true" || srcLC == "yes" || srcLC == "on")
  4004. target = true;
  4005. else if (srcLC == "n" || srcLC == "0" || srcLC == "false" || srcLC == "no" || srcLC == "off")
  4006. target = false;
  4007. else
  4008. return ParserResult::runtimeError( "Expected a boolean value but did not recognise: '" + source + "'" );
  4009. return ParserResult::ok( ParseResultType::Matched );
  4010. }
  4011. struct BoundRefBase {
  4012. BoundRefBase() = default;
  4013. BoundRefBase( BoundRefBase const & ) = delete;
  4014. BoundRefBase( BoundRefBase && ) = delete;
  4015. BoundRefBase &operator=( BoundRefBase const & ) = delete;
  4016. BoundRefBase &operator=( BoundRefBase && ) = delete;
  4017. virtual ~BoundRefBase() = default;
  4018. virtual auto isFlag() const -> bool = 0;
  4019. virtual auto isContainer() const -> bool { return false; }
  4020. virtual auto setValue( std::string const &arg ) -> ParserResult = 0;
  4021. virtual auto setFlag( bool flag ) -> ParserResult = 0;
  4022. };
  4023. struct BoundValueRefBase : BoundRefBase {
  4024. auto isFlag() const -> bool override { return false; }
  4025. auto setFlag( bool ) -> ParserResult override {
  4026. return ParserResult::logicError( "Flags can only be set on boolean fields" );
  4027. }
  4028. };
  4029. struct BoundFlagRefBase : BoundRefBase {
  4030. auto isFlag() const -> bool override { return true; }
  4031. auto setValue( std::string const &arg ) -> ParserResult override {
  4032. bool flag;
  4033. auto result = convertInto( arg, flag );
  4034. if( result )
  4035. setFlag( flag );
  4036. return result;
  4037. }
  4038. };
  4039. template<typename T>
  4040. struct BoundRef : BoundValueRefBase {
  4041. T &m_ref;
  4042. explicit BoundRef( T &ref ) : m_ref( ref ) {}
  4043. auto setValue( std::string const &arg ) -> ParserResult override {
  4044. return convertInto( arg, m_ref );
  4045. }
  4046. };
  4047. template<typename T>
  4048. struct BoundRef<std::vector<T>> : BoundValueRefBase {
  4049. std::vector<T> &m_ref;
  4050. explicit BoundRef( std::vector<T> &ref ) : m_ref( ref ) {}
  4051. auto isContainer() const -> bool override { return true; }
  4052. auto setValue( std::string const &arg ) -> ParserResult override {
  4053. T temp;
  4054. auto result = convertInto( arg, temp );
  4055. if( result )
  4056. m_ref.push_back( temp );
  4057. return result;
  4058. }
  4059. };
  4060. struct BoundFlagRef : BoundFlagRefBase {
  4061. bool &m_ref;
  4062. explicit BoundFlagRef( bool &ref ) : m_ref( ref ) {}
  4063. auto setFlag( bool flag ) -> ParserResult override {
  4064. m_ref = flag;
  4065. return ParserResult::ok( ParseResultType::Matched );
  4066. }
  4067. };
  4068. template<typename ReturnType>
  4069. struct LambdaInvoker {
  4070. static_assert( std::is_same<ReturnType, ParserResult>::value, "Lambda must return void or clara::ParserResult" );
  4071. template<typename L, typename ArgType>
  4072. static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
  4073. return lambda( arg );
  4074. }
  4075. };
  4076. template<>
  4077. struct LambdaInvoker<void> {
  4078. template<typename L, typename ArgType>
  4079. static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
  4080. lambda( arg );
  4081. return ParserResult::ok( ParseResultType::Matched );
  4082. }
  4083. };
  4084. template<typename ArgType, typename L>
  4085. inline auto invokeLambda( L const &lambda, std::string const &arg ) -> ParserResult {
  4086. ArgType temp;
  4087. auto result = convertInto( arg, temp );
  4088. return !result
  4089. ? result
  4090. : LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( lambda, temp );
  4091. };
  4092. template<typename L>
  4093. struct BoundLambda : BoundValueRefBase {
  4094. L m_lambda;
  4095. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  4096. explicit BoundLambda( L const &lambda ) : m_lambda( lambda ) {}
  4097. auto setValue( std::string const &arg ) -> ParserResult override {
  4098. return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>( m_lambda, arg );
  4099. }
  4100. };
  4101. template<typename L>
  4102. struct BoundFlagLambda : BoundFlagRefBase {
  4103. L m_lambda;
  4104. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  4105. static_assert( std::is_same<typename UnaryLambdaTraits<L>::ArgType, bool>::value, "flags must be boolean" );
  4106. explicit BoundFlagLambda( L const &lambda ) : m_lambda( lambda ) {}
  4107. auto setFlag( bool flag ) -> ParserResult override {
  4108. return LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( m_lambda, flag );
  4109. }
  4110. };
  4111. enum class Optionality { Optional, Required };
  4112. struct Parser;
  4113. class ParserBase {
  4114. public:
  4115. virtual ~ParserBase() = default;
  4116. virtual auto validate() const -> Result { return Result::ok(); }
  4117. virtual auto parse( std::string const& exeName, TokenStream const &tokens) const -> InternalParseResult = 0;
  4118. virtual auto cardinality() const -> size_t { return 1; }
  4119. auto parse( Args const &args ) const -> InternalParseResult {
  4120. return parse( args.exeName(), TokenStream( args ) );
  4121. }
  4122. };
  4123. template<typename DerivedT>
  4124. class ComposableParserImpl : public ParserBase {
  4125. public:
  4126. template<typename T>
  4127. auto operator|( T const &other ) const -> Parser;
  4128. };
  4129. // Common code and state for Args and Opts
  4130. template<typename DerivedT>
  4131. class ParserRefImpl : public ComposableParserImpl<DerivedT> {
  4132. protected:
  4133. Optionality m_optionality = Optionality::Optional;
  4134. std::shared_ptr<BoundRefBase> m_ref;
  4135. std::string m_hint;
  4136. std::string m_description;
  4137. explicit ParserRefImpl( std::shared_ptr<BoundRefBase> const &ref ) : m_ref( ref ) {}
  4138. public:
  4139. template<typename T>
  4140. ParserRefImpl( T &ref, std::string const &hint )
  4141. : m_ref( std::make_shared<BoundRef<T>>( ref ) ),
  4142. m_hint( hint )
  4143. {}
  4144. template<typename LambdaT>
  4145. ParserRefImpl( LambdaT const &ref, std::string const &hint )
  4146. : m_ref( std::make_shared<BoundLambda<LambdaT>>( ref ) ),
  4147. m_hint(hint)
  4148. {}
  4149. auto operator()( std::string const &description ) -> DerivedT & {
  4150. m_description = description;
  4151. return static_cast<DerivedT &>( *this );
  4152. }
  4153. auto optional() -> DerivedT & {
  4154. m_optionality = Optionality::Optional;
  4155. return static_cast<DerivedT &>( *this );
  4156. };
  4157. auto required() -> DerivedT & {
  4158. m_optionality = Optionality::Required;
  4159. return static_cast<DerivedT &>( *this );
  4160. };
  4161. auto isOptional() const -> bool {
  4162. return m_optionality == Optionality::Optional;
  4163. }
  4164. auto cardinality() const -> size_t override {
  4165. if( m_ref->isContainer() )
  4166. return 0;
  4167. else
  4168. return 1;
  4169. }
  4170. auto hint() const -> std::string { return m_hint; }
  4171. };
  4172. class ExeName : public ComposableParserImpl<ExeName> {
  4173. std::shared_ptr<std::string> m_name;
  4174. std::shared_ptr<BoundRefBase> m_ref;
  4175. template<typename LambdaT>
  4176. static auto makeRef(LambdaT const &lambda) -> std::shared_ptr<BoundRefBase> {
  4177. return std::make_shared<BoundLambda<LambdaT>>( lambda) ;
  4178. }
  4179. public:
  4180. ExeName() : m_name( std::make_shared<std::string>( "<executable>" ) ) {}
  4181. explicit ExeName( std::string &ref ) : ExeName() {
  4182. m_ref = std::make_shared<BoundRef<std::string>>( ref );
  4183. }
  4184. template<typename LambdaT>
  4185. explicit ExeName( LambdaT const& lambda ) : ExeName() {
  4186. m_ref = std::make_shared<BoundLambda<LambdaT>>( lambda );
  4187. }
  4188. // The exe name is not parsed out of the normal tokens, but is handled specially
  4189. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  4190. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
  4191. }
  4192. auto name() const -> std::string { return *m_name; }
  4193. auto set( std::string const& newName ) -> ParserResult {
  4194. auto lastSlash = newName.find_last_of( "\\/" );
  4195. auto filename = ( lastSlash == std::string::npos )
  4196. ? newName
  4197. : newName.substr( lastSlash+1 );
  4198. *m_name = filename;
  4199. if( m_ref )
  4200. return m_ref->setValue( filename );
  4201. else
  4202. return ParserResult::ok( ParseResultType::Matched );
  4203. }
  4204. };
  4205. class Arg : public ParserRefImpl<Arg> {
  4206. public:
  4207. using ParserRefImpl::ParserRefImpl;
  4208. auto parse( std::string const &, TokenStream const &tokens ) const -> InternalParseResult override {
  4209. auto validationResult = validate();
  4210. if( !validationResult )
  4211. return InternalParseResult( validationResult );
  4212. auto remainingTokens = tokens;
  4213. auto const &token = *remainingTokens;
  4214. if( token.type != TokenType::Argument )
  4215. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
  4216. auto result = m_ref->setValue( remainingTokens->token );
  4217. if( !result )
  4218. return InternalParseResult( result );
  4219. else
  4220. return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
  4221. }
  4222. };
  4223. inline auto normaliseOpt( std::string const &optName ) -> std::string {
  4224. #ifdef CATCH_PLATFORM_WINDOWS
  4225. if( optName[0] == '/' )
  4226. return "-" + optName.substr( 1 );
  4227. else
  4228. #endif
  4229. return optName;
  4230. }
  4231. class Opt : public ParserRefImpl<Opt> {
  4232. protected:
  4233. std::vector<std::string> m_optNames;
  4234. public:
  4235. template<typename LambdaT>
  4236. explicit Opt( LambdaT const &ref ) : ParserRefImpl( std::make_shared<BoundFlagLambda<LambdaT>>( ref ) ) {}
  4237. explicit Opt( bool &ref ) : ParserRefImpl( std::make_shared<BoundFlagRef>( ref ) ) {}
  4238. template<typename LambdaT>
  4239. Opt( LambdaT const &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  4240. template<typename T>
  4241. Opt( T &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  4242. auto operator[]( std::string const &optName ) -> Opt & {
  4243. m_optNames.push_back( optName );
  4244. return *this;
  4245. }
  4246. auto getHelpColumns() const -> std::vector<HelpColumns> {
  4247. std::ostringstream oss;
  4248. bool first = true;
  4249. for( auto const &opt : m_optNames ) {
  4250. if (first)
  4251. first = false;
  4252. else
  4253. oss << ", ";
  4254. oss << opt;
  4255. }
  4256. if( !m_hint.empty() )
  4257. oss << " <" << m_hint << ">";
  4258. return { { oss.str(), m_description } };
  4259. }
  4260. auto isMatch( std::string const &optToken ) const -> bool {
  4261. auto normalisedToken = normaliseOpt( optToken );
  4262. for( auto const &name : m_optNames ) {
  4263. if( normaliseOpt( name ) == normalisedToken )
  4264. return true;
  4265. }
  4266. return false;
  4267. }
  4268. using ParserBase::parse;
  4269. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  4270. auto validationResult = validate();
  4271. if( !validationResult )
  4272. return InternalParseResult( validationResult );
  4273. auto remainingTokens = tokens;
  4274. if( remainingTokens && remainingTokens->type == TokenType::Option ) {
  4275. auto const &token = *remainingTokens;
  4276. if( isMatch(token.token ) ) {
  4277. if( m_ref->isFlag() ) {
  4278. auto result = m_ref->setFlag( true );
  4279. if( !result )
  4280. return InternalParseResult( result );
  4281. if( result.value() == ParseResultType::ShortCircuitAll )
  4282. return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
  4283. } else {
  4284. ++remainingTokens;
  4285. if( !remainingTokens )
  4286. return InternalParseResult::runtimeError( "Expected argument following " + token.token );
  4287. auto const &argToken = *remainingTokens;
  4288. if( argToken.type != TokenType::Argument )
  4289. return InternalParseResult::runtimeError( "Expected argument following " + token.token );
  4290. auto result = m_ref->setValue( argToken.token );
  4291. if( !result )
  4292. return InternalParseResult( result );
  4293. if( result.value() == ParseResultType::ShortCircuitAll )
  4294. return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
  4295. }
  4296. return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
  4297. }
  4298. }
  4299. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
  4300. }
  4301. auto validate() const -> Result override {
  4302. if( m_optNames.empty() )
  4303. return Result::logicError( "No options supplied to Opt" );
  4304. for( auto const &name : m_optNames ) {
  4305. if( name.empty() )
  4306. return Result::logicError( "Option name cannot be empty" );
  4307. #ifdef CATCH_PLATFORM_WINDOWS
  4308. if( name[0] != '-' && name[0] != '/' )
  4309. return Result::logicError( "Option name must begin with '-' or '/'" );
  4310. #else
  4311. if( name[0] != '-' )
  4312. return Result::logicError( "Option name must begin with '-'" );
  4313. #endif
  4314. }
  4315. return ParserRefImpl::validate();
  4316. }
  4317. };
  4318. struct Help : Opt {
  4319. Help( bool &showHelpFlag )
  4320. : Opt([&]( bool flag ) {
  4321. showHelpFlag = flag;
  4322. return ParserResult::ok( ParseResultType::ShortCircuitAll );
  4323. })
  4324. {
  4325. static_cast<Opt &>( *this )
  4326. ("display usage information")
  4327. ["-?"]["-h"]["--help"]
  4328. .optional();
  4329. }
  4330. };
  4331. struct Parser : ParserBase {
  4332. mutable ExeName m_exeName;
  4333. std::vector<Opt> m_options;
  4334. std::vector<Arg> m_args;
  4335. auto operator|=( ExeName const &exeName ) -> Parser & {
  4336. m_exeName = exeName;
  4337. return *this;
  4338. }
  4339. auto operator|=( Arg const &arg ) -> Parser & {
  4340. m_args.push_back(arg);
  4341. return *this;
  4342. }
  4343. auto operator|=( Opt const &opt ) -> Parser & {
  4344. m_options.push_back(opt);
  4345. return *this;
  4346. }
  4347. auto operator|=( Parser const &other ) -> Parser & {
  4348. m_options.insert(m_options.end(), other.m_options.begin(), other.m_options.end());
  4349. m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end());
  4350. return *this;
  4351. }
  4352. template<typename T>
  4353. auto operator|( T const &other ) const -> Parser {
  4354. return Parser( *this ) |= other;
  4355. }
  4356. auto getHelpColumns() const -> std::vector<HelpColumns> {
  4357. std::vector<HelpColumns> cols;
  4358. for (auto const &o : m_options) {
  4359. auto childCols = o.getHelpColumns();
  4360. cols.insert( cols.end(), childCols.begin(), childCols.end() );
  4361. }
  4362. return cols;
  4363. }
  4364. void writeToStream( std::ostream &os ) const {
  4365. if (!m_exeName.name().empty()) {
  4366. os << "usage:\n" << " " << m_exeName.name() << " ";
  4367. bool required = true, first = true;
  4368. for( auto const &arg : m_args ) {
  4369. if (first)
  4370. first = false;
  4371. else
  4372. os << " ";
  4373. if( arg.isOptional() && required ) {
  4374. os << "[";
  4375. required = false;
  4376. }
  4377. os << "<" << arg.hint() << ">";
  4378. if( arg.cardinality() == 0 )
  4379. os << " ... ";
  4380. }
  4381. if( !required )
  4382. os << "]";
  4383. if( !m_options.empty() )
  4384. os << " options";
  4385. os << "\n\nwhere options are:" << std::endl;
  4386. }
  4387. auto rows = getHelpColumns();
  4388. size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH;
  4389. size_t optWidth = 0;
  4390. for( auto const &cols : rows )
  4391. optWidth = (std::max)(optWidth, cols.left.size() + 2);
  4392. for( auto const &cols : rows ) {
  4393. auto row =
  4394. TextFlow::Column( cols.left ).width( optWidth ).indent( 2 ) +
  4395. TextFlow::Spacer(4) +
  4396. TextFlow::Column( cols.right ).width( consoleWidth - 7 - optWidth );
  4397. os << row << std::endl;
  4398. }
  4399. }
  4400. friend auto operator<<( std::ostream &os, Parser const &parser ) -> std::ostream& {
  4401. parser.writeToStream( os );
  4402. return os;
  4403. }
  4404. auto validate() const -> Result override {
  4405. for( auto const &opt : m_options ) {
  4406. auto result = opt.validate();
  4407. if( !result )
  4408. return result;
  4409. }
  4410. for( auto const &arg : m_args ) {
  4411. auto result = arg.validate();
  4412. if( !result )
  4413. return result;
  4414. }
  4415. return Result::ok();
  4416. }
  4417. using ParserBase::parse;
  4418. auto parse( std::string const& exeName, TokenStream const &tokens ) const -> InternalParseResult override {
  4419. struct ParserInfo {
  4420. ParserBase const* parser = nullptr;
  4421. size_t count = 0;
  4422. };
  4423. const size_t totalParsers = m_options.size() + m_args.size();
  4424. assert( totalParsers < 512 );
  4425. // ParserInfo parseInfos[totalParsers]; // <-- this is what we really want to do
  4426. ParserInfo parseInfos[512];
  4427. {
  4428. size_t i = 0;
  4429. for (auto const &opt : m_options) parseInfos[i++].parser = &opt;
  4430. for (auto const &arg : m_args) parseInfos[i++].parser = &arg;
  4431. }
  4432. m_exeName.set( exeName );
  4433. auto result = InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
  4434. while( result.value().remainingTokens() ) {
  4435. bool tokenParsed = false;
  4436. for( size_t i = 0; i < totalParsers; ++i ) {
  4437. auto& parseInfo = parseInfos[i];
  4438. if( parseInfo.parser->cardinality() == 0 || parseInfo.count < parseInfo.parser->cardinality() ) {
  4439. result = parseInfo.parser->parse(exeName, result.value().remainingTokens());
  4440. if (!result)
  4441. return result;
  4442. if (result.value().type() != ParseResultType::NoMatch) {
  4443. tokenParsed = true;
  4444. ++parseInfo.count;
  4445. break;
  4446. }
  4447. }
  4448. }
  4449. if( result.value().type() == ParseResultType::ShortCircuitAll )
  4450. return result;
  4451. if( !tokenParsed )
  4452. return InternalParseResult::runtimeError( "Unrecognised token: " + result.value().remainingTokens()->token );
  4453. }
  4454. // !TBD Check missing required options
  4455. return result;
  4456. }
  4457. };
  4458. template<typename DerivedT>
  4459. template<typename T>
  4460. auto ComposableParserImpl<DerivedT>::operator|( T const &other ) const -> Parser {
  4461. return Parser() | static_cast<DerivedT const &>( *this ) | other;
  4462. }
  4463. } // namespace detail
  4464. // A Combined parser
  4465. using detail::Parser;
  4466. // A parser for options
  4467. using detail::Opt;
  4468. // A parser for arguments
  4469. using detail::Arg;
  4470. // Wrapper for argc, argv from main()
  4471. using detail::Args;
  4472. // Specifies the name of the executable
  4473. using detail::ExeName;
  4474. // Convenience wrapper for option parser that specifies the help option
  4475. using detail::Help;
  4476. // enum of result types from a parse
  4477. using detail::ParseResultType;
  4478. // Result type for parser operation
  4479. using detail::ParserResult;
  4480. }} // namespace Catch::clara
  4481. // end clara.hpp
  4482. #ifdef __clang__
  4483. #pragma clang diagnostic pop
  4484. #endif
  4485. // Restore Clara's value for console width, if present
  4486. #ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  4487. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  4488. #undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  4489. #endif
  4490. // end catch_clara.h
  4491. namespace Catch {
  4492. clara::Parser makeCommandLineParser( ConfigData& config );
  4493. } // end namespace Catch
  4494. // end catch_commandline.h
  4495. #include <fstream>
  4496. #include <ctime>
  4497. namespace Catch {
  4498. clara::Parser makeCommandLineParser( ConfigData& config ) {
  4499. using namespace clara;
  4500. auto const setWarning = [&]( std::string const& warning ) {
  4501. if( warning != "NoAssertions" )
  4502. return ParserResult::runtimeError( "Unrecognised warning: '" + warning + "'" );
  4503. config.warnings = static_cast<WarnAbout::What>( config.warnings | WarnAbout::NoAssertions );
  4504. return ParserResult::ok( ParseResultType::Matched );
  4505. };
  4506. auto const loadTestNamesFromFile = [&]( std::string const& filename ) {
  4507. std::ifstream f( filename.c_str() );
  4508. if( !f.is_open() )
  4509. return ParserResult::runtimeError( "Unable to load input file: '" + filename + "'" );
  4510. std::string line;
  4511. while( std::getline( f, line ) ) {
  4512. line = trim(line);
  4513. if( !line.empty() && !startsWith( line, '#' ) ) {
  4514. if( !startsWith( line, '"' ) )
  4515. line = '"' + line + '"';
  4516. config.testsOrTags.push_back( line + ',' );
  4517. }
  4518. }
  4519. return ParserResult::ok( ParseResultType::Matched );
  4520. };
  4521. auto const setTestOrder = [&]( std::string const& order ) {
  4522. if( startsWith( "declared", order ) )
  4523. config.runOrder = RunTests::InDeclarationOrder;
  4524. else if( startsWith( "lexical", order ) )
  4525. config.runOrder = RunTests::InLexicographicalOrder;
  4526. else if( startsWith( "random", order ) )
  4527. config.runOrder = RunTests::InRandomOrder;
  4528. else
  4529. return clara::ParserResult::runtimeError( "Unrecognised ordering: '" + order + "'" );
  4530. return ParserResult::ok( ParseResultType::Matched );
  4531. };
  4532. auto const setRngSeed = [&]( std::string const& seed ) {
  4533. if( seed != "time" )
  4534. return clara::detail::convertInto( seed, config.rngSeed );
  4535. config.rngSeed = static_cast<unsigned int>( std::time(nullptr) );
  4536. return ParserResult::ok( ParseResultType::Matched );
  4537. };
  4538. auto const setColourUsage = [&]( std::string const& useColour ) {
  4539. auto mode = toLower( useColour );
  4540. if( mode == "yes" )
  4541. config.useColour = UseColour::Yes;
  4542. else if( mode == "no" )
  4543. config.useColour = UseColour::No;
  4544. else if( mode == "auto" )
  4545. config.useColour = UseColour::Auto;
  4546. else
  4547. return ParserResult::runtimeError( "colour mode must be one of: auto, yes or no. '" + useColour + "' not recognised" );
  4548. return ParserResult::ok( ParseResultType::Matched );
  4549. };
  4550. auto const setWaitForKeypress = [&]( std::string const& keypress ) {
  4551. auto keypressLc = toLower( keypress );
  4552. if( keypressLc == "start" )
  4553. config.waitForKeypress = WaitForKeypress::BeforeStart;
  4554. else if( keypressLc == "exit" )
  4555. config.waitForKeypress = WaitForKeypress::BeforeExit;
  4556. else if( keypressLc == "both" )
  4557. config.waitForKeypress = WaitForKeypress::BeforeStartAndExit;
  4558. else
  4559. return ParserResult::runtimeError( "keypress argument must be one of: start, exit or both. '" + keypress + "' not recognised" );
  4560. return ParserResult::ok( ParseResultType::Matched );
  4561. };
  4562. auto const setVerbosity = [&]( std::string const& verbosity ) {
  4563. auto lcVerbosity = toLower( verbosity );
  4564. if( lcVerbosity == "quiet" )
  4565. config.verbosity = Verbosity::Quiet;
  4566. else if( lcVerbosity == "normal" )
  4567. config.verbosity = Verbosity::Normal;
  4568. else if( lcVerbosity == "high" )
  4569. config.verbosity = Verbosity::High;
  4570. else
  4571. return ParserResult::runtimeError( "Unrecognised verbosity, '" + verbosity + "'" );
  4572. return ParserResult::ok( ParseResultType::Matched );
  4573. };
  4574. auto cli
  4575. = ExeName( config.processName )
  4576. | Help( config.showHelp )
  4577. | Opt( config.listTests )
  4578. ["-l"]["--list-tests"]
  4579. ( "list all/matching test cases" )
  4580. | Opt( config.listTags )
  4581. ["-t"]["--list-tags"]
  4582. ( "list all/matching tags" )
  4583. | Opt( config.showSuccessfulTests )
  4584. ["-s"]["--success"]
  4585. ( "include successful tests in output" )
  4586. | Opt( config.shouldDebugBreak )
  4587. ["-b"]["--break"]
  4588. ( "break into debugger on failure" )
  4589. | Opt( config.noThrow )
  4590. ["-e"]["--nothrow"]
  4591. ( "skip exception tests" )
  4592. | Opt( config.showInvisibles )
  4593. ["-i"]["--invisibles"]
  4594. ( "show invisibles (tabs, newlines)" )
  4595. | Opt( config.outputFilename, "filename" )
  4596. ["-o"]["--out"]
  4597. ( "output filename" )
  4598. | Opt( config.reporterNames, "name" )
  4599. ["-r"]["--reporter"]
  4600. ( "reporter to use (defaults to console)" )
  4601. | Opt( config.name, "name" )
  4602. ["-n"]["--name"]
  4603. ( "suite name" )
  4604. | Opt( [&]( bool ){ config.abortAfter = 1; } )
  4605. ["-a"]["--abort"]
  4606. ( "abort at first failure" )
  4607. | Opt( [&]( int x ){ config.abortAfter = x; }, "no. failures" )
  4608. ["-x"]["--abortx"]
  4609. ( "abort after x failures" )
  4610. | Opt( setWarning, "warning name" )
  4611. ["-w"]["--warn"]
  4612. ( "enable warnings" )
  4613. | Opt( [&]( bool flag ) { config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never; }, "yes|no" )
  4614. ["-d"]["--durations"]
  4615. ( "show test durations" )
  4616. | Opt( loadTestNamesFromFile, "filename" )
  4617. ["-f"]["--input-file"]
  4618. ( "load test names to run from a file" )
  4619. | Opt( config.filenamesAsTags )
  4620. ["-#"]["--filenames-as-tags"]
  4621. ( "adds a tag for the filename" )
  4622. | Opt( config.sectionsToRun, "section name" )
  4623. ["-c"]["--section"]
  4624. ( "specify section to run" )
  4625. | Opt( setVerbosity, "quiet|normal|high" )
  4626. ["-v"]["--verbosity"]
  4627. ( "set output verbosity" )
  4628. | Opt( config.listTestNamesOnly )
  4629. ["--list-test-names-only"]
  4630. ( "list all/matching test cases names only" )
  4631. | Opt( config.listReporters )
  4632. ["--list-reporters"]
  4633. ( "list all reporters" )
  4634. | Opt( setTestOrder, "decl|lex|rand" )
  4635. ["--order"]
  4636. ( "test case order (defaults to decl)" )
  4637. | Opt( setRngSeed, "'time'|number" )
  4638. ["--rng-seed"]
  4639. ( "set a specific seed for random numbers" )
  4640. | Opt( setColourUsage, "yes|no" )
  4641. ["--use-colour"]
  4642. ( "should output be colourised" )
  4643. | Opt( config.libIdentify )
  4644. ["--libidentify"]
  4645. ( "report name and version according to libidentify standard" )
  4646. | Opt( setWaitForKeypress, "start|exit|both" )
  4647. ["--wait-for-keypress"]
  4648. ( "waits for a keypress before exiting" )
  4649. | Opt( config.benchmarkResolutionMultiple, "multiplier" )
  4650. ["--benchmark-resolution-multiple"]
  4651. ( "multiple of clock resolution to run benchmarks" )
  4652. | Arg( config.testsOrTags, "test name|pattern|tags" )
  4653. ( "which test or tests to use" );
  4654. return cli;
  4655. }
  4656. } // end namespace Catch
  4657. // end catch_commandline.cpp
  4658. // start catch_common.cpp
  4659. #include <cstring>
  4660. #include <ostream>
  4661. namespace Catch {
  4662. SourceLineInfo::SourceLineInfo( char const* _file, std::size_t _line ) noexcept
  4663. : file( _file ),
  4664. line( _line )
  4665. {}
  4666. bool SourceLineInfo::empty() const noexcept {
  4667. return file[0] == '\0';
  4668. }
  4669. bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const noexcept {
  4670. return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0);
  4671. }
  4672. bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const noexcept {
  4673. return line < other.line || ( line == other.line && (std::strcmp(file, other.file) < 0));
  4674. }
  4675. std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) {
  4676. #ifndef __GNUG__
  4677. os << info.file << '(' << info.line << ')';
  4678. #else
  4679. os << info.file << ':' << info.line;
  4680. #endif
  4681. return os;
  4682. }
  4683. bool isTrue( bool value ){ return value; }
  4684. bool alwaysTrue() { return true; }
  4685. bool alwaysFalse() { return false; }
  4686. std::string StreamEndStop::operator+() const {
  4687. return std::string();
  4688. }
  4689. NonCopyable::NonCopyable() = default;
  4690. NonCopyable::~NonCopyable() = default;
  4691. }
  4692. // end catch_common.cpp
  4693. // start catch_config.cpp
  4694. namespace Catch {
  4695. Config::Config( ConfigData const& data )
  4696. : m_data( data ),
  4697. m_stream( openStream() )
  4698. {
  4699. if( !data.testsOrTags.empty() ) {
  4700. TestSpecParser parser( ITagAliasRegistry::get() );
  4701. for( auto const& testOrTags : data.testsOrTags )
  4702. parser.parse( testOrTags );
  4703. m_testSpec = parser.testSpec();
  4704. }
  4705. }
  4706. std::string const& Config::getFilename() const {
  4707. return m_data.outputFilename ;
  4708. }
  4709. bool Config::listTests() const { return m_data.listTests; }
  4710. bool Config::listTestNamesOnly() const { return m_data.listTestNamesOnly; }
  4711. bool Config::listTags() const { return m_data.listTags; }
  4712. bool Config::listReporters() const { return m_data.listReporters; }
  4713. std::string Config::getProcessName() const { return m_data.processName; }
  4714. std::vector<std::string> const& Config::getReporterNames() const { return m_data.reporterNames; }
  4715. std::vector<std::string> const& Config::getSectionsToRun() const { return m_data.sectionsToRun; }
  4716. TestSpec const& Config::testSpec() const { return m_testSpec; }
  4717. bool Config::showHelp() const { return m_data.showHelp; }
  4718. // IConfig interface
  4719. bool Config::allowThrows() const { return !m_data.noThrow; }
  4720. std::ostream& Config::stream() const { return m_stream->stream(); }
  4721. std::string Config::name() const { return m_data.name.empty() ? m_data.processName : m_data.name; }
  4722. bool Config::includeSuccessfulResults() const { return m_data.showSuccessfulTests; }
  4723. bool Config::warnAboutMissingAssertions() const { return m_data.warnings & WarnAbout::NoAssertions; }
  4724. ShowDurations::OrNot Config::showDurations() const { return m_data.showDurations; }
  4725. RunTests::InWhatOrder Config::runOrder() const { return m_data.runOrder; }
  4726. unsigned int Config::rngSeed() const { return m_data.rngSeed; }
  4727. int Config::benchmarkResolutionMultiple() const { return m_data.benchmarkResolutionMultiple; }
  4728. UseColour::YesOrNo Config::useColour() const { return m_data.useColour; }
  4729. bool Config::shouldDebugBreak() const { return m_data.shouldDebugBreak; }
  4730. int Config::abortAfter() const { return m_data.abortAfter; }
  4731. bool Config::showInvisibles() const { return m_data.showInvisibles; }
  4732. Verbosity Config::verbosity() const { return m_data.verbosity; }
  4733. IStream const* Config::openStream() {
  4734. if( m_data.outputFilename.empty() )
  4735. return new CoutStream();
  4736. else if( m_data.outputFilename[0] == '%' ) {
  4737. if( m_data.outputFilename == "%debug" )
  4738. return new DebugOutStream();
  4739. else
  4740. CATCH_ERROR( "Unrecognised stream: '" << m_data.outputFilename << "'" );
  4741. }
  4742. else
  4743. return new FileStream( m_data.outputFilename );
  4744. }
  4745. } // end namespace Catch
  4746. // end catch_config.cpp
  4747. // start catch_console_colour.cpp
  4748. #if defined(__clang__)
  4749. # pragma clang diagnostic push
  4750. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  4751. #endif
  4752. // start catch_errno_guard.h
  4753. namespace Catch {
  4754. class ErrnoGuard {
  4755. public:
  4756. ErrnoGuard();
  4757. ~ErrnoGuard();
  4758. private:
  4759. int m_oldErrno;
  4760. };
  4761. }
  4762. // end catch_errno_guard.h
  4763. // start catch_windows_h_proxy.h
  4764. #if defined(CATCH_PLATFORM_WINDOWS)
  4765. #if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX)
  4766. # define CATCH_DEFINED_NOMINMAX
  4767. # define NOMINMAX
  4768. #endif
  4769. #if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN)
  4770. # define CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  4771. # define WIN32_LEAN_AND_MEAN
  4772. #endif
  4773. #ifdef __AFXDLL
  4774. #include <AfxWin.h>
  4775. #else
  4776. #include <windows.h>
  4777. #endif
  4778. #ifdef CATCH_DEFINED_NOMINMAX
  4779. # undef NOMINMAX
  4780. #endif
  4781. #ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  4782. # undef WIN32_LEAN_AND_MEAN
  4783. #endif
  4784. #endif // defined(CATCH_PLATFORM_WINDOWS)
  4785. // end catch_windows_h_proxy.h
  4786. namespace Catch {
  4787. namespace {
  4788. struct IColourImpl {
  4789. virtual ~IColourImpl() = default;
  4790. virtual void use( Colour::Code _colourCode ) = 0;
  4791. };
  4792. struct NoColourImpl : IColourImpl {
  4793. void use( Colour::Code ) {}
  4794. static IColourImpl* instance() {
  4795. static NoColourImpl s_instance;
  4796. return &s_instance;
  4797. }
  4798. };
  4799. } // anon namespace
  4800. } // namespace Catch
  4801. #if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI )
  4802. # ifdef CATCH_PLATFORM_WINDOWS
  4803. # define CATCH_CONFIG_COLOUR_WINDOWS
  4804. # else
  4805. # define CATCH_CONFIG_COLOUR_ANSI
  4806. # endif
  4807. #endif
  4808. #if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) /////////////////////////////////////////
  4809. namespace Catch {
  4810. namespace {
  4811. class Win32ColourImpl : public IColourImpl {
  4812. public:
  4813. Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) )
  4814. {
  4815. CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
  4816. GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo );
  4817. originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY );
  4818. originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY );
  4819. }
  4820. virtual void use( Colour::Code _colourCode ) override {
  4821. switch( _colourCode ) {
  4822. case Colour::None: return setTextAttribute( originalForegroundAttributes );
  4823. case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  4824. case Colour::Red: return setTextAttribute( FOREGROUND_RED );
  4825. case Colour::Green: return setTextAttribute( FOREGROUND_GREEN );
  4826. case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE );
  4827. case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN );
  4828. case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN );
  4829. case Colour::Grey: return setTextAttribute( 0 );
  4830. case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY );
  4831. case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED );
  4832. case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN );
  4833. case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  4834. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  4835. }
  4836. }
  4837. private:
  4838. void setTextAttribute( WORD _textAttribute ) {
  4839. SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes );
  4840. }
  4841. HANDLE stdoutHandle;
  4842. WORD originalForegroundAttributes;
  4843. WORD originalBackgroundAttributes;
  4844. };
  4845. IColourImpl* platformColourInstance() {
  4846. static Win32ColourImpl s_instance;
  4847. IConfigPtr config = getCurrentContext().getConfig();
  4848. UseColour::YesOrNo colourMode = config
  4849. ? config->useColour()
  4850. : UseColour::Auto;
  4851. if( colourMode == UseColour::Auto )
  4852. colourMode = UseColour::Yes;
  4853. return colourMode == UseColour::Yes
  4854. ? &s_instance
  4855. : NoColourImpl::instance();
  4856. }
  4857. } // end anon namespace
  4858. } // end namespace Catch
  4859. #elif defined( CATCH_CONFIG_COLOUR_ANSI ) //////////////////////////////////////
  4860. #include <unistd.h>
  4861. namespace Catch {
  4862. namespace {
  4863. // use POSIX/ ANSI console terminal codes
  4864. // Thanks to Adam Strzelecki for original contribution
  4865. // (http://github.com/nanoant)
  4866. // https://github.com/philsquared/Catch/pull/131
  4867. class PosixColourImpl : public IColourImpl {
  4868. public:
  4869. virtual void use( Colour::Code _colourCode ) override {
  4870. switch( _colourCode ) {
  4871. case Colour::None:
  4872. case Colour::White: return setColour( "[0m" );
  4873. case Colour::Red: return setColour( "[0;31m" );
  4874. case Colour::Green: return setColour( "[0;32m" );
  4875. case Colour::Blue: return setColour( "[0;34m" );
  4876. case Colour::Cyan: return setColour( "[0;36m" );
  4877. case Colour::Yellow: return setColour( "[0;33m" );
  4878. case Colour::Grey: return setColour( "[1;30m" );
  4879. case Colour::LightGrey: return setColour( "[0;37m" );
  4880. case Colour::BrightRed: return setColour( "[1;31m" );
  4881. case Colour::BrightGreen: return setColour( "[1;32m" );
  4882. case Colour::BrightWhite: return setColour( "[1;37m" );
  4883. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  4884. }
  4885. }
  4886. static IColourImpl* instance() {
  4887. static PosixColourImpl s_instance;
  4888. return &s_instance;
  4889. }
  4890. private:
  4891. void setColour( const char* _escapeCode ) {
  4892. Catch::cout() << '\033' << _escapeCode;
  4893. }
  4894. };
  4895. bool useColourOnPlatform() {
  4896. return
  4897. #ifdef CATCH_PLATFORM_MAC
  4898. !isDebuggerActive() &&
  4899. #endif
  4900. isatty(STDOUT_FILENO);
  4901. }
  4902. IColourImpl* platformColourInstance() {
  4903. ErrnoGuard guard;
  4904. IConfigPtr config = getCurrentContext().getConfig();
  4905. UseColour::YesOrNo colourMode = config
  4906. ? config->useColour()
  4907. : UseColour::Auto;
  4908. if( colourMode == UseColour::Auto )
  4909. colourMode = useColourOnPlatform()
  4910. ? UseColour::Yes
  4911. : UseColour::No;
  4912. return colourMode == UseColour::Yes
  4913. ? PosixColourImpl::instance()
  4914. : NoColourImpl::instance();
  4915. }
  4916. } // end anon namespace
  4917. } // end namespace Catch
  4918. #else // not Windows or ANSI ///////////////////////////////////////////////
  4919. namespace Catch {
  4920. static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); }
  4921. } // end namespace Catch
  4922. #endif // Windows/ ANSI/ None
  4923. namespace Catch {
  4924. Colour::Colour( Code _colourCode ) { use( _colourCode ); }
  4925. Colour::Colour( Colour&& rhs ) noexcept {
  4926. m_moved = rhs.m_moved;
  4927. rhs.m_moved = true;
  4928. }
  4929. Colour& Colour::operator=( Colour&& rhs ) noexcept {
  4930. m_moved = rhs.m_moved;
  4931. rhs.m_moved = true;
  4932. return *this;
  4933. }
  4934. Colour::~Colour(){ if( !m_moved ) use( None ); }
  4935. void Colour::use( Code _colourCode ) {
  4936. static IColourImpl* impl = platformColourInstance();
  4937. impl->use( _colourCode );
  4938. }
  4939. std::ostream& operator << ( std::ostream& os, Colour const& ) {
  4940. return os;
  4941. }
  4942. } // end namespace Catch
  4943. #if defined(__clang__)
  4944. # pragma clang diagnostic pop
  4945. #endif
  4946. // end catch_console_colour.cpp
  4947. // start catch_context.cpp
  4948. namespace Catch {
  4949. class Context : public IMutableContext, NonCopyable {
  4950. public: // IContext
  4951. virtual IResultCapture* getResultCapture() override {
  4952. return m_resultCapture;
  4953. }
  4954. virtual IRunner* getRunner() override {
  4955. return m_runner;
  4956. }
  4957. virtual IConfigPtr getConfig() const override {
  4958. return m_config;
  4959. }
  4960. virtual ~Context() override;
  4961. public: // IMutableContext
  4962. virtual void setResultCapture( IResultCapture* resultCapture ) override {
  4963. m_resultCapture = resultCapture;
  4964. }
  4965. virtual void setRunner( IRunner* runner ) override {
  4966. m_runner = runner;
  4967. }
  4968. virtual void setConfig( IConfigPtr const& config ) override {
  4969. m_config = config;
  4970. }
  4971. friend IMutableContext& getCurrentMutableContext();
  4972. private:
  4973. IConfigPtr m_config;
  4974. IRunner* m_runner = nullptr;
  4975. IResultCapture* m_resultCapture = nullptr;
  4976. };
  4977. namespace {
  4978. Context* currentContext = nullptr;
  4979. }
  4980. IMutableContext& getCurrentMutableContext() {
  4981. if( !currentContext )
  4982. currentContext = new Context();
  4983. return *currentContext;
  4984. }
  4985. IContext& getCurrentContext() {
  4986. return getCurrentMutableContext();
  4987. }
  4988. void cleanUpContext() {
  4989. delete currentContext;
  4990. currentContext = nullptr;
  4991. }
  4992. IContext::~IContext() = default;
  4993. IMutableContext::~IMutableContext() = default;
  4994. Context::~Context() = default;
  4995. }
  4996. // end catch_context.cpp
  4997. // start catch_debug_console.cpp
  4998. // start catch_debug_console.h
  4999. #include <string>
  5000. namespace Catch {
  5001. void writeToDebugConsole( std::string const& text );
  5002. }
  5003. // end catch_debug_console.h
  5004. #ifdef CATCH_PLATFORM_WINDOWS
  5005. namespace Catch {
  5006. void writeToDebugConsole( std::string const& text ) {
  5007. ::OutputDebugStringA( text.c_str() );
  5008. }
  5009. }
  5010. #else
  5011. namespace Catch {
  5012. void writeToDebugConsole( std::string const& text ) {
  5013. // !TBD: Need a version for Mac/ XCode and other IDEs
  5014. Catch::cout() << text;
  5015. }
  5016. }
  5017. #endif // Platform
  5018. // end catch_debug_console.cpp
  5019. // start catch_debugger.cpp
  5020. #ifdef CATCH_PLATFORM_MAC
  5021. #include <assert.h>
  5022. #include <stdbool.h>
  5023. #include <sys/types.h>
  5024. #include <unistd.h>
  5025. #include <sys/sysctl.h>
  5026. namespace Catch {
  5027. // The following function is taken directly from the following technical note:
  5028. // http://developer.apple.com/library/mac/#qa/qa2004/qa1361.html
  5029. // Returns true if the current process is being debugged (either
  5030. // running under the debugger or has a debugger attached post facto).
  5031. bool isDebuggerActive(){
  5032. int mib[4];
  5033. struct kinfo_proc info;
  5034. std::size_t size;
  5035. // Initialize the flags so that, if sysctl fails for some bizarre
  5036. // reason, we get a predictable result.
  5037. info.kp_proc.p_flag = 0;
  5038. // Initialize mib, which tells sysctl the info we want, in this case
  5039. // we're looking for information about a specific process ID.
  5040. mib[0] = CTL_KERN;
  5041. mib[1] = KERN_PROC;
  5042. mib[2] = KERN_PROC_PID;
  5043. mib[3] = getpid();
  5044. // Call sysctl.
  5045. size = sizeof(info);
  5046. if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0) != 0 ) {
  5047. Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl;
  5048. return false;
  5049. }
  5050. // We're being debugged if the P_TRACED flag is set.
  5051. return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
  5052. }
  5053. } // namespace Catch
  5054. #elif defined(CATCH_PLATFORM_LINUX)
  5055. #include <fstream>
  5056. #include <string>
  5057. namespace Catch{
  5058. // The standard POSIX way of detecting a debugger is to attempt to
  5059. // ptrace() the process, but this needs to be done from a child and not
  5060. // this process itself to still allow attaching to this process later
  5061. // if wanted, so is rather heavy. Under Linux we have the PID of the
  5062. // "debugger" (which doesn't need to be gdb, of course, it could also
  5063. // be strace, for example) in /proc/$PID/status, so just get it from
  5064. // there instead.
  5065. bool isDebuggerActive(){
  5066. // Libstdc++ has a bug, where std::ifstream sets errno to 0
  5067. // This way our users can properly assert over errno values
  5068. ErrnoGuard guard;
  5069. std::ifstream in("/proc/self/status");
  5070. for( std::string line; std::getline(in, line); ) {
  5071. static const int PREFIX_LEN = 11;
  5072. if( line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0 ) {
  5073. // We're traced if the PID is not 0 and no other PID starts
  5074. // with 0 digit, so it's enough to check for just a single
  5075. // character.
  5076. return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0';
  5077. }
  5078. }
  5079. return false;
  5080. }
  5081. } // namespace Catch
  5082. #elif defined(_MSC_VER)
  5083. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  5084. namespace Catch {
  5085. bool isDebuggerActive() {
  5086. return IsDebuggerPresent() != 0;
  5087. }
  5088. }
  5089. #elif defined(__MINGW32__)
  5090. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  5091. namespace Catch {
  5092. bool isDebuggerActive() {
  5093. return IsDebuggerPresent() != 0;
  5094. }
  5095. }
  5096. #else
  5097. namespace Catch {
  5098. bool isDebuggerActive() { return false; }
  5099. }
  5100. #endif // Platform
  5101. // end catch_debugger.cpp
  5102. // start catch_decomposer.cpp
  5103. namespace Catch {
  5104. ITransientExpression::~ITransientExpression() = default;
  5105. void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs ) {
  5106. if( lhs.size() + rhs.size() < 40 &&
  5107. lhs.find('\n') == std::string::npos &&
  5108. rhs.find('\n') == std::string::npos )
  5109. os << lhs << " " << op << " " << rhs;
  5110. else
  5111. os << lhs << "\n" << op << "\n" << rhs;
  5112. }
  5113. }
  5114. // end catch_decomposer.cpp
  5115. // start catch_errno_guard.cpp
  5116. #include <cerrno>
  5117. namespace Catch {
  5118. ErrnoGuard::ErrnoGuard():m_oldErrno(errno){}
  5119. ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; }
  5120. }
  5121. // end catch_errno_guard.cpp
  5122. // start catch_exception_translator_registry.cpp
  5123. // start catch_exception_translator_registry.h
  5124. #include <vector>
  5125. #include <string>
  5126. #include <memory>
  5127. namespace Catch {
  5128. class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry {
  5129. public:
  5130. ~ExceptionTranslatorRegistry();
  5131. virtual void registerTranslator( const IExceptionTranslator* translator );
  5132. virtual std::string translateActiveException() const override;
  5133. std::string tryTranslators() const;
  5134. private:
  5135. std::vector<std::unique_ptr<IExceptionTranslator const>> m_translators;
  5136. };
  5137. }
  5138. // end catch_exception_translator_registry.h
  5139. #ifdef __OBJC__
  5140. #import "Foundation/Foundation.h"
  5141. #endif
  5142. namespace Catch {
  5143. ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {
  5144. }
  5145. void ExceptionTranslatorRegistry::registerTranslator( const IExceptionTranslator* translator ) {
  5146. m_translators.push_back( std::unique_ptr<const IExceptionTranslator>( translator ) );
  5147. }
  5148. std::string ExceptionTranslatorRegistry::translateActiveException() const {
  5149. try {
  5150. #ifdef __OBJC__
  5151. // In Objective-C try objective-c exceptions first
  5152. @try {
  5153. return tryTranslators();
  5154. }
  5155. @catch (NSException *exception) {
  5156. return Catch::Detail::stringify( [exception description] );
  5157. }
  5158. #else
  5159. return tryTranslators();
  5160. #endif
  5161. }
  5162. catch( TestFailureException& ) {
  5163. std::rethrow_exception(std::current_exception());
  5164. }
  5165. catch( std::exception& ex ) {
  5166. return ex.what();
  5167. }
  5168. catch( std::string& msg ) {
  5169. return msg;
  5170. }
  5171. catch( const char* msg ) {
  5172. return msg;
  5173. }
  5174. catch(...) {
  5175. return "Unknown exception";
  5176. }
  5177. }
  5178. std::string ExceptionTranslatorRegistry::tryTranslators() const {
  5179. if( m_translators.empty() )
  5180. std::rethrow_exception(std::current_exception());
  5181. else
  5182. return m_translators[0]->translate( m_translators.begin()+1, m_translators.end() );
  5183. }
  5184. }
  5185. // end catch_exception_translator_registry.cpp
  5186. // start catch_fatal_condition.cpp
  5187. // start catch_fatal_condition.h
  5188. #include <string>
  5189. #if defined ( CATCH_PLATFORM_WINDOWS ) /////////////////////////////////////////
  5190. # if !defined ( CATCH_CONFIG_WINDOWS_SEH )
  5191. namespace Catch {
  5192. struct FatalConditionHandler {
  5193. void reset();
  5194. };
  5195. }
  5196. # else // CATCH_CONFIG_WINDOWS_SEH is defined
  5197. namespace Catch {
  5198. struct FatalConditionHandler {
  5199. static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo);
  5200. FatalConditionHandler();
  5201. static void reset();
  5202. ~FatalConditionHandler();
  5203. private:
  5204. static bool isSet;
  5205. static ULONG guaranteeSize;
  5206. static PVOID exceptionHandlerHandle;
  5207. };
  5208. } // namespace Catch
  5209. # endif // CATCH_CONFIG_WINDOWS_SEH
  5210. #else // Not Windows - assumed to be POSIX compatible //////////////////////////
  5211. # if !defined(CATCH_CONFIG_POSIX_SIGNALS)
  5212. namespace Catch {
  5213. struct FatalConditionHandler {
  5214. void reset();
  5215. };
  5216. }
  5217. # else // CATCH_CONFIG_POSIX_SIGNALS is defined
  5218. #include <signal.h>
  5219. namespace Catch {
  5220. struct FatalConditionHandler {
  5221. static bool isSet;
  5222. static struct sigaction oldSigActions[];// [sizeof(signalDefs) / sizeof(SignalDefs)];
  5223. static stack_t oldSigStack;
  5224. static char altStackMem[];
  5225. static void handleSignal( int sig );
  5226. FatalConditionHandler();
  5227. ~FatalConditionHandler();
  5228. static void reset();
  5229. };
  5230. } // namespace Catch
  5231. # endif // CATCH_CONFIG_POSIX_SIGNALS
  5232. #endif // not Windows
  5233. // end catch_fatal_condition.h
  5234. namespace {
  5235. // Report the error condition
  5236. void reportFatal( char const * const message ) {
  5237. Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition( message );
  5238. }
  5239. }
  5240. #if defined ( CATCH_PLATFORM_WINDOWS ) /////////////////////////////////////////
  5241. # if !defined ( CATCH_CONFIG_WINDOWS_SEH )
  5242. namespace Catch {
  5243. void FatalConditionHandler::reset() {}
  5244. }
  5245. # else // CATCH_CONFIG_WINDOWS_SEH is defined
  5246. namespace Catch {
  5247. struct SignalDefs { DWORD id; const char* name; };
  5248. // There is no 1-1 mapping between signals and windows exceptions.
  5249. // Windows can easily distinguish between SO and SigSegV,
  5250. // but SigInt, SigTerm, etc are handled differently.
  5251. static SignalDefs signalDefs[] = {
  5252. { EXCEPTION_ILLEGAL_INSTRUCTION, "SIGILL - Illegal instruction signal" },
  5253. { EXCEPTION_STACK_OVERFLOW, "SIGSEGV - Stack overflow" },
  5254. { EXCEPTION_ACCESS_VIOLATION, "SIGSEGV - Segmentation violation signal" },
  5255. { EXCEPTION_INT_DIVIDE_BY_ZERO, "Divide by zero error" },
  5256. };
  5257. LONG CALLBACK FatalConditionHandler::handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {
  5258. for (auto const& def : signalDefs) {
  5259. if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) {
  5260. reportFatal(def.name);
  5261. }
  5262. }
  5263. // If its not an exception we care about, pass it along.
  5264. // This stops us from eating debugger breaks etc.
  5265. return EXCEPTION_CONTINUE_SEARCH;
  5266. }
  5267. FatalConditionHandler::FatalConditionHandler() {
  5268. isSet = true;
  5269. // 32k seems enough for Catch to handle stack overflow,
  5270. // but the value was found experimentally, so there is no strong guarantee
  5271. guaranteeSize = 32 * 1024;
  5272. exceptionHandlerHandle = nullptr;
  5273. // Register as first handler in current chain
  5274. exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);
  5275. // Pass in guarantee size to be filled
  5276. SetThreadStackGuarantee(&guaranteeSize);
  5277. }
  5278. void FatalConditionHandler::reset() {
  5279. if (isSet) {
  5280. // Unregister handler and restore the old guarantee
  5281. RemoveVectoredExceptionHandler(exceptionHandlerHandle);
  5282. SetThreadStackGuarantee(&guaranteeSize);
  5283. exceptionHandlerHandle = nullptr;
  5284. isSet = false;
  5285. }
  5286. }
  5287. FatalConditionHandler::~FatalConditionHandler() {
  5288. reset();
  5289. }
  5290. bool FatalConditionHandler::isSet = false;
  5291. ULONG FatalConditionHandler::guaranteeSize = 0;
  5292. PVOID FatalConditionHandler::exceptionHandlerHandle = nullptr;
  5293. } // namespace Catch
  5294. # endif // CATCH_CONFIG_WINDOWS_SEH
  5295. #else // Not Windows - assumed to be POSIX compatible //////////////////////////
  5296. # if !defined(CATCH_CONFIG_POSIX_SIGNALS)
  5297. namespace Catch {
  5298. void FatalConditionHandler::reset() {}
  5299. }
  5300. # else // CATCH_CONFIG_POSIX_SIGNALS is defined
  5301. #include <signal.h>
  5302. namespace Catch {
  5303. struct SignalDefs {
  5304. int id;
  5305. const char* name;
  5306. };
  5307. static SignalDefs signalDefs[] = {
  5308. { SIGINT, "SIGINT - Terminal interrupt signal" },
  5309. { SIGILL, "SIGILL - Illegal instruction signal" },
  5310. { SIGFPE, "SIGFPE - Floating point error signal" },
  5311. { SIGSEGV, "SIGSEGV - Segmentation violation signal" },
  5312. { SIGTERM, "SIGTERM - Termination request signal" },
  5313. { SIGABRT, "SIGABRT - Abort (abnormal termination) signal" }
  5314. };
  5315. void FatalConditionHandler::handleSignal( int sig ) {
  5316. char const * name = "<unknown signal>";
  5317. for (auto const& def : signalDefs) {
  5318. if (sig == def.id) {
  5319. name = def.name;
  5320. break;
  5321. }
  5322. }
  5323. reset();
  5324. reportFatal(name);
  5325. raise( sig );
  5326. }
  5327. FatalConditionHandler::FatalConditionHandler() {
  5328. isSet = true;
  5329. stack_t sigStack;
  5330. sigStack.ss_sp = altStackMem;
  5331. sigStack.ss_size = SIGSTKSZ;
  5332. sigStack.ss_flags = 0;
  5333. sigaltstack(&sigStack, &oldSigStack);
  5334. struct sigaction sa = { };
  5335. sa.sa_handler = handleSignal;
  5336. sa.sa_flags = SA_ONSTACK;
  5337. for (std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i) {
  5338. sigaction(signalDefs[i].id, &sa, &oldSigActions[i]);
  5339. }
  5340. }
  5341. FatalConditionHandler::~FatalConditionHandler() {
  5342. reset();
  5343. }
  5344. void FatalConditionHandler::reset() {
  5345. if( isSet ) {
  5346. // Set signals back to previous values -- hopefully nobody overwrote them in the meantime
  5347. for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) {
  5348. sigaction(signalDefs[i].id, &oldSigActions[i], nullptr);
  5349. }
  5350. // Return the old stack
  5351. sigaltstack(&oldSigStack, nullptr);
  5352. isSet = false;
  5353. }
  5354. }
  5355. bool FatalConditionHandler::isSet = false;
  5356. struct sigaction FatalConditionHandler::oldSigActions[sizeof(signalDefs)/sizeof(SignalDefs)] = {};
  5357. stack_t FatalConditionHandler::oldSigStack = {};
  5358. char FatalConditionHandler::altStackMem[SIGSTKSZ] = {};
  5359. } // namespace Catch
  5360. # endif // CATCH_CONFIG_POSIX_SIGNALS
  5361. #endif // not Windows
  5362. // end catch_fatal_condition.cpp
  5363. // start catch_interfaces_capture.cpp
  5364. namespace Catch {
  5365. IResultCapture::~IResultCapture() = default;
  5366. }
  5367. // end catch_interfaces_capture.cpp
  5368. // start catch_interfaces_config.cpp
  5369. namespace Catch {
  5370. IConfig::~IConfig() = default;
  5371. }
  5372. // end catch_interfaces_config.cpp
  5373. // start catch_interfaces_exception.cpp
  5374. namespace Catch {
  5375. IExceptionTranslator::~IExceptionTranslator() = default;
  5376. IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() = default;
  5377. }
  5378. // end catch_interfaces_exception.cpp
  5379. // start catch_interfaces_registry_hub.cpp
  5380. namespace Catch {
  5381. IRegistryHub::~IRegistryHub() = default;
  5382. IMutableRegistryHub::~IMutableRegistryHub() = default;
  5383. }
  5384. // end catch_interfaces_registry_hub.cpp
  5385. // start catch_interfaces_reporter.cpp
  5386. // start catch_reporter_multi.h
  5387. namespace Catch {
  5388. class MultipleReporters : public IStreamingReporter {
  5389. using Reporters = std::vector<IStreamingReporterPtr>;
  5390. Reporters m_reporters;
  5391. public:
  5392. void add( IStreamingReporterPtr&& reporter );
  5393. public: // IStreamingReporter
  5394. ReporterPreferences getPreferences() const override;
  5395. void noMatchingTestCases( std::string const& spec ) override;
  5396. static std::set<Verbosity> getSupportedVerbosities();
  5397. void benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) override;
  5398. void benchmarkEnded( BenchmarkStats const& benchmarkStats ) override;
  5399. void testRunStarting( TestRunInfo const& testRunInfo ) override;
  5400. void testGroupStarting( GroupInfo const& groupInfo ) override;
  5401. void testCaseStarting( TestCaseInfo const& testInfo ) override;
  5402. void sectionStarting( SectionInfo const& sectionInfo ) override;
  5403. void assertionStarting( AssertionInfo const& assertionInfo ) override;
  5404. // The return value indicates if the messages buffer should be cleared:
  5405. bool assertionEnded( AssertionStats const& assertionStats ) override;
  5406. void sectionEnded( SectionStats const& sectionStats ) override;
  5407. void testCaseEnded( TestCaseStats const& testCaseStats ) override;
  5408. void testGroupEnded( TestGroupStats const& testGroupStats ) override;
  5409. void testRunEnded( TestRunStats const& testRunStats ) override;
  5410. void skipTest( TestCaseInfo const& testInfo ) override;
  5411. bool isMulti() const override;
  5412. };
  5413. } // end namespace Catch
  5414. // end catch_reporter_multi.h
  5415. namespace Catch {
  5416. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig )
  5417. : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {}
  5418. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream )
  5419. : m_stream( &_stream ), m_fullConfig( _fullConfig ) {}
  5420. std::ostream& ReporterConfig::stream() const { return *m_stream; }
  5421. IConfigPtr ReporterConfig::fullConfig() const { return m_fullConfig; }
  5422. TestRunInfo::TestRunInfo( std::string const& _name ) : name( _name ) {}
  5423. GroupInfo::GroupInfo( std::string const& _name,
  5424. std::size_t _groupIndex,
  5425. std::size_t _groupsCount )
  5426. : name( _name ),
  5427. groupIndex( _groupIndex ),
  5428. groupsCounts( _groupsCount )
  5429. {}
  5430. AssertionStats::AssertionStats( AssertionResult const& _assertionResult,
  5431. std::vector<MessageInfo> const& _infoMessages,
  5432. Totals const& _totals )
  5433. : assertionResult( _assertionResult ),
  5434. infoMessages( _infoMessages ),
  5435. totals( _totals )
  5436. {
  5437. assertionResult.m_resultData.lazyExpression.m_transientExpression = _assertionResult.m_resultData.lazyExpression.m_transientExpression;
  5438. if( assertionResult.hasMessage() ) {
  5439. // Copy message into messages list.
  5440. // !TBD This should have been done earlier, somewhere
  5441. MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() );
  5442. builder << assertionResult.getMessage();
  5443. builder.m_info.message = builder.m_stream.str();
  5444. infoMessages.push_back( builder.m_info );
  5445. }
  5446. }
  5447. AssertionStats::~AssertionStats() = default;
  5448. SectionStats::SectionStats( SectionInfo const& _sectionInfo,
  5449. Counts const& _assertions,
  5450. double _durationInSeconds,
  5451. bool _missingAssertions )
  5452. : sectionInfo( _sectionInfo ),
  5453. assertions( _assertions ),
  5454. durationInSeconds( _durationInSeconds ),
  5455. missingAssertions( _missingAssertions )
  5456. {}
  5457. SectionStats::~SectionStats() = default;
  5458. TestCaseStats::TestCaseStats( TestCaseInfo const& _testInfo,
  5459. Totals const& _totals,
  5460. std::string const& _stdOut,
  5461. std::string const& _stdErr,
  5462. bool _aborting )
  5463. : testInfo( _testInfo ),
  5464. totals( _totals ),
  5465. stdOut( _stdOut ),
  5466. stdErr( _stdErr ),
  5467. aborting( _aborting )
  5468. {}
  5469. TestCaseStats::~TestCaseStats() = default;
  5470. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo,
  5471. Totals const& _totals,
  5472. bool _aborting )
  5473. : groupInfo( _groupInfo ),
  5474. totals( _totals ),
  5475. aborting( _aborting )
  5476. {}
  5477. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo )
  5478. : groupInfo( _groupInfo ),
  5479. aborting( false )
  5480. {}
  5481. TestGroupStats::~TestGroupStats() = default;
  5482. TestRunStats::TestRunStats( TestRunInfo const& _runInfo,
  5483. Totals const& _totals,
  5484. bool _aborting )
  5485. : runInfo( _runInfo ),
  5486. totals( _totals ),
  5487. aborting( _aborting )
  5488. {}
  5489. TestRunStats::~TestRunStats() = default;
  5490. void IStreamingReporter::fatalErrorEncountered( StringRef ) {}
  5491. bool IStreamingReporter::isMulti() const { return false; }
  5492. IReporterFactory::~IReporterFactory() = default;
  5493. IReporterRegistry::~IReporterRegistry() = default;
  5494. void addReporter( IStreamingReporterPtr& existingReporter, IStreamingReporterPtr&& additionalReporter ) {
  5495. if( !existingReporter ) {
  5496. existingReporter = std::move( additionalReporter );
  5497. return;
  5498. }
  5499. MultipleReporters* multi = nullptr;
  5500. if( existingReporter->isMulti() ) {
  5501. multi = static_cast<MultipleReporters*>( existingReporter.get() );
  5502. }
  5503. else {
  5504. auto newMulti = std::unique_ptr<MultipleReporters>( new MultipleReporters );
  5505. newMulti->add( std::move( existingReporter ) );
  5506. multi = newMulti.get();
  5507. existingReporter = std::move( newMulti );
  5508. }
  5509. multi->add( std::move( additionalReporter ) );
  5510. }
  5511. } // end namespace Catch
  5512. // end catch_interfaces_reporter.cpp
  5513. // start catch_interfaces_runner.cpp
  5514. namespace Catch {
  5515. IRunner::~IRunner() = default;
  5516. }
  5517. // end catch_interfaces_runner.cpp
  5518. // start catch_interfaces_testcase.cpp
  5519. namespace Catch {
  5520. ITestInvoker::~ITestInvoker() = default;
  5521. ITestCaseRegistry::~ITestCaseRegistry() = default;
  5522. }
  5523. // end catch_interfaces_testcase.cpp
  5524. // start catch_leak_detector.cpp
  5525. namespace Catch {
  5526. #ifdef CATCH_CONFIG_WINDOWS_CRTDBG
  5527. #include <crtdbg.h>
  5528. LeakDetector::LeakDetector() {
  5529. int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
  5530. flag |= _CRTDBG_LEAK_CHECK_DF;
  5531. flag |= _CRTDBG_ALLOC_MEM_DF;
  5532. _CrtSetDbgFlag(flag);
  5533. _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
  5534. _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
  5535. // Change this to leaking allocation's number to break there
  5536. _CrtSetBreakAlloc(-1);
  5537. }
  5538. #else
  5539. LeakDetector::LeakDetector(){}
  5540. #endif
  5541. }
  5542. // end catch_leak_detector.cpp
  5543. // start catch_list.cpp
  5544. // start catch_list.h
  5545. #include <set>
  5546. namespace Catch {
  5547. std::size_t listTests( Config const& config );
  5548. std::size_t listTestsNamesOnly( Config const& config );
  5549. struct TagInfo {
  5550. void add( std::string const& spelling );
  5551. std::string all() const;
  5552. std::set<std::string> spellings;
  5553. std::size_t count = 0;
  5554. };
  5555. std::size_t listTags( Config const& config );
  5556. std::size_t listReporters( Config const& /*config*/ );
  5557. Option<std::size_t> list( Config const& config );
  5558. } // end namespace Catch
  5559. // end catch_list.h
  5560. // start catch_text.h
  5561. namespace Catch {
  5562. using namespace clara::TextFlow;
  5563. }
  5564. // end catch_text.h
  5565. #include <limits>
  5566. #include <algorithm>
  5567. #include <iomanip>
  5568. namespace Catch {
  5569. std::size_t listTests( Config const& config ) {
  5570. TestSpec testSpec = config.testSpec();
  5571. if( config.testSpec().hasFilters() )
  5572. Catch::cout() << "Matching test cases:\n";
  5573. else {
  5574. Catch::cout() << "All available test cases:\n";
  5575. testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( "*" ).testSpec();
  5576. }
  5577. auto matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  5578. for( auto const& testCaseInfo : matchedTestCases ) {
  5579. Colour::Code colour = testCaseInfo.isHidden()
  5580. ? Colour::SecondaryText
  5581. : Colour::None;
  5582. Colour colourGuard( colour );
  5583. Catch::cout() << Column( testCaseInfo.name ).initialIndent( 2 ).indent( 4 ) << "\n";
  5584. if( config.verbosity() >= Verbosity::High ) {
  5585. Catch::cout() << Column( Catch::Detail::stringify( testCaseInfo.lineInfo ) ).indent(4) << std::endl;
  5586. std::string description = testCaseInfo.description;
  5587. if( description.empty() )
  5588. description = "(NO DESCRIPTION)";
  5589. Catch::cout() << Column( description ).indent(4) << std::endl;
  5590. }
  5591. if( !testCaseInfo.tags.empty() )
  5592. Catch::cout() << Column( testCaseInfo.tagsAsString() ).indent( 6 ) << "\n";
  5593. }
  5594. if( !config.testSpec().hasFilters() )
  5595. Catch::cout() << pluralise( matchedTestCases.size(), "test case" ) << '\n' << std::endl;
  5596. else
  5597. Catch::cout() << pluralise( matchedTestCases.size(), "matching test case" ) << '\n' << std::endl;
  5598. return matchedTestCases.size();
  5599. }
  5600. std::size_t listTestsNamesOnly( Config const& config ) {
  5601. TestSpec testSpec = config.testSpec();
  5602. if( !config.testSpec().hasFilters() )
  5603. testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( "*" ).testSpec();
  5604. std::size_t matchedTests = 0;
  5605. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  5606. for( auto const& testCaseInfo : matchedTestCases ) {
  5607. matchedTests++;
  5608. if( startsWith( testCaseInfo.name, '#' ) )
  5609. Catch::cout() << '"' << testCaseInfo.name << '"';
  5610. else
  5611. Catch::cout() << testCaseInfo.name;
  5612. if ( config.verbosity() >= Verbosity::High )
  5613. Catch::cout() << "\t@" << testCaseInfo.lineInfo;
  5614. Catch::cout() << std::endl;
  5615. }
  5616. return matchedTests;
  5617. }
  5618. void TagInfo::add( std::string const& spelling ) {
  5619. ++count;
  5620. spellings.insert( spelling );
  5621. }
  5622. std::string TagInfo::all() const {
  5623. std::string out;
  5624. for( auto const& spelling : spellings )
  5625. out += "[" + spelling + "]";
  5626. return out;
  5627. }
  5628. std::size_t listTags( Config const& config ) {
  5629. TestSpec testSpec = config.testSpec();
  5630. if( config.testSpec().hasFilters() )
  5631. Catch::cout() << "Tags for matching test cases:\n";
  5632. else {
  5633. Catch::cout() << "All available tags:\n";
  5634. testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( "*" ).testSpec();
  5635. }
  5636. std::map<std::string, TagInfo> tagCounts;
  5637. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  5638. for( auto const& testCase : matchedTestCases ) {
  5639. for( auto const& tagName : testCase.getTestCaseInfo().tags ) {
  5640. std::string lcaseTagName = toLower( tagName );
  5641. auto countIt = tagCounts.find( lcaseTagName );
  5642. if( countIt == tagCounts.end() )
  5643. countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first;
  5644. countIt->second.add( tagName );
  5645. }
  5646. }
  5647. for( auto const& tagCount : tagCounts ) {
  5648. std::ostringstream oss;
  5649. oss << " " << std::setw(2) << tagCount.second.count << " ";
  5650. auto wrapper = Column( tagCount.second.all() )
  5651. .initialIndent( 0 )
  5652. .indent( oss.str().size() )
  5653. .width( CATCH_CONFIG_CONSOLE_WIDTH-10 );
  5654. Catch::cout() << oss.str() << wrapper << '\n';
  5655. }
  5656. Catch::cout() << pluralise( tagCounts.size(), "tag" ) << '\n' << std::endl;
  5657. return tagCounts.size();
  5658. }
  5659. std::size_t listReporters( Config const& /*config*/ ) {
  5660. Catch::cout() << "Available reporters:\n";
  5661. IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
  5662. std::size_t maxNameLen = 0;
  5663. for( auto const& factoryKvp : factories )
  5664. maxNameLen = (std::max)( maxNameLen, factoryKvp.first.size() );
  5665. for( auto const& factoryKvp : factories ) {
  5666. Catch::cout()
  5667. << Column( factoryKvp.first + ":" )
  5668. .indent(2)
  5669. .width( 5+maxNameLen )
  5670. + Column( factoryKvp.second->getDescription() )
  5671. .initialIndent(0)
  5672. .indent(2)
  5673. .width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 )
  5674. << "\n";
  5675. }
  5676. Catch::cout() << std::endl;
  5677. return factories.size();
  5678. }
  5679. Option<std::size_t> list( Config const& config ) {
  5680. Option<std::size_t> listedCount;
  5681. if( config.listTests() )
  5682. listedCount = listedCount.valueOr(0) + listTests( config );
  5683. if( config.listTestNamesOnly() )
  5684. listedCount = listedCount.valueOr(0) + listTestsNamesOnly( config );
  5685. if( config.listTags() )
  5686. listedCount = listedCount.valueOr(0) + listTags( config );
  5687. if( config.listReporters() )
  5688. listedCount = listedCount.valueOr(0) + listReporters( config );
  5689. return listedCount;
  5690. }
  5691. } // end namespace Catch
  5692. // end catch_list.cpp
  5693. // start catch_matchers.cpp
  5694. namespace Catch {
  5695. namespace Matchers {
  5696. namespace Impl {
  5697. std::string MatcherUntypedBase::toString() const {
  5698. if( m_cachedToString.empty() )
  5699. m_cachedToString = describe();
  5700. return m_cachedToString;
  5701. }
  5702. MatcherUntypedBase::~MatcherUntypedBase() = default;
  5703. } // namespace Impl
  5704. } // namespace Matchers
  5705. using namespace Matchers;
  5706. using Matchers::Impl::MatcherBase;
  5707. } // namespace Catch
  5708. // end catch_matchers.cpp
  5709. // start catch_matchers_string.cpp
  5710. namespace Catch {
  5711. namespace Matchers {
  5712. namespace StdString {
  5713. CasedString::CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity )
  5714. : m_caseSensitivity( caseSensitivity ),
  5715. m_str( adjustString( str ) )
  5716. {}
  5717. std::string CasedString::adjustString( std::string const& str ) const {
  5718. return m_caseSensitivity == CaseSensitive::No
  5719. ? toLower( str )
  5720. : str;
  5721. }
  5722. std::string CasedString::caseSensitivitySuffix() const {
  5723. return m_caseSensitivity == CaseSensitive::No
  5724. ? " (case insensitive)"
  5725. : std::string();
  5726. }
  5727. StringMatcherBase::StringMatcherBase( std::string const& operation, CasedString const& comparator )
  5728. : m_comparator( comparator ),
  5729. m_operation( operation ) {
  5730. }
  5731. std::string StringMatcherBase::describe() const {
  5732. std::string description;
  5733. description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
  5734. m_comparator.caseSensitivitySuffix().size());
  5735. description += m_operation;
  5736. description += ": \"";
  5737. description += m_comparator.m_str;
  5738. description += "\"";
  5739. description += m_comparator.caseSensitivitySuffix();
  5740. return description;
  5741. }
  5742. EqualsMatcher::EqualsMatcher( CasedString const& comparator ) : StringMatcherBase( "equals", comparator ) {}
  5743. bool EqualsMatcher::match( std::string const& source ) const {
  5744. return m_comparator.adjustString( source ) == m_comparator.m_str;
  5745. }
  5746. ContainsMatcher::ContainsMatcher( CasedString const& comparator ) : StringMatcherBase( "contains", comparator ) {}
  5747. bool ContainsMatcher::match( std::string const& source ) const {
  5748. return contains( m_comparator.adjustString( source ), m_comparator.m_str );
  5749. }
  5750. StartsWithMatcher::StartsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "starts with", comparator ) {}
  5751. bool StartsWithMatcher::match( std::string const& source ) const {
  5752. return startsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  5753. }
  5754. EndsWithMatcher::EndsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "ends with", comparator ) {}
  5755. bool EndsWithMatcher::match( std::string const& source ) const {
  5756. return endsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  5757. }
  5758. } // namespace StdString
  5759. StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  5760. return StdString::EqualsMatcher( StdString::CasedString( str, caseSensitivity) );
  5761. }
  5762. StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  5763. return StdString::ContainsMatcher( StdString::CasedString( str, caseSensitivity) );
  5764. }
  5765. StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  5766. return StdString::EndsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  5767. }
  5768. StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  5769. return StdString::StartsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  5770. }
  5771. } // namespace Matchers
  5772. } // namespace Catch
  5773. // end catch_matchers_string.cpp
  5774. // start catch_message.cpp
  5775. namespace Catch {
  5776. MessageInfo::MessageInfo( std::string const& _macroName,
  5777. SourceLineInfo const& _lineInfo,
  5778. ResultWas::OfType _type )
  5779. : macroName( _macroName ),
  5780. lineInfo( _lineInfo ),
  5781. type( _type ),
  5782. sequence( ++globalCount )
  5783. {}
  5784. bool MessageInfo::operator==( MessageInfo const& other ) const {
  5785. return sequence == other.sequence;
  5786. }
  5787. bool MessageInfo::operator<( MessageInfo const& other ) const {
  5788. return sequence < other.sequence;
  5789. }
  5790. // This may need protecting if threading support is added
  5791. unsigned int MessageInfo::globalCount = 0;
  5792. ////////////////////////////////////////////////////////////////////////////
  5793. Catch::MessageBuilder::MessageBuilder( std::string const& macroName,
  5794. SourceLineInfo const& lineInfo,
  5795. ResultWas::OfType type )
  5796. :m_info(macroName, lineInfo, type) {}
  5797. ////////////////////////////////////////////////////////////////////////////
  5798. ScopedMessage::ScopedMessage( MessageBuilder const& builder )
  5799. : m_info( builder.m_info )
  5800. {
  5801. m_info.message = builder.m_stream.str();
  5802. getResultCapture().pushScopedMessage( m_info );
  5803. }
  5804. ScopedMessage::~ScopedMessage() {
  5805. if ( !std::uncaught_exception() ){
  5806. getResultCapture().popScopedMessage(m_info);
  5807. }
  5808. }
  5809. } // end namespace Catch
  5810. // end catch_message.cpp
  5811. // start catch_random_number_generator.cpp
  5812. // start catch_random_number_generator.h
  5813. #include <algorithm>
  5814. namespace Catch {
  5815. struct IConfig;
  5816. void seedRng( IConfig const& config );
  5817. unsigned int rngSeed();
  5818. struct RandomNumberGenerator {
  5819. using result_type = unsigned int;
  5820. static constexpr result_type (min)() { return 0; }
  5821. static constexpr result_type (max)() { return 1000000; }
  5822. result_type operator()( result_type n ) const;
  5823. result_type operator()() const;
  5824. template<typename V>
  5825. static void shuffle( V& vector ) {
  5826. RandomNumberGenerator rng;
  5827. std::shuffle( vector.begin(), vector.end(), rng );
  5828. }
  5829. };
  5830. }
  5831. // end catch_random_number_generator.h
  5832. #include <cstdlib>
  5833. namespace Catch {
  5834. void seedRng( IConfig const& config ) {
  5835. if( config.rngSeed() != 0 )
  5836. std::srand( config.rngSeed() );
  5837. }
  5838. unsigned int rngSeed() {
  5839. return getCurrentContext().getConfig()->rngSeed();
  5840. }
  5841. RandomNumberGenerator::result_type RandomNumberGenerator::operator()( result_type n ) const {
  5842. return std::rand() % n;
  5843. }
  5844. RandomNumberGenerator::result_type RandomNumberGenerator::operator()() const {
  5845. return std::rand() % (max)();
  5846. }
  5847. }
  5848. // end catch_random_number_generator.cpp
  5849. // start catch_registry_hub.cpp
  5850. // start catch_test_case_registry_impl.h
  5851. #include <vector>
  5852. #include <set>
  5853. #include <algorithm>
  5854. #include <ios>
  5855. namespace Catch {
  5856. class TestCase;
  5857. struct IConfig;
  5858. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases );
  5859. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
  5860. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions );
  5861. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
  5862. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
  5863. class TestRegistry : public ITestCaseRegistry {
  5864. public:
  5865. virtual ~TestRegistry() = default;
  5866. virtual void registerTest( TestCase const& testCase );
  5867. std::vector<TestCase> const& getAllTests() const override;
  5868. std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const override;
  5869. private:
  5870. std::vector<TestCase> m_functions;
  5871. mutable RunTests::InWhatOrder m_currentSortOrder = RunTests::InDeclarationOrder;
  5872. mutable std::vector<TestCase> m_sortedFunctions;
  5873. std::size_t m_unnamedCount = 0;
  5874. std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised
  5875. };
  5876. ///////////////////////////////////////////////////////////////////////////
  5877. class TestInvokerAsFunction : public ITestInvoker {
  5878. void(*m_testAsFunction)();
  5879. public:
  5880. TestInvokerAsFunction( void(*testAsFunction)() ) noexcept;
  5881. void invoke() const override;
  5882. };
  5883. std::string extractClassName( std::string const& classOrQualifiedMethodName );
  5884. ///////////////////////////////////////////////////////////////////////////
  5885. } // end namespace Catch
  5886. // end catch_test_case_registry_impl.h
  5887. // start catch_reporter_registry.h
  5888. #include <map>
  5889. namespace Catch {
  5890. class ReporterRegistry : public IReporterRegistry {
  5891. public:
  5892. ~ReporterRegistry() override;
  5893. IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const override;
  5894. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory );
  5895. void registerListener( IReporterFactoryPtr const& factory );
  5896. FactoryMap const& getFactories() const override;
  5897. Listeners const& getListeners() const override;
  5898. private:
  5899. FactoryMap m_factories;
  5900. Listeners m_listeners;
  5901. };
  5902. }
  5903. // end catch_reporter_registry.h
  5904. // start catch_tag_alias_registry.h
  5905. // start catch_tag_alias.h
  5906. #include <string>
  5907. namespace Catch {
  5908. struct TagAlias {
  5909. TagAlias(std::string const& _tag, SourceLineInfo _lineInfo);
  5910. std::string tag;
  5911. SourceLineInfo lineInfo;
  5912. };
  5913. } // end namespace Catch
  5914. // end catch_tag_alias.h
  5915. #include <map>
  5916. namespace Catch {
  5917. class TagAliasRegistry : public ITagAliasRegistry {
  5918. public:
  5919. ~TagAliasRegistry() override;
  5920. TagAlias const* find( std::string const& alias ) const override;
  5921. std::string expandAliases( std::string const& unexpandedTestSpec ) const override;
  5922. void add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo );
  5923. private:
  5924. std::map<std::string, TagAlias> m_registry;
  5925. };
  5926. } // end namespace Catch
  5927. // end catch_tag_alias_registry.h
  5928. // start catch_startup_exception_registry.h
  5929. #include <vector>
  5930. #include <exception>
  5931. namespace Catch {
  5932. class StartupExceptionRegistry {
  5933. public:
  5934. void add(std::exception_ptr const& exception) noexcept;
  5935. std::vector<std::exception_ptr> const& getExceptions() const noexcept;
  5936. private:
  5937. std::vector<std::exception_ptr> m_exceptions;
  5938. };
  5939. } // end namespace Catch
  5940. // end catch_startup_exception_registry.h
  5941. namespace Catch {
  5942. namespace {
  5943. class RegistryHub : public IRegistryHub, public IMutableRegistryHub,
  5944. private NonCopyable {
  5945. public: // IRegistryHub
  5946. RegistryHub() = default;
  5947. IReporterRegistry const& getReporterRegistry() const override {
  5948. return m_reporterRegistry;
  5949. }
  5950. ITestCaseRegistry const& getTestCaseRegistry() const override {
  5951. return m_testCaseRegistry;
  5952. }
  5953. IExceptionTranslatorRegistry& getExceptionTranslatorRegistry() override {
  5954. return m_exceptionTranslatorRegistry;
  5955. }
  5956. ITagAliasRegistry const& getTagAliasRegistry() const override {
  5957. return m_tagAliasRegistry;
  5958. }
  5959. StartupExceptionRegistry const& getStartupExceptionRegistry() const override {
  5960. return m_exceptionRegistry;
  5961. }
  5962. public: // IMutableRegistryHub
  5963. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) override {
  5964. m_reporterRegistry.registerReporter( name, factory );
  5965. }
  5966. void registerListener( IReporterFactoryPtr const& factory ) override {
  5967. m_reporterRegistry.registerListener( factory );
  5968. }
  5969. void registerTest( TestCase const& testInfo ) override {
  5970. m_testCaseRegistry.registerTest( testInfo );
  5971. }
  5972. void registerTranslator( const IExceptionTranslator* translator ) override {
  5973. m_exceptionTranslatorRegistry.registerTranslator( translator );
  5974. }
  5975. void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) override {
  5976. m_tagAliasRegistry.add( alias, tag, lineInfo );
  5977. }
  5978. void registerStartupException() noexcept override {
  5979. m_exceptionRegistry.add(std::current_exception());
  5980. }
  5981. private:
  5982. TestRegistry m_testCaseRegistry;
  5983. ReporterRegistry m_reporterRegistry;
  5984. ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
  5985. TagAliasRegistry m_tagAliasRegistry;
  5986. StartupExceptionRegistry m_exceptionRegistry;
  5987. };
  5988. // Single, global, instance
  5989. RegistryHub*& getTheRegistryHub() {
  5990. static RegistryHub* theRegistryHub = nullptr;
  5991. if( !theRegistryHub )
  5992. theRegistryHub = new RegistryHub();
  5993. return theRegistryHub;
  5994. }
  5995. }
  5996. IRegistryHub& getRegistryHub() {
  5997. return *getTheRegistryHub();
  5998. }
  5999. IMutableRegistryHub& getMutableRegistryHub() {
  6000. return *getTheRegistryHub();
  6001. }
  6002. void cleanUp() {
  6003. delete getTheRegistryHub();
  6004. getTheRegistryHub() = nullptr;
  6005. cleanUpContext();
  6006. }
  6007. std::string translateActiveException() {
  6008. return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException();
  6009. }
  6010. } // end namespace Catch
  6011. // end catch_registry_hub.cpp
  6012. // start catch_reporter_registry.cpp
  6013. namespace Catch {
  6014. ReporterRegistry::~ReporterRegistry() = default;
  6015. IStreamingReporterPtr ReporterRegistry::create( std::string const& name, IConfigPtr const& config ) const {
  6016. auto it = m_factories.find( name );
  6017. if( it == m_factories.end() )
  6018. return nullptr;
  6019. return it->second->create( ReporterConfig( config ) );
  6020. }
  6021. void ReporterRegistry::registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) {
  6022. m_factories.emplace(name, factory);
  6023. }
  6024. void ReporterRegistry::registerListener( IReporterFactoryPtr const& factory ) {
  6025. m_listeners.push_back( factory );
  6026. }
  6027. IReporterRegistry::FactoryMap const& ReporterRegistry::getFactories() const {
  6028. return m_factories;
  6029. }
  6030. IReporterRegistry::Listeners const& ReporterRegistry::getListeners() const {
  6031. return m_listeners;
  6032. }
  6033. }
  6034. // end catch_reporter_registry.cpp
  6035. // start catch_result_type.cpp
  6036. namespace Catch {
  6037. bool isOk( ResultWas::OfType resultType ) {
  6038. return ( resultType & ResultWas::FailureBit ) == 0;
  6039. }
  6040. bool isJustInfo( int flags ) {
  6041. return flags == ResultWas::Info;
  6042. }
  6043. ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) {
  6044. return static_cast<ResultDisposition::Flags>( static_cast<int>( lhs ) | static_cast<int>( rhs ) );
  6045. }
  6046. bool shouldContinueOnFailure( int flags ) { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; }
  6047. bool isFalseTest( int flags ) { return ( flags & ResultDisposition::FalseTest ) != 0; }
  6048. bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; }
  6049. } // end namespace Catch
  6050. // end catch_result_type.cpp
  6051. // start catch_run_context.cpp
  6052. // start catch_run_context.h
  6053. #include <string>
  6054. namespace Catch {
  6055. struct IMutableContext;
  6056. class StreamRedirect {
  6057. public:
  6058. StreamRedirect(std::ostream& stream, std::string& targetString);
  6059. ~StreamRedirect();
  6060. private:
  6061. std::ostream& m_stream;
  6062. std::streambuf* m_prevBuf;
  6063. std::ostringstream m_oss;
  6064. std::string& m_targetString;
  6065. };
  6066. // StdErr has two constituent streams in C++, std::cerr and std::clog
  6067. // This means that we need to redirect 2 streams into 1 to keep proper
  6068. // order of writes and cannot use StreamRedirect on its own
  6069. class StdErrRedirect {
  6070. public:
  6071. StdErrRedirect(std::string& targetString);
  6072. ~StdErrRedirect();
  6073. private:
  6074. std::streambuf* m_cerrBuf;
  6075. std::streambuf* m_clogBuf;
  6076. std::ostringstream m_oss;
  6077. std::string& m_targetString;
  6078. };
  6079. ///////////////////////////////////////////////////////////////////////////
  6080. class RunContext : public IResultCapture, public IRunner {
  6081. public:
  6082. RunContext( RunContext const& ) = delete;
  6083. RunContext& operator =( RunContext const& ) = delete;
  6084. explicit RunContext(IConfigPtr const& _config, IStreamingReporterPtr&& reporter);
  6085. virtual ~RunContext();
  6086. void testGroupStarting(std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount);
  6087. void testGroupEnded(std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount);
  6088. Totals runTest(TestCase const& testCase);
  6089. IConfigPtr config() const;
  6090. IStreamingReporter& reporter() const;
  6091. private: // IResultCapture
  6092. void assertionStarting(AssertionInfo const& info) override;
  6093. void assertionEnded(AssertionResult const& result) override;
  6094. bool sectionStarted( SectionInfo const& sectionInfo, Counts& assertions ) override;
  6095. bool testForMissingAssertions(Counts& assertions);
  6096. void sectionEnded(SectionEndInfo const& endInfo) override;
  6097. void sectionEndedEarly(SectionEndInfo const& endInfo) override;
  6098. void benchmarkStarting( BenchmarkInfo const& info ) override;
  6099. void benchmarkEnded( BenchmarkStats const& stats ) override;
  6100. void pushScopedMessage(MessageInfo const& message) override;
  6101. void popScopedMessage(MessageInfo const& message) override;
  6102. std::string getCurrentTestName() const override;
  6103. const AssertionResult* getLastResult() const override;
  6104. void exceptionEarlyReported() override;
  6105. void handleFatalErrorCondition( StringRef message ) override;
  6106. bool lastAssertionPassed() override;
  6107. void assertionPassed() override;
  6108. void assertionRun() override;
  6109. public:
  6110. // !TBD We need to do this another way!
  6111. bool aborting() const override;
  6112. private:
  6113. void runCurrentTest(std::string& redirectedCout, std::string& redirectedCerr);
  6114. void invokeActiveTestCase();
  6115. private:
  6116. void handleUnfinishedSections();
  6117. TestRunInfo m_runInfo;
  6118. IMutableContext& m_context;
  6119. TestCase const* m_activeTestCase = nullptr;
  6120. ITracker* m_testCaseTracker;
  6121. Option<AssertionResult> m_lastResult;
  6122. IConfigPtr m_config;
  6123. Totals m_totals;
  6124. IStreamingReporterPtr m_reporter;
  6125. std::vector<MessageInfo> m_messages;
  6126. AssertionInfo m_lastAssertionInfo;
  6127. std::vector<SectionEndInfo> m_unfinishedSections;
  6128. std::vector<ITracker*> m_activeSections;
  6129. TrackerContext m_trackerContext;
  6130. std::size_t m_prevPassed = 0;
  6131. bool m_shouldReportUnexpected = true;
  6132. };
  6133. IResultCapture& getResultCapture();
  6134. } // end namespace Catch
  6135. // end catch_run_context.h
  6136. #include <cassert>
  6137. #include <algorithm>
  6138. namespace Catch {
  6139. StreamRedirect::StreamRedirect(std::ostream& stream, std::string& targetString)
  6140. : m_stream(stream),
  6141. m_prevBuf(stream.rdbuf()),
  6142. m_targetString(targetString) {
  6143. stream.rdbuf(m_oss.rdbuf());
  6144. }
  6145. StreamRedirect::~StreamRedirect() {
  6146. m_targetString += m_oss.str();
  6147. m_stream.rdbuf(m_prevBuf);
  6148. }
  6149. StdErrRedirect::StdErrRedirect(std::string & targetString)
  6150. :m_cerrBuf(cerr().rdbuf()), m_clogBuf(clog().rdbuf()),
  6151. m_targetString(targetString) {
  6152. cerr().rdbuf(m_oss.rdbuf());
  6153. clog().rdbuf(m_oss.rdbuf());
  6154. }
  6155. StdErrRedirect::~StdErrRedirect() {
  6156. m_targetString += m_oss.str();
  6157. cerr().rdbuf(m_cerrBuf);
  6158. clog().rdbuf(m_clogBuf);
  6159. }
  6160. RunContext::RunContext(IConfigPtr const& _config, IStreamingReporterPtr&& reporter)
  6161. : m_runInfo(_config->name()),
  6162. m_context(getCurrentMutableContext()),
  6163. m_config(_config),
  6164. m_reporter(std::move(reporter)),
  6165. m_lastAssertionInfo{ "", SourceLineInfo("",0), "", ResultDisposition::Normal }
  6166. {
  6167. m_context.setRunner(this);
  6168. m_context.setConfig(m_config);
  6169. m_context.setResultCapture(this);
  6170. m_reporter->testRunStarting(m_runInfo);
  6171. }
  6172. RunContext::~RunContext() {
  6173. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting()));
  6174. }
  6175. void RunContext::testGroupStarting(std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount) {
  6176. m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount));
  6177. }
  6178. void RunContext::testGroupEnded(std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount) {
  6179. m_reporter->testGroupEnded(TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting()));
  6180. }
  6181. Totals RunContext::runTest(TestCase const& testCase) {
  6182. Totals prevTotals = m_totals;
  6183. std::string redirectedCout;
  6184. std::string redirectedCerr;
  6185. TestCaseInfo testInfo = testCase.getTestCaseInfo();
  6186. m_reporter->testCaseStarting(testInfo);
  6187. m_activeTestCase = &testCase;
  6188. ITracker& rootTracker = m_trackerContext.startRun();
  6189. assert(rootTracker.isSectionTracker());
  6190. static_cast<SectionTracker&>(rootTracker).addInitialFilters(m_config->getSectionsToRun());
  6191. do {
  6192. m_trackerContext.startCycle();
  6193. m_testCaseTracker = &SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo));
  6194. runCurrentTest(redirectedCout, redirectedCerr);
  6195. } while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting());
  6196. Totals deltaTotals = m_totals.delta(prevTotals);
  6197. if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) {
  6198. deltaTotals.assertions.failed++;
  6199. deltaTotals.testCases.passed--;
  6200. deltaTotals.testCases.failed++;
  6201. }
  6202. m_totals.testCases += deltaTotals.testCases;
  6203. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  6204. deltaTotals,
  6205. redirectedCout,
  6206. redirectedCerr,
  6207. aborting()));
  6208. m_activeTestCase = nullptr;
  6209. m_testCaseTracker = nullptr;
  6210. return deltaTotals;
  6211. }
  6212. IConfigPtr RunContext::config() const {
  6213. return m_config;
  6214. }
  6215. IStreamingReporter& RunContext::reporter() const {
  6216. return *m_reporter;
  6217. }
  6218. void RunContext::assertionStarting(AssertionInfo const& info) {
  6219. m_reporter->assertionStarting( info );
  6220. }
  6221. void RunContext::assertionEnded(AssertionResult const & result) {
  6222. if (result.getResultType() == ResultWas::Ok) {
  6223. m_totals.assertions.passed++;
  6224. } else if (!result.isOk()) {
  6225. if( m_activeTestCase->getTestCaseInfo().okToFail() )
  6226. m_totals.assertions.failedButOk++;
  6227. else
  6228. m_totals.assertions.failed++;
  6229. }
  6230. // We have no use for the return value (whether messages should be cleared), because messages were made scoped
  6231. // and should be let to clear themselves out.
  6232. static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals)));
  6233. // Reset working state
  6234. m_lastAssertionInfo = { "", m_lastAssertionInfo.lineInfo, "{Unknown expression after the reported line}", m_lastAssertionInfo.resultDisposition };
  6235. m_lastResult = result;
  6236. }
  6237. bool RunContext::sectionStarted(SectionInfo const & sectionInfo, Counts & assertions) {
  6238. ITracker& sectionTracker = SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(sectionInfo.name, sectionInfo.lineInfo));
  6239. if (!sectionTracker.isOpen())
  6240. return false;
  6241. m_activeSections.push_back(&sectionTracker);
  6242. m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;
  6243. m_reporter->sectionStarting(sectionInfo);
  6244. assertions = m_totals.assertions;
  6245. return true;
  6246. }
  6247. bool RunContext::testForMissingAssertions(Counts& assertions) {
  6248. if (assertions.total() != 0)
  6249. return false;
  6250. if (!m_config->warnAboutMissingAssertions())
  6251. return false;
  6252. if (m_trackerContext.currentTracker().hasChildren())
  6253. return false;
  6254. m_totals.assertions.failed++;
  6255. assertions.failed++;
  6256. return true;
  6257. }
  6258. void RunContext::sectionEnded(SectionEndInfo const & endInfo) {
  6259. Counts assertions = m_totals.assertions - endInfo.prevAssertions;
  6260. bool missingAssertions = testForMissingAssertions(assertions);
  6261. if (!m_activeSections.empty()) {
  6262. m_activeSections.back()->close();
  6263. m_activeSections.pop_back();
  6264. }
  6265. m_reporter->sectionEnded(SectionStats(endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions));
  6266. m_messages.clear();
  6267. }
  6268. void RunContext::sectionEndedEarly(SectionEndInfo const & endInfo) {
  6269. if (m_unfinishedSections.empty())
  6270. m_activeSections.back()->fail();
  6271. else
  6272. m_activeSections.back()->close();
  6273. m_activeSections.pop_back();
  6274. m_unfinishedSections.push_back(endInfo);
  6275. }
  6276. void RunContext::benchmarkStarting( BenchmarkInfo const& info ) {
  6277. m_reporter->benchmarkStarting( info );
  6278. }
  6279. void RunContext::benchmarkEnded( BenchmarkStats const& stats ) {
  6280. m_reporter->benchmarkEnded( stats );
  6281. }
  6282. void RunContext::pushScopedMessage(MessageInfo const & message) {
  6283. m_messages.push_back(message);
  6284. }
  6285. void RunContext::popScopedMessage(MessageInfo const & message) {
  6286. m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end());
  6287. }
  6288. std::string RunContext::getCurrentTestName() const {
  6289. return m_activeTestCase
  6290. ? m_activeTestCase->getTestCaseInfo().name
  6291. : std::string();
  6292. }
  6293. const AssertionResult * RunContext::getLastResult() const {
  6294. return &(*m_lastResult);
  6295. }
  6296. void RunContext::exceptionEarlyReported() {
  6297. m_shouldReportUnexpected = false;
  6298. }
  6299. void RunContext::handleFatalErrorCondition( StringRef message ) {
  6300. // First notify reporter that bad things happened
  6301. m_reporter->fatalErrorEncountered(message);
  6302. // Don't rebuild the result -- the stringification itself can cause more fatal errors
  6303. // Instead, fake a result data.
  6304. AssertionResultData tempResult( ResultWas::FatalErrorCondition, { false } );
  6305. tempResult.message = message;
  6306. AssertionResult result(m_lastAssertionInfo, tempResult);
  6307. getResultCapture().assertionEnded(result);
  6308. handleUnfinishedSections();
  6309. // Recreate section for test case (as we will lose the one that was in scope)
  6310. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  6311. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name, testCaseInfo.description);
  6312. Counts assertions;
  6313. assertions.failed = 1;
  6314. SectionStats testCaseSectionStats(testCaseSection, assertions, 0, false);
  6315. m_reporter->sectionEnded(testCaseSectionStats);
  6316. auto const& testInfo = m_activeTestCase->getTestCaseInfo();
  6317. Totals deltaTotals;
  6318. deltaTotals.testCases.failed = 1;
  6319. deltaTotals.assertions.failed = 1;
  6320. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  6321. deltaTotals,
  6322. std::string(),
  6323. std::string(),
  6324. false));
  6325. m_totals.testCases.failed++;
  6326. testGroupEnded(std::string(), m_totals, 1, 1);
  6327. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, false));
  6328. }
  6329. bool RunContext::lastAssertionPassed() {
  6330. return m_totals.assertions.passed == (m_prevPassed + 1);
  6331. }
  6332. void RunContext::assertionPassed() {
  6333. ++m_totals.assertions.passed;
  6334. m_lastAssertionInfo.capturedExpression = "{Unknown expression after the reported line}";
  6335. m_lastAssertionInfo.macroName = "";
  6336. }
  6337. void RunContext::assertionRun() {
  6338. m_prevPassed = m_totals.assertions.passed;
  6339. }
  6340. bool RunContext::aborting() const {
  6341. return m_totals.assertions.failed == static_cast<std::size_t>(m_config->abortAfter());
  6342. }
  6343. void RunContext::runCurrentTest(std::string & redirectedCout, std::string & redirectedCerr) {
  6344. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  6345. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name, testCaseInfo.description);
  6346. m_reporter->sectionStarting(testCaseSection);
  6347. Counts prevAssertions = m_totals.assertions;
  6348. double duration = 0;
  6349. m_shouldReportUnexpected = true;
  6350. try {
  6351. m_lastAssertionInfo = { "TEST_CASE", testCaseInfo.lineInfo, "", ResultDisposition::Normal };
  6352. seedRng(*m_config);
  6353. Timer timer;
  6354. timer.start();
  6355. if (m_reporter->getPreferences().shouldRedirectStdOut) {
  6356. StreamRedirect coutRedir(cout(), redirectedCout);
  6357. StdErrRedirect errRedir(redirectedCerr);
  6358. invokeActiveTestCase();
  6359. } else {
  6360. invokeActiveTestCase();
  6361. }
  6362. duration = timer.getElapsedSeconds();
  6363. } catch (TestFailureException&) {
  6364. // This just means the test was aborted due to failure
  6365. } catch (...) {
  6366. // Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under REQUIRE assertions
  6367. // are reported without translation at the point of origin.
  6368. if (m_shouldReportUnexpected) {
  6369. AssertionHandler
  6370. ( m_lastAssertionInfo.macroName,
  6371. m_lastAssertionInfo.lineInfo,
  6372. m_lastAssertionInfo.capturedExpression,
  6373. m_lastAssertionInfo.resultDisposition ).useActiveException();
  6374. }
  6375. }
  6376. m_testCaseTracker->close();
  6377. handleUnfinishedSections();
  6378. m_messages.clear();
  6379. Counts assertions = m_totals.assertions - prevAssertions;
  6380. bool missingAssertions = testForMissingAssertions(assertions);
  6381. SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions);
  6382. m_reporter->sectionEnded(testCaseSectionStats);
  6383. }
  6384. void RunContext::invokeActiveTestCase() {
  6385. FatalConditionHandler fatalConditionHandler; // Handle signals
  6386. m_activeTestCase->invoke();
  6387. fatalConditionHandler.reset();
  6388. }
  6389. void RunContext::handleUnfinishedSections() {
  6390. // If sections ended prematurely due to an exception we stored their
  6391. // infos here so we can tear them down outside the unwind process.
  6392. for (auto it = m_unfinishedSections.rbegin(),
  6393. itEnd = m_unfinishedSections.rend();
  6394. it != itEnd;
  6395. ++it)
  6396. sectionEnded(*it);
  6397. m_unfinishedSections.clear();
  6398. }
  6399. IResultCapture& getResultCapture() {
  6400. if (auto* capture = getCurrentContext().getResultCapture())
  6401. return *capture;
  6402. else
  6403. CATCH_INTERNAL_ERROR("No result capture instance");
  6404. }
  6405. }
  6406. // end catch_run_context.cpp
  6407. // start catch_section.cpp
  6408. namespace Catch {
  6409. Section::Section( SectionInfo const& info )
  6410. : m_info( info ),
  6411. m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) )
  6412. {
  6413. m_timer.start();
  6414. }
  6415. #if defined(_MSC_VER)
  6416. #pragma warning(push)
  6417. #pragma warning(disable:4996) // std::uncaught_exception is deprecated in C++17
  6418. #endif
  6419. Section::~Section() {
  6420. if( m_sectionIncluded ) {
  6421. SectionEndInfo endInfo( m_info, m_assertions, m_timer.getElapsedSeconds() );
  6422. if( std::uncaught_exception() )
  6423. getResultCapture().sectionEndedEarly( endInfo );
  6424. else
  6425. getResultCapture().sectionEnded( endInfo );
  6426. }
  6427. }
  6428. #if defined(_MSC_VER)
  6429. #pragma warning(pop)
  6430. #endif
  6431. // This indicates whether the section should be executed or not
  6432. Section::operator bool() const {
  6433. return m_sectionIncluded;
  6434. }
  6435. } // end namespace Catch
  6436. // end catch_section.cpp
  6437. // start catch_section_info.cpp
  6438. namespace Catch {
  6439. SectionInfo::SectionInfo
  6440. ( SourceLineInfo const& _lineInfo,
  6441. std::string const& _name,
  6442. std::string const& _description )
  6443. : name( _name ),
  6444. description( _description ),
  6445. lineInfo( _lineInfo )
  6446. {}
  6447. SectionEndInfo::SectionEndInfo( SectionInfo const& _sectionInfo, Counts const& _prevAssertions, double _durationInSeconds )
  6448. : sectionInfo( _sectionInfo ), prevAssertions( _prevAssertions ), durationInSeconds( _durationInSeconds )
  6449. {}
  6450. } // end namespace Catch
  6451. // end catch_section_info.cpp
  6452. // start catch_session.cpp
  6453. // start catch_session.h
  6454. #include <memory>
  6455. namespace Catch {
  6456. class Session : NonCopyable {
  6457. public:
  6458. Session();
  6459. ~Session() override;
  6460. void showHelp() const;
  6461. void libIdentify();
  6462. int applyCommandLine( int argc, char* argv[] );
  6463. void useConfigData( ConfigData const& configData );
  6464. int run( int argc, char* argv[] );
  6465. #if defined(WIN32) && defined(UNICODE)
  6466. int run( int argc, wchar_t* const argv[] );
  6467. #endif
  6468. int run();
  6469. clara::Parser const& cli() const;
  6470. void cli( clara::Parser const& newParser );
  6471. ConfigData& configData();
  6472. Config& config();
  6473. private:
  6474. int runInternal();
  6475. clara::Parser m_cli;
  6476. ConfigData m_configData;
  6477. std::shared_ptr<Config> m_config;
  6478. bool m_startupExceptions = false;
  6479. };
  6480. } // end namespace Catch
  6481. // end catch_session.h
  6482. // start catch_version.h
  6483. #include <iosfwd>
  6484. namespace Catch {
  6485. // Versioning information
  6486. struct Version {
  6487. Version( Version const& ) = delete;
  6488. Version& operator=( Version const& ) = delete;
  6489. Version( unsigned int _majorVersion,
  6490. unsigned int _minorVersion,
  6491. unsigned int _patchNumber,
  6492. char const * const _branchName,
  6493. unsigned int _buildNumber );
  6494. unsigned int const majorVersion;
  6495. unsigned int const minorVersion;
  6496. unsigned int const patchNumber;
  6497. // buildNumber is only used if branchName is not null
  6498. char const * const branchName;
  6499. unsigned int const buildNumber;
  6500. friend std::ostream& operator << ( std::ostream& os, Version const& version );
  6501. };
  6502. Version const& libraryVersion();
  6503. }
  6504. // end catch_version.h
  6505. #include <cstdlib>
  6506. #include <iomanip>
  6507. namespace {
  6508. const int MaxExitCode = 255;
  6509. using Catch::IStreamingReporterPtr;
  6510. using Catch::IConfigPtr;
  6511. using Catch::Config;
  6512. IStreamingReporterPtr createReporter(std::string const& reporterName, IConfigPtr const& config) {
  6513. auto reporter = Catch::getRegistryHub().getReporterRegistry().create(reporterName, config);
  6514. CATCH_ENFORCE(reporter, "No reporter registered with name: '" << reporterName << "'");
  6515. return reporter;
  6516. }
  6517. #ifndef CATCH_CONFIG_DEFAULT_REPORTER
  6518. #define CATCH_CONFIG_DEFAULT_REPORTER "console"
  6519. #endif
  6520. IStreamingReporterPtr makeReporter(std::shared_ptr<Config> const& config) {
  6521. auto const& reporterNames = config->getReporterNames();
  6522. if (reporterNames.empty())
  6523. return createReporter(CATCH_CONFIG_DEFAULT_REPORTER, config);
  6524. IStreamingReporterPtr reporter;
  6525. for (auto const& name : reporterNames)
  6526. addReporter(reporter, createReporter(name, config));
  6527. return reporter;
  6528. }
  6529. #undef CATCH_CONFIG_DEFAULT_REPORTER
  6530. void addListeners(IStreamingReporterPtr& reporters, IConfigPtr const& config) {
  6531. auto const& listeners = Catch::getRegistryHub().getReporterRegistry().getListeners();
  6532. for (auto const& listener : listeners)
  6533. addReporter(reporters, listener->create(Catch::ReporterConfig(config)));
  6534. }
  6535. Catch::Totals runTests(std::shared_ptr<Config> const& config) {
  6536. using namespace Catch;
  6537. IStreamingReporterPtr reporter = makeReporter(config);
  6538. addListeners(reporter, config);
  6539. RunContext context(config, std::move(reporter));
  6540. Totals totals;
  6541. context.testGroupStarting(config->name(), 1, 1);
  6542. TestSpec testSpec = config->testSpec();
  6543. if (!testSpec.hasFilters())
  6544. testSpec = TestSpecParser(ITagAliasRegistry::get()).parse("~[.]").testSpec(); // All not hidden tests
  6545. auto const& allTestCases = getAllTestCasesSorted(*config);
  6546. for (auto const& testCase : allTestCases) {
  6547. if (!context.aborting() && matchTest(testCase, testSpec, *config))
  6548. totals += context.runTest(testCase);
  6549. else
  6550. context.reporter().skipTest(testCase);
  6551. }
  6552. context.testGroupEnded(config->name(), totals, 1, 1);
  6553. return totals;
  6554. }
  6555. void applyFilenamesAsTags(Catch::IConfig const& config) {
  6556. using namespace Catch;
  6557. auto& tests = const_cast<std::vector<TestCase>&>(getAllTestCasesSorted(config));
  6558. for (auto& testCase : tests) {
  6559. auto tags = testCase.tags;
  6560. std::string filename = testCase.lineInfo.file;
  6561. auto lastSlash = filename.find_last_of("\\/");
  6562. if (lastSlash != std::string::npos) {
  6563. filename.erase(0, lastSlash);
  6564. filename[0] = '#';
  6565. }
  6566. auto lastDot = filename.find_last_of('.');
  6567. if (lastDot != std::string::npos) {
  6568. filename.erase(lastDot);
  6569. }
  6570. tags.push_back(std::move(filename));
  6571. setTags(testCase, tags);
  6572. }
  6573. }
  6574. }
  6575. namespace Catch {
  6576. Session::Session() {
  6577. static bool alreadyInstantiated = false;
  6578. if( alreadyInstantiated ) {
  6579. try { CATCH_INTERNAL_ERROR( "Only one instance of Catch::Session can ever be used" ); }
  6580. catch(...) { getMutableRegistryHub().registerStartupException(); }
  6581. }
  6582. const auto& exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions();
  6583. if ( !exceptions.empty() ) {
  6584. m_startupExceptions = true;
  6585. Colour colourGuard( Colour::Red );
  6586. Catch::cerr() << "Errors occured during startup!" << '\n';
  6587. // iterate over all exceptions and notify user
  6588. for ( const auto& ex_ptr : exceptions ) {
  6589. try {
  6590. std::rethrow_exception(ex_ptr);
  6591. } catch ( std::exception const& ex ) {
  6592. Catch::cerr() << Column( ex.what() ).indent(2) << '\n';
  6593. }
  6594. }
  6595. }
  6596. alreadyInstantiated = true;
  6597. m_cli = makeCommandLineParser( m_configData );
  6598. }
  6599. Session::~Session() {
  6600. Catch::cleanUp();
  6601. }
  6602. void Session::showHelp() const {
  6603. Catch::cout()
  6604. << "\nCatch v" << libraryVersion() << "\n"
  6605. << m_cli << std::endl
  6606. << "For more detailed usage please see the project docs\n" << std::endl;
  6607. }
  6608. void Session::libIdentify() {
  6609. Catch::cout()
  6610. << std::left << std::setw(16) << "description: " << "A Catch test executable\n"
  6611. << std::left << std::setw(16) << "category: " << "testframework\n"
  6612. << std::left << std::setw(16) << "framework: " << "Catch Test\n"
  6613. << std::left << std::setw(16) << "version: " << libraryVersion() << std::endl;
  6614. }
  6615. int Session::applyCommandLine( int argc, char* argv[] ) {
  6616. if( m_startupExceptions )
  6617. return 1;
  6618. auto result = m_cli.parse( clara::Args( argc, argv ) );
  6619. if( !result ) {
  6620. Catch::cerr()
  6621. << Colour( Colour::Red )
  6622. << "\nError(s) in input:\n"
  6623. << Column( result.errorMessage() ).indent( 2 )
  6624. << "\n\n";
  6625. Catch::cerr() << "Run with -? for usage\n" << std::endl;
  6626. return MaxExitCode;
  6627. }
  6628. if( m_configData.showHelp )
  6629. showHelp();
  6630. if( m_configData.libIdentify )
  6631. libIdentify();
  6632. m_config.reset();
  6633. return 0;
  6634. }
  6635. void Session::useConfigData( ConfigData const& configData ) {
  6636. m_configData = configData;
  6637. m_config.reset();
  6638. }
  6639. int Session::run( int argc, char* argv[] ) {
  6640. if( m_startupExceptions )
  6641. return 1;
  6642. int returnCode = applyCommandLine( argc, argv );
  6643. if( returnCode == 0 )
  6644. returnCode = run();
  6645. return returnCode;
  6646. }
  6647. #if defined(WIN32) && defined(UNICODE)
  6648. int Session::run( int argc, wchar_t* const argv[] ) {
  6649. char **utf8Argv = new char *[ argc ];
  6650. for ( int i = 0; i < argc; ++i ) {
  6651. int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, NULL, 0, NULL, NULL );
  6652. utf8Argv[ i ] = new char[ bufSize ];
  6653. WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, NULL, NULL );
  6654. }
  6655. int returnCode = run( argc, utf8Argv );
  6656. for ( int i = 0; i < argc; ++i )
  6657. delete [] utf8Argv[ i ];
  6658. delete [] utf8Argv;
  6659. return returnCode;
  6660. }
  6661. #endif
  6662. int Session::run() {
  6663. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeStart ) != 0 ) {
  6664. Catch::cout() << "...waiting for enter/ return before starting" << std::endl;
  6665. static_cast<void>(std::getchar());
  6666. }
  6667. int exitCode = runInternal();
  6668. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeExit ) != 0 ) {
  6669. Catch::cout() << "...waiting for enter/ return before exiting, with code: " << exitCode << std::endl;
  6670. static_cast<void>(std::getchar());
  6671. }
  6672. return exitCode;
  6673. }
  6674. clara::Parser const& Session::cli() const {
  6675. return m_cli;
  6676. }
  6677. void Session::cli( clara::Parser const& newParser ) {
  6678. m_cli = newParser;
  6679. }
  6680. ConfigData& Session::configData() {
  6681. return m_configData;
  6682. }
  6683. Config& Session::config() {
  6684. if( !m_config )
  6685. m_config = std::make_shared<Config>( m_configData );
  6686. return *m_config;
  6687. }
  6688. int Session::runInternal() {
  6689. if( m_startupExceptions )
  6690. return 1;
  6691. if( m_configData.showHelp || m_configData.libIdentify )
  6692. return 0;
  6693. try
  6694. {
  6695. config(); // Force config to be constructed
  6696. seedRng( *m_config );
  6697. if( m_configData.filenamesAsTags )
  6698. applyFilenamesAsTags( *m_config );
  6699. // Handle list request
  6700. if( Option<std::size_t> listed = list( config() ) )
  6701. return static_cast<int>( *listed );
  6702. return (std::min)( MaxExitCode, static_cast<int>( runTests( m_config ).assertions.failed ) );
  6703. }
  6704. catch( std::exception& ex ) {
  6705. Catch::cerr() << ex.what() << std::endl;
  6706. return MaxExitCode;
  6707. }
  6708. }
  6709. } // end namespace Catch
  6710. // end catch_session.cpp
  6711. // start catch_startup_exception_registry.cpp
  6712. namespace Catch {
  6713. void StartupExceptionRegistry::add( std::exception_ptr const& exception ) noexcept {
  6714. try {
  6715. m_exceptions.push_back(exception);
  6716. }
  6717. catch(...) {
  6718. // If we run out of memory during start-up there's really not a lot more we can do about it
  6719. std::terminate();
  6720. }
  6721. }
  6722. std::vector<std::exception_ptr> const& StartupExceptionRegistry::getExceptions() const noexcept {
  6723. return m_exceptions;
  6724. }
  6725. } // end namespace Catch
  6726. // end catch_startup_exception_registry.cpp
  6727. // start catch_stream.cpp
  6728. #include <stdexcept>
  6729. #include <cstdio>
  6730. #include <iostream>
  6731. namespace Catch {
  6732. template<typename WriterF, std::size_t bufferSize=256>
  6733. class StreamBufImpl : public StreamBufBase {
  6734. char data[bufferSize];
  6735. WriterF m_writer;
  6736. public:
  6737. StreamBufImpl() {
  6738. setp( data, data + sizeof(data) );
  6739. }
  6740. ~StreamBufImpl() noexcept {
  6741. StreamBufImpl::sync();
  6742. }
  6743. private:
  6744. int overflow( int c ) override {
  6745. sync();
  6746. if( c != EOF ) {
  6747. if( pbase() == epptr() )
  6748. m_writer( std::string( 1, static_cast<char>( c ) ) );
  6749. else
  6750. sputc( static_cast<char>( c ) );
  6751. }
  6752. return 0;
  6753. }
  6754. int sync() override {
  6755. if( pbase() != pptr() ) {
  6756. m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) );
  6757. setp( pbase(), epptr() );
  6758. }
  6759. return 0;
  6760. }
  6761. };
  6762. ///////////////////////////////////////////////////////////////////////////
  6763. Catch::IStream::~IStream() = default;
  6764. FileStream::FileStream( std::string const& filename ) {
  6765. m_ofs.open( filename.c_str() );
  6766. CATCH_ENFORCE( !m_ofs.fail(), "Unable to open file: '" << filename << "'" );
  6767. }
  6768. std::ostream& FileStream::stream() const {
  6769. return m_ofs;
  6770. }
  6771. struct OutputDebugWriter {
  6772. void operator()( std::string const&str ) {
  6773. writeToDebugConsole( str );
  6774. }
  6775. };
  6776. DebugOutStream::DebugOutStream()
  6777. : m_streamBuf( new StreamBufImpl<OutputDebugWriter>() ),
  6778. m_os( m_streamBuf.get() )
  6779. {}
  6780. std::ostream& DebugOutStream::stream() const {
  6781. return m_os;
  6782. }
  6783. // Store the streambuf from cout up-front because
  6784. // cout may get redirected when running tests
  6785. CoutStream::CoutStream()
  6786. : m_os( Catch::cout().rdbuf() )
  6787. {}
  6788. std::ostream& CoutStream::stream() const {
  6789. return m_os;
  6790. }
  6791. #ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions
  6792. std::ostream& cout() {
  6793. return std::cout;
  6794. }
  6795. std::ostream& cerr() {
  6796. return std::cerr;
  6797. }
  6798. std::ostream& clog() {
  6799. return std::clog;
  6800. }
  6801. #endif
  6802. }
  6803. // end catch_stream.cpp
  6804. // start catch_streambuf.cpp
  6805. namespace Catch {
  6806. StreamBufBase::~StreamBufBase() = default;
  6807. }
  6808. // end catch_streambuf.cpp
  6809. // start catch_string_manip.cpp
  6810. #include <algorithm>
  6811. #include <ostream>
  6812. #include <cstring>
  6813. #include <cctype>
  6814. namespace Catch {
  6815. bool startsWith( std::string const& s, std::string const& prefix ) {
  6816. return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
  6817. }
  6818. bool startsWith( std::string const& s, char prefix ) {
  6819. return !s.empty() && s[0] == prefix;
  6820. }
  6821. bool endsWith( std::string const& s, std::string const& suffix ) {
  6822. return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
  6823. }
  6824. bool endsWith( std::string const& s, char suffix ) {
  6825. return !s.empty() && s[s.size()-1] == suffix;
  6826. }
  6827. bool contains( std::string const& s, std::string const& infix ) {
  6828. return s.find( infix ) != std::string::npos;
  6829. }
  6830. char toLowerCh(char c) {
  6831. return static_cast<char>( std::tolower( c ) );
  6832. }
  6833. void toLowerInPlace( std::string& s ) {
  6834. std::transform( s.begin(), s.end(), s.begin(), toLowerCh );
  6835. }
  6836. std::string toLower( std::string const& s ) {
  6837. std::string lc = s;
  6838. toLowerInPlace( lc );
  6839. return lc;
  6840. }
  6841. std::string trim( std::string const& str ) {
  6842. static char const* whitespaceChars = "\n\r\t ";
  6843. std::string::size_type start = str.find_first_not_of( whitespaceChars );
  6844. std::string::size_type end = str.find_last_not_of( whitespaceChars );
  6845. return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string();
  6846. }
  6847. bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) {
  6848. bool replaced = false;
  6849. std::size_t i = str.find( replaceThis );
  6850. while( i != std::string::npos ) {
  6851. replaced = true;
  6852. str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() );
  6853. if( i < str.size()-withThis.size() )
  6854. i = str.find( replaceThis, i+withThis.size() );
  6855. else
  6856. i = std::string::npos;
  6857. }
  6858. return replaced;
  6859. }
  6860. pluralise::pluralise( std::size_t count, std::string const& label )
  6861. : m_count( count ),
  6862. m_label( label )
  6863. {}
  6864. std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) {
  6865. os << pluraliser.m_count << ' ' << pluraliser.m_label;
  6866. if( pluraliser.m_count != 1 )
  6867. os << 's';
  6868. return os;
  6869. }
  6870. }
  6871. // end catch_string_manip.cpp
  6872. // start catch_stringref.cpp
  6873. #if defined(__clang__)
  6874. # pragma clang diagnostic push
  6875. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  6876. #endif
  6877. #include <ostream>
  6878. #include <cassert>
  6879. #include <cstring>
  6880. namespace Catch {
  6881. auto getEmptyStringRef() -> StringRef {
  6882. static StringRef s_emptyStringRef("");
  6883. return s_emptyStringRef;
  6884. }
  6885. StringRef::StringRef() noexcept
  6886. : StringRef( getEmptyStringRef() )
  6887. {}
  6888. StringRef::StringRef( StringRef const& other ) noexcept
  6889. : m_start( other.m_start ),
  6890. m_size( other.m_size )
  6891. {}
  6892. StringRef::StringRef( StringRef&& other ) noexcept
  6893. : m_start( other.m_start ),
  6894. m_size( other.m_size ),
  6895. m_data( other.m_data )
  6896. {
  6897. other.m_data = nullptr;
  6898. }
  6899. StringRef::StringRef( char const* rawChars ) noexcept
  6900. : m_start( rawChars ),
  6901. m_size( static_cast<size_type>( std::strlen( rawChars ) ) )
  6902. {
  6903. assert( rawChars != nullptr );
  6904. }
  6905. StringRef::StringRef( char const* rawChars, size_type size ) noexcept
  6906. : m_start( rawChars ),
  6907. m_size( size )
  6908. {
  6909. size_type rawSize = rawChars == nullptr ? 0 : static_cast<size_type>( std::strlen( rawChars ) );
  6910. if( rawSize < size )
  6911. m_size = rawSize;
  6912. }
  6913. StringRef::StringRef( std::string const& stdString ) noexcept
  6914. : m_start( stdString.c_str() ),
  6915. m_size( stdString.size() )
  6916. {}
  6917. StringRef::~StringRef() noexcept {
  6918. delete[] m_data;
  6919. }
  6920. auto StringRef::operator = ( StringRef other ) noexcept -> StringRef& {
  6921. swap( other );
  6922. return *this;
  6923. }
  6924. StringRef::operator std::string() const {
  6925. return std::string( m_start, m_size );
  6926. }
  6927. void StringRef::swap( StringRef& other ) noexcept {
  6928. std::swap( m_start, other.m_start );
  6929. std::swap( m_size, other.m_size );
  6930. std::swap( m_data, other.m_data );
  6931. }
  6932. auto StringRef::c_str() const -> char const* {
  6933. if( isSubstring() )
  6934. const_cast<StringRef*>( this )->takeOwnership();
  6935. return m_start;
  6936. }
  6937. auto StringRef::data() const noexcept -> char const* {
  6938. return m_start;
  6939. }
  6940. auto StringRef::isOwned() const noexcept -> bool {
  6941. return m_data != nullptr;
  6942. }
  6943. auto StringRef::isSubstring() const noexcept -> bool {
  6944. return m_start[m_size] != '\0';
  6945. }
  6946. void StringRef::takeOwnership() {
  6947. if( !isOwned() ) {
  6948. m_data = new char[m_size+1];
  6949. memcpy( m_data, m_start, m_size );
  6950. m_data[m_size] = '\0';
  6951. m_start = m_data;
  6952. }
  6953. }
  6954. auto StringRef::substr( size_type start, size_type size ) const noexcept -> StringRef {
  6955. if( start < m_size )
  6956. return StringRef( m_start+start, size );
  6957. else
  6958. return StringRef();
  6959. }
  6960. auto StringRef::operator == ( StringRef const& other ) const noexcept -> bool {
  6961. return
  6962. size() == other.size() &&
  6963. (std::strncmp( m_start, other.m_start, size() ) == 0);
  6964. }
  6965. auto StringRef::operator != ( StringRef const& other ) const noexcept -> bool {
  6966. return !operator==( other );
  6967. }
  6968. auto StringRef::operator[](size_type index) const noexcept -> char {
  6969. return m_start[index];
  6970. }
  6971. auto StringRef::empty() const noexcept -> bool {
  6972. return m_size == 0;
  6973. }
  6974. auto StringRef::size() const noexcept -> size_type {
  6975. return m_size;
  6976. }
  6977. auto StringRef::numberOfCharacters() const noexcept -> size_type {
  6978. size_type noChars = m_size;
  6979. // Make adjustments for uft encodings
  6980. for( size_type i=0; i < m_size; ++i ) {
  6981. char c = m_start[i];
  6982. if( ( c & 0b11000000 ) == 0b11000000 ) {
  6983. if( ( c & 0b11100000 ) == 0b11000000 )
  6984. noChars--;
  6985. else if( ( c & 0b11110000 ) == 0b11100000 )
  6986. noChars-=2;
  6987. else if( ( c & 0b11111000 ) == 0b11110000 )
  6988. noChars-=3;
  6989. }
  6990. }
  6991. return noChars;
  6992. }
  6993. auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string {
  6994. std::string str;
  6995. str.reserve( lhs.size() + rhs.size() );
  6996. str += lhs;
  6997. str += rhs;
  6998. return str;
  6999. }
  7000. auto operator + ( StringRef const& lhs, const char* rhs ) -> std::string {
  7001. return std::string( lhs ) + std::string( rhs );
  7002. }
  7003. auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string {
  7004. return std::string( lhs ) + std::string( rhs );
  7005. }
  7006. auto operator << ( std::ostream& os, StringRef const& str ) -> std::ostream& {
  7007. return os << str.c_str();
  7008. }
  7009. } // namespace Catch
  7010. #if defined(__clang__)
  7011. # pragma clang diagnostic pop
  7012. #endif
  7013. // end catch_stringref.cpp
  7014. // start catch_tag_alias.cpp
  7015. namespace Catch {
  7016. TagAlias::TagAlias(std::string const & _tag, SourceLineInfo _lineInfo): tag(_tag), lineInfo(_lineInfo) {}
  7017. }
  7018. // end catch_tag_alias.cpp
  7019. // start catch_tag_alias_autoregistrar.cpp
  7020. namespace Catch {
  7021. RegistrarForTagAliases::RegistrarForTagAliases(char const* alias, char const* tag, SourceLineInfo const& lineInfo) {
  7022. try {
  7023. getMutableRegistryHub().registerTagAlias(alias, tag, lineInfo);
  7024. } catch (...) {
  7025. // Do not throw when constructing global objects, instead register the exception to be processed later
  7026. getMutableRegistryHub().registerStartupException();
  7027. }
  7028. }
  7029. }
  7030. // end catch_tag_alias_autoregistrar.cpp
  7031. // start catch_tag_alias_registry.cpp
  7032. namespace Catch {
  7033. TagAliasRegistry::~TagAliasRegistry() {}
  7034. TagAlias const* TagAliasRegistry::find( std::string const& alias ) const {
  7035. auto it = m_registry.find( alias );
  7036. if( it != m_registry.end() )
  7037. return &(it->second);
  7038. else
  7039. return nullptr;
  7040. }
  7041. std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const {
  7042. std::string expandedTestSpec = unexpandedTestSpec;
  7043. for( auto const& registryKvp : m_registry ) {
  7044. std::size_t pos = expandedTestSpec.find( registryKvp.first );
  7045. if( pos != std::string::npos ) {
  7046. expandedTestSpec = expandedTestSpec.substr( 0, pos ) +
  7047. registryKvp.second.tag +
  7048. expandedTestSpec.substr( pos + registryKvp.first.size() );
  7049. }
  7050. }
  7051. return expandedTestSpec;
  7052. }
  7053. void TagAliasRegistry::add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) {
  7054. CATCH_ENFORCE( startsWith(alias, "[@") && endsWith(alias, ']'),
  7055. "error: tag alias, '" << alias << "' is not of the form [@alias name].\n" << lineInfo );
  7056. CATCH_ENFORCE( m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second,
  7057. "error: tag alias, '" << alias << "' already registered.\n"
  7058. << "\tFirst seen at: " << find(alias)->lineInfo << "\n"
  7059. << "\tRedefined at: " << lineInfo );
  7060. }
  7061. ITagAliasRegistry::~ITagAliasRegistry() {}
  7062. ITagAliasRegistry const& ITagAliasRegistry::get() {
  7063. return getRegistryHub().getTagAliasRegistry();
  7064. }
  7065. } // end namespace Catch
  7066. // end catch_tag_alias_registry.cpp
  7067. // start catch_test_case_info.cpp
  7068. #include <cctype>
  7069. #include <exception>
  7070. #include <algorithm>
  7071. namespace Catch {
  7072. TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) {
  7073. if( startsWith( tag, '.' ) ||
  7074. tag == "!hide" )
  7075. return TestCaseInfo::IsHidden;
  7076. else if( tag == "!throws" )
  7077. return TestCaseInfo::Throws;
  7078. else if( tag == "!shouldfail" )
  7079. return TestCaseInfo::ShouldFail;
  7080. else if( tag == "!mayfail" )
  7081. return TestCaseInfo::MayFail;
  7082. else if( tag == "!nonportable" )
  7083. return TestCaseInfo::NonPortable;
  7084. else if( tag == "!benchmark" )
  7085. return static_cast<TestCaseInfo::SpecialProperties>( TestCaseInfo::Benchmark | TestCaseInfo::IsHidden );
  7086. else
  7087. return TestCaseInfo::None;
  7088. }
  7089. bool isReservedTag( std::string const& tag ) {
  7090. return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !std::isalnum( tag[0] );
  7091. }
  7092. void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) {
  7093. CATCH_ENFORCE( !isReservedTag(tag),
  7094. "Tag name: [" << tag << "] is not allowed.\n"
  7095. << "Tag names starting with non alpha-numeric characters are reserved\n"
  7096. << _lineInfo );
  7097. }
  7098. TestCase makeTestCase( ITestInvoker* _testCase,
  7099. std::string const& _className,
  7100. std::string const& _name,
  7101. std::string const& _descOrTags,
  7102. SourceLineInfo const& _lineInfo )
  7103. {
  7104. bool isHidden = false;
  7105. // Parse out tags
  7106. std::vector<std::string> tags;
  7107. std::string desc, tag;
  7108. bool inTag = false;
  7109. for (char c : _descOrTags) {
  7110. if( !inTag ) {
  7111. if( c == '[' )
  7112. inTag = true;
  7113. else
  7114. desc += c;
  7115. }
  7116. else {
  7117. if( c == ']' ) {
  7118. TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag );
  7119. if( ( prop & TestCaseInfo::IsHidden ) != 0 )
  7120. isHidden = true;
  7121. else if( prop == TestCaseInfo::None )
  7122. enforceNotReservedTag( tag, _lineInfo );
  7123. tags.push_back( tag );
  7124. tag.clear();
  7125. inTag = false;
  7126. }
  7127. else
  7128. tag += c;
  7129. }
  7130. }
  7131. if( isHidden ) {
  7132. tags.push_back( "." );
  7133. }
  7134. TestCaseInfo info( _name, _className, desc, tags, _lineInfo );
  7135. return TestCase( _testCase, info );
  7136. }
  7137. void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags ) {
  7138. std::sort(begin(tags), end(tags));
  7139. tags.erase(std::unique(begin(tags), end(tags)), end(tags));
  7140. testCaseInfo.lcaseTags.clear();
  7141. for( auto const& tag : tags ) {
  7142. std::string lcaseTag = toLower( tag );
  7143. testCaseInfo.properties = static_cast<TestCaseInfo::SpecialProperties>( testCaseInfo.properties | parseSpecialTag( lcaseTag ) );
  7144. testCaseInfo.lcaseTags.push_back( lcaseTag );
  7145. }
  7146. testCaseInfo.tags = std::move(tags);
  7147. }
  7148. TestCaseInfo::TestCaseInfo( std::string const& _name,
  7149. std::string const& _className,
  7150. std::string const& _description,
  7151. std::vector<std::string> const& _tags,
  7152. SourceLineInfo const& _lineInfo )
  7153. : name( _name ),
  7154. className( _className ),
  7155. description( _description ),
  7156. lineInfo( _lineInfo ),
  7157. properties( None )
  7158. {
  7159. setTags( *this, _tags );
  7160. }
  7161. bool TestCaseInfo::isHidden() const {
  7162. return ( properties & IsHidden ) != 0;
  7163. }
  7164. bool TestCaseInfo::throws() const {
  7165. return ( properties & Throws ) != 0;
  7166. }
  7167. bool TestCaseInfo::okToFail() const {
  7168. return ( properties & (ShouldFail | MayFail ) ) != 0;
  7169. }
  7170. bool TestCaseInfo::expectedToFail() const {
  7171. return ( properties & (ShouldFail ) ) != 0;
  7172. }
  7173. std::string TestCaseInfo::tagsAsString() const {
  7174. std::string ret;
  7175. // '[' and ']' per tag
  7176. std::size_t full_size = 2 * tags.size();
  7177. for (const auto& tag : tags) {
  7178. full_size += tag.size();
  7179. }
  7180. ret.reserve(full_size);
  7181. for (const auto& tag : tags) {
  7182. ret.push_back('[');
  7183. ret.append(tag);
  7184. ret.push_back(']');
  7185. }
  7186. return ret;
  7187. }
  7188. TestCase::TestCase( ITestInvoker* testCase, TestCaseInfo const& info ) : TestCaseInfo( info ), test( testCase ) {}
  7189. TestCase TestCase::withName( std::string const& _newName ) const {
  7190. TestCase other( *this );
  7191. other.name = _newName;
  7192. return other;
  7193. }
  7194. void TestCase::invoke() const {
  7195. test->invoke();
  7196. }
  7197. bool TestCase::operator == ( TestCase const& other ) const {
  7198. return test.get() == other.test.get() &&
  7199. name == other.name &&
  7200. className == other.className;
  7201. }
  7202. bool TestCase::operator < ( TestCase const& other ) const {
  7203. return name < other.name;
  7204. }
  7205. TestCaseInfo const& TestCase::getTestCaseInfo() const
  7206. {
  7207. return *this;
  7208. }
  7209. } // end namespace Catch
  7210. // end catch_test_case_info.cpp
  7211. // start catch_test_case_registry_impl.cpp
  7212. #include <sstream>
  7213. namespace Catch {
  7214. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases ) {
  7215. std::vector<TestCase> sorted = unsortedTestCases;
  7216. switch( config.runOrder() ) {
  7217. case RunTests::InLexicographicalOrder:
  7218. std::sort( sorted.begin(), sorted.end() );
  7219. break;
  7220. case RunTests::InRandomOrder:
  7221. seedRng( config );
  7222. RandomNumberGenerator::shuffle( sorted );
  7223. break;
  7224. case RunTests::InDeclarationOrder:
  7225. // already in declaration order
  7226. break;
  7227. }
  7228. return sorted;
  7229. }
  7230. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ) {
  7231. return testSpec.matches( testCase ) && ( config.allowThrows() || !testCase.throws() );
  7232. }
  7233. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions ) {
  7234. std::set<TestCase> seenFunctions;
  7235. for( auto const& function : functions ) {
  7236. auto prev = seenFunctions.insert( function );
  7237. CATCH_ENFORCE( prev.second,
  7238. "error: TEST_CASE( \"" << function.name << "\" ) already defined.\n"
  7239. << "\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo << "\n"
  7240. << "\tRedefined at " << function.getTestCaseInfo().lineInfo );
  7241. }
  7242. }
  7243. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config ) {
  7244. std::vector<TestCase> filtered;
  7245. filtered.reserve( testCases.size() );
  7246. for( auto const& testCase : testCases )
  7247. if( matchTest( testCase, testSpec, config ) )
  7248. filtered.push_back( testCase );
  7249. return filtered;
  7250. }
  7251. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config ) {
  7252. return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config );
  7253. }
  7254. void TestRegistry::registerTest( TestCase const& testCase ) {
  7255. std::string name = testCase.getTestCaseInfo().name;
  7256. if( name.empty() ) {
  7257. std::ostringstream oss;
  7258. oss << "Anonymous test case " << ++m_unnamedCount;
  7259. return registerTest( testCase.withName( oss.str() ) );
  7260. }
  7261. m_functions.push_back( testCase );
  7262. }
  7263. std::vector<TestCase> const& TestRegistry::getAllTests() const {
  7264. return m_functions;
  7265. }
  7266. std::vector<TestCase> const& TestRegistry::getAllTestsSorted( IConfig const& config ) const {
  7267. if( m_sortedFunctions.empty() )
  7268. enforceNoDuplicateTestCases( m_functions );
  7269. if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) {
  7270. m_sortedFunctions = sortTests( config, m_functions );
  7271. m_currentSortOrder = config.runOrder();
  7272. }
  7273. return m_sortedFunctions;
  7274. }
  7275. ///////////////////////////////////////////////////////////////////////////
  7276. TestInvokerAsFunction::TestInvokerAsFunction( void(*testAsFunction)() ) noexcept : m_testAsFunction( testAsFunction ) {}
  7277. void TestInvokerAsFunction::invoke() const {
  7278. m_testAsFunction();
  7279. }
  7280. std::string extractClassName( std::string const& classOrQualifiedMethodName ) {
  7281. std::string className = classOrQualifiedMethodName;
  7282. if( startsWith( className, '&' ) )
  7283. {
  7284. std::size_t lastColons = className.rfind( "::" );
  7285. std::size_t penultimateColons = className.rfind( "::", lastColons-1 );
  7286. if( penultimateColons == std::string::npos )
  7287. penultimateColons = 1;
  7288. className = className.substr( penultimateColons, lastColons-penultimateColons );
  7289. }
  7290. return className;
  7291. }
  7292. } // end namespace Catch
  7293. // end catch_test_case_registry_impl.cpp
  7294. // start catch_test_case_tracker.cpp
  7295. #include <algorithm>
  7296. #include <assert.h>
  7297. #include <stdexcept>
  7298. #include <memory>
  7299. #if defined(__clang__)
  7300. # pragma clang diagnostic push
  7301. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  7302. #endif
  7303. namespace Catch {
  7304. namespace TestCaseTracking {
  7305. NameAndLocation::NameAndLocation( std::string const& _name, SourceLineInfo const& _location )
  7306. : name( _name ),
  7307. location( _location )
  7308. {}
  7309. ITracker::~ITracker() = default;
  7310. TrackerContext& TrackerContext::instance() {
  7311. static TrackerContext s_instance;
  7312. return s_instance;
  7313. }
  7314. ITracker& TrackerContext::startRun() {
  7315. m_rootTracker = std::make_shared<SectionTracker>( NameAndLocation( "{root}", CATCH_INTERNAL_LINEINFO ), *this, nullptr );
  7316. m_currentTracker = nullptr;
  7317. m_runState = Executing;
  7318. return *m_rootTracker;
  7319. }
  7320. void TrackerContext::endRun() {
  7321. m_rootTracker.reset();
  7322. m_currentTracker = nullptr;
  7323. m_runState = NotStarted;
  7324. }
  7325. void TrackerContext::startCycle() {
  7326. m_currentTracker = m_rootTracker.get();
  7327. m_runState = Executing;
  7328. }
  7329. void TrackerContext::completeCycle() {
  7330. m_runState = CompletedCycle;
  7331. }
  7332. bool TrackerContext::completedCycle() const {
  7333. return m_runState == CompletedCycle;
  7334. }
  7335. ITracker& TrackerContext::currentTracker() {
  7336. return *m_currentTracker;
  7337. }
  7338. void TrackerContext::setCurrentTracker( ITracker* tracker ) {
  7339. m_currentTracker = tracker;
  7340. }
  7341. TrackerBase::TrackerHasName::TrackerHasName( NameAndLocation const& nameAndLocation ) : m_nameAndLocation( nameAndLocation ) {}
  7342. bool TrackerBase::TrackerHasName::operator ()( ITrackerPtr const& tracker ) const {
  7343. return
  7344. tracker->nameAndLocation().name == m_nameAndLocation.name &&
  7345. tracker->nameAndLocation().location == m_nameAndLocation.location;
  7346. }
  7347. TrackerBase::TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  7348. : m_nameAndLocation( nameAndLocation ),
  7349. m_ctx( ctx ),
  7350. m_parent( parent )
  7351. {}
  7352. NameAndLocation const& TrackerBase::nameAndLocation() const {
  7353. return m_nameAndLocation;
  7354. }
  7355. bool TrackerBase::isComplete() const {
  7356. return m_runState == CompletedSuccessfully || m_runState == Failed;
  7357. }
  7358. bool TrackerBase::isSuccessfullyCompleted() const {
  7359. return m_runState == CompletedSuccessfully;
  7360. }
  7361. bool TrackerBase::isOpen() const {
  7362. return m_runState != NotStarted && !isComplete();
  7363. }
  7364. bool TrackerBase::hasChildren() const {
  7365. return !m_children.empty();
  7366. }
  7367. void TrackerBase::addChild( ITrackerPtr const& child ) {
  7368. m_children.push_back( child );
  7369. }
  7370. ITrackerPtr TrackerBase::findChild( NameAndLocation const& nameAndLocation ) {
  7371. auto it = std::find_if( m_children.begin(), m_children.end(), TrackerHasName( nameAndLocation ) );
  7372. return( it != m_children.end() )
  7373. ? *it
  7374. : nullptr;
  7375. }
  7376. ITracker& TrackerBase::parent() {
  7377. assert( m_parent ); // Should always be non-null except for root
  7378. return *m_parent;
  7379. }
  7380. void TrackerBase::openChild() {
  7381. if( m_runState != ExecutingChildren ) {
  7382. m_runState = ExecutingChildren;
  7383. if( m_parent )
  7384. m_parent->openChild();
  7385. }
  7386. }
  7387. bool TrackerBase::isSectionTracker() const { return false; }
  7388. bool TrackerBase::isIndexTracker() const { return false; }
  7389. void TrackerBase::open() {
  7390. m_runState = Executing;
  7391. moveToThis();
  7392. if( m_parent )
  7393. m_parent->openChild();
  7394. }
  7395. void TrackerBase::close() {
  7396. // Close any still open children (e.g. generators)
  7397. while( &m_ctx.currentTracker() != this )
  7398. m_ctx.currentTracker().close();
  7399. switch( m_runState ) {
  7400. case NeedsAnotherRun:
  7401. break;
  7402. case Executing:
  7403. m_runState = CompletedSuccessfully;
  7404. break;
  7405. case ExecutingChildren:
  7406. if( m_children.empty() || m_children.back()->isComplete() )
  7407. m_runState = CompletedSuccessfully;
  7408. break;
  7409. case NotStarted:
  7410. case CompletedSuccessfully:
  7411. case Failed:
  7412. CATCH_INTERNAL_ERROR( "Illogical state: " << m_runState );
  7413. default:
  7414. CATCH_INTERNAL_ERROR( "Unknown state: " << m_runState );
  7415. }
  7416. moveToParent();
  7417. m_ctx.completeCycle();
  7418. }
  7419. void TrackerBase::fail() {
  7420. m_runState = Failed;
  7421. if( m_parent )
  7422. m_parent->markAsNeedingAnotherRun();
  7423. moveToParent();
  7424. m_ctx.completeCycle();
  7425. }
  7426. void TrackerBase::markAsNeedingAnotherRun() {
  7427. m_runState = NeedsAnotherRun;
  7428. }
  7429. void TrackerBase::moveToParent() {
  7430. assert( m_parent );
  7431. m_ctx.setCurrentTracker( m_parent );
  7432. }
  7433. void TrackerBase::moveToThis() {
  7434. m_ctx.setCurrentTracker( this );
  7435. }
  7436. SectionTracker::SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  7437. : TrackerBase( nameAndLocation, ctx, parent )
  7438. {
  7439. if( parent ) {
  7440. while( !parent->isSectionTracker() )
  7441. parent = &parent->parent();
  7442. SectionTracker& parentSection = static_cast<SectionTracker&>( *parent );
  7443. addNextFilters( parentSection.m_filters );
  7444. }
  7445. }
  7446. bool SectionTracker::isSectionTracker() const { return true; }
  7447. SectionTracker& SectionTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ) {
  7448. std::shared_ptr<SectionTracker> section;
  7449. ITracker& currentTracker = ctx.currentTracker();
  7450. if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  7451. assert( childTracker );
  7452. assert( childTracker->isSectionTracker() );
  7453. section = std::static_pointer_cast<SectionTracker>( childTracker );
  7454. }
  7455. else {
  7456. section = std::make_shared<SectionTracker>( nameAndLocation, ctx, &currentTracker );
  7457. currentTracker.addChild( section );
  7458. }
  7459. if( !ctx.completedCycle() )
  7460. section->tryOpen();
  7461. return *section;
  7462. }
  7463. void SectionTracker::tryOpen() {
  7464. if( !isComplete() && (m_filters.empty() || m_filters[0].empty() || m_filters[0] == m_nameAndLocation.name ) )
  7465. open();
  7466. }
  7467. void SectionTracker::addInitialFilters( std::vector<std::string> const& filters ) {
  7468. if( !filters.empty() ) {
  7469. m_filters.push_back(""); // Root - should never be consulted
  7470. m_filters.push_back(""); // Test Case - not a section filter
  7471. m_filters.insert( m_filters.end(), filters.begin(), filters.end() );
  7472. }
  7473. }
  7474. void SectionTracker::addNextFilters( std::vector<std::string> const& filters ) {
  7475. if( filters.size() > 1 )
  7476. m_filters.insert( m_filters.end(), ++filters.begin(), filters.end() );
  7477. }
  7478. IndexTracker::IndexTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent, int size )
  7479. : TrackerBase( nameAndLocation, ctx, parent ),
  7480. m_size( size )
  7481. {}
  7482. bool IndexTracker::isIndexTracker() const { return true; }
  7483. IndexTracker& IndexTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation, int size ) {
  7484. std::shared_ptr<IndexTracker> tracker;
  7485. ITracker& currentTracker = ctx.currentTracker();
  7486. if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  7487. assert( childTracker );
  7488. assert( childTracker->isIndexTracker() );
  7489. tracker = std::static_pointer_cast<IndexTracker>( childTracker );
  7490. }
  7491. else {
  7492. tracker = std::make_shared<IndexTracker>( nameAndLocation, ctx, &currentTracker, size );
  7493. currentTracker.addChild( tracker );
  7494. }
  7495. if( !ctx.completedCycle() && !tracker->isComplete() ) {
  7496. if( tracker->m_runState != ExecutingChildren && tracker->m_runState != NeedsAnotherRun )
  7497. tracker->moveNext();
  7498. tracker->open();
  7499. }
  7500. return *tracker;
  7501. }
  7502. int IndexTracker::index() const { return m_index; }
  7503. void IndexTracker::moveNext() {
  7504. m_index++;
  7505. m_children.clear();
  7506. }
  7507. void IndexTracker::close() {
  7508. TrackerBase::close();
  7509. if( m_runState == CompletedSuccessfully && m_index < m_size-1 )
  7510. m_runState = Executing;
  7511. }
  7512. } // namespace TestCaseTracking
  7513. using TestCaseTracking::ITracker;
  7514. using TestCaseTracking::TrackerContext;
  7515. using TestCaseTracking::SectionTracker;
  7516. using TestCaseTracking::IndexTracker;
  7517. } // namespace Catch
  7518. #if defined(__clang__)
  7519. # pragma clang diagnostic pop
  7520. #endif
  7521. // end catch_test_case_tracker.cpp
  7522. // start catch_test_registry.cpp
  7523. namespace Catch {
  7524. auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker* {
  7525. return new(std::nothrow) TestInvokerAsFunction( testAsFunction );
  7526. }
  7527. NameAndTags::NameAndTags( StringRef name_ , StringRef tags_ ) noexcept : name( name_ ), tags( tags_ ) {}
  7528. AutoReg::AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef classOrMethod, NameAndTags const& nameAndTags ) noexcept {
  7529. try {
  7530. getMutableRegistryHub()
  7531. .registerTest(
  7532. makeTestCase(
  7533. invoker,
  7534. extractClassName( classOrMethod ),
  7535. nameAndTags.name,
  7536. nameAndTags.tags,
  7537. lineInfo));
  7538. } catch (...) {
  7539. // Do not throw when constructing global objects, instead register the exception to be processed later
  7540. getMutableRegistryHub().registerStartupException();
  7541. }
  7542. }
  7543. AutoReg::~AutoReg() = default;
  7544. }
  7545. // end catch_test_registry.cpp
  7546. // start catch_test_spec.cpp
  7547. #include <algorithm>
  7548. #include <string>
  7549. #include <vector>
  7550. #include <memory>
  7551. namespace Catch {
  7552. TestSpec::Pattern::~Pattern() = default;
  7553. TestSpec::NamePattern::~NamePattern() = default;
  7554. TestSpec::TagPattern::~TagPattern() = default;
  7555. TestSpec::ExcludedPattern::~ExcludedPattern() = default;
  7556. TestSpec::NamePattern::NamePattern( std::string const& name )
  7557. : m_wildcardPattern( toLower( name ), CaseSensitive::No )
  7558. {}
  7559. bool TestSpec::NamePattern::matches( TestCaseInfo const& testCase ) const {
  7560. return m_wildcardPattern.matches( toLower( testCase.name ) );
  7561. }
  7562. TestSpec::TagPattern::TagPattern( std::string const& tag ) : m_tag( toLower( tag ) ) {}
  7563. bool TestSpec::TagPattern::matches( TestCaseInfo const& testCase ) const {
  7564. return std::find(begin(testCase.lcaseTags),
  7565. end(testCase.lcaseTags),
  7566. m_tag) != end(testCase.lcaseTags);
  7567. }
  7568. TestSpec::ExcludedPattern::ExcludedPattern( PatternPtr const& underlyingPattern ) : m_underlyingPattern( underlyingPattern ) {}
  7569. bool TestSpec::ExcludedPattern::matches( TestCaseInfo const& testCase ) const { return !m_underlyingPattern->matches( testCase ); }
  7570. bool TestSpec::Filter::matches( TestCaseInfo const& testCase ) const {
  7571. // All patterns in a filter must match for the filter to be a match
  7572. for( auto const& pattern : m_patterns ) {
  7573. if( !pattern->matches( testCase ) )
  7574. return false;
  7575. }
  7576. return true;
  7577. }
  7578. bool TestSpec::hasFilters() const {
  7579. return !m_filters.empty();
  7580. }
  7581. bool TestSpec::matches( TestCaseInfo const& testCase ) const {
  7582. // A TestSpec matches if any filter matches
  7583. for( auto const& filter : m_filters )
  7584. if( filter.matches( testCase ) )
  7585. return true;
  7586. return false;
  7587. }
  7588. }
  7589. // end catch_test_spec.cpp
  7590. // start catch_test_spec_parser.cpp
  7591. namespace Catch {
  7592. TestSpecParser::TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {}
  7593. TestSpecParser& TestSpecParser::parse( std::string const& arg ) {
  7594. m_mode = None;
  7595. m_exclusion = false;
  7596. m_start = std::string::npos;
  7597. m_arg = m_tagAliases->expandAliases( arg );
  7598. m_escapeChars.clear();
  7599. for( m_pos = 0; m_pos < m_arg.size(); ++m_pos )
  7600. visitChar( m_arg[m_pos] );
  7601. if( m_mode == Name )
  7602. addPattern<TestSpec::NamePattern>();
  7603. return *this;
  7604. }
  7605. TestSpec TestSpecParser::testSpec() {
  7606. addFilter();
  7607. return m_testSpec;
  7608. }
  7609. void TestSpecParser::visitChar( char c ) {
  7610. if( m_mode == None ) {
  7611. switch( c ) {
  7612. case ' ': return;
  7613. case '~': m_exclusion = true; return;
  7614. case '[': return startNewMode( Tag, ++m_pos );
  7615. case '"': return startNewMode( QuotedName, ++m_pos );
  7616. case '\\': return escape();
  7617. default: startNewMode( Name, m_pos ); break;
  7618. }
  7619. }
  7620. if( m_mode == Name ) {
  7621. if( c == ',' ) {
  7622. addPattern<TestSpec::NamePattern>();
  7623. addFilter();
  7624. }
  7625. else if( c == '[' ) {
  7626. if( subString() == "exclude:" )
  7627. m_exclusion = true;
  7628. else
  7629. addPattern<TestSpec::NamePattern>();
  7630. startNewMode( Tag, ++m_pos );
  7631. }
  7632. else if( c == '\\' )
  7633. escape();
  7634. }
  7635. else if( m_mode == EscapedName )
  7636. m_mode = Name;
  7637. else if( m_mode == QuotedName && c == '"' )
  7638. addPattern<TestSpec::NamePattern>();
  7639. else if( m_mode == Tag && c == ']' )
  7640. addPattern<TestSpec::TagPattern>();
  7641. }
  7642. void TestSpecParser::startNewMode( Mode mode, std::size_t start ) {
  7643. m_mode = mode;
  7644. m_start = start;
  7645. }
  7646. void TestSpecParser::escape() {
  7647. if( m_mode == None )
  7648. m_start = m_pos;
  7649. m_mode = EscapedName;
  7650. m_escapeChars.push_back( m_pos );
  7651. }
  7652. std::string TestSpecParser::subString() const { return m_arg.substr( m_start, m_pos - m_start ); }
  7653. void TestSpecParser::addFilter() {
  7654. if( !m_currentFilter.m_patterns.empty() ) {
  7655. m_testSpec.m_filters.push_back( m_currentFilter );
  7656. m_currentFilter = TestSpec::Filter();
  7657. }
  7658. }
  7659. TestSpec parseTestSpec( std::string const& arg ) {
  7660. return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec();
  7661. }
  7662. } // namespace Catch
  7663. // end catch_test_spec_parser.cpp
  7664. // start catch_timer.cpp
  7665. #include <chrono>
  7666. namespace Catch {
  7667. auto getCurrentNanosecondsSinceEpoch() -> uint64_t {
  7668. return std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::high_resolution_clock::now().time_since_epoch() ).count();
  7669. }
  7670. auto estimateClockResolution() -> uint64_t {
  7671. uint64_t sum = 0;
  7672. static const uint64_t iterations = 1000000;
  7673. for( std::size_t i = 0; i < iterations; ++i ) {
  7674. uint64_t ticks;
  7675. uint64_t baseTicks = getCurrentNanosecondsSinceEpoch();
  7676. do {
  7677. ticks = getCurrentNanosecondsSinceEpoch();
  7678. }
  7679. while( ticks == baseTicks );
  7680. auto delta = ticks - baseTicks;
  7681. sum += delta;
  7682. }
  7683. // We're just taking the mean, here. To do better we could take the std. dev and exclude outliers
  7684. // - and potentially do more iterations if there's a high variance.
  7685. return sum/iterations;
  7686. }
  7687. auto getEstimatedClockResolution() -> uint64_t {
  7688. static auto s_resolution = estimateClockResolution();
  7689. return s_resolution;
  7690. }
  7691. void Timer::start() {
  7692. m_nanoseconds = getCurrentNanosecondsSinceEpoch();
  7693. }
  7694. auto Timer::getElapsedNanoseconds() const -> unsigned int {
  7695. return static_cast<unsigned int>(getCurrentNanosecondsSinceEpoch() - m_nanoseconds);
  7696. }
  7697. auto Timer::getElapsedMicroseconds() const -> unsigned int {
  7698. return static_cast<unsigned int>(getElapsedNanoseconds()/1000);
  7699. }
  7700. auto Timer::getElapsedMilliseconds() const -> unsigned int {
  7701. return static_cast<unsigned int>(getElapsedMicroseconds()/1000);
  7702. }
  7703. auto Timer::getElapsedSeconds() const -> double {
  7704. return getElapsedMicroseconds()/1000000.0;
  7705. }
  7706. } // namespace Catch
  7707. // end catch_timer.cpp
  7708. // start catch_tostring.cpp
  7709. #if defined(__clang__)
  7710. # pragma clang diagnostic push
  7711. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  7712. # pragma clang diagnostic ignored "-Wglobal-constructors"
  7713. #endif
  7714. #include <iomanip>
  7715. namespace Catch {
  7716. namespace Detail {
  7717. const std::string unprintableString = "{?}";
  7718. namespace {
  7719. const int hexThreshold = 255;
  7720. struct Endianness {
  7721. enum Arch { Big, Little };
  7722. static Arch which() {
  7723. union _{
  7724. int asInt;
  7725. char asChar[sizeof (int)];
  7726. } u;
  7727. u.asInt = 1;
  7728. return ( u.asChar[sizeof(int)-1] == 1 ) ? Big : Little;
  7729. }
  7730. };
  7731. }
  7732. std::string rawMemoryToString( const void *object, std::size_t size ) {
  7733. // Reverse order for little endian architectures
  7734. int i = 0, end = static_cast<int>( size ), inc = 1;
  7735. if( Endianness::which() == Endianness::Little ) {
  7736. i = end-1;
  7737. end = inc = -1;
  7738. }
  7739. unsigned char const *bytes = static_cast<unsigned char const *>(object);
  7740. std::ostringstream os;
  7741. os << "0x" << std::setfill('0') << std::hex;
  7742. for( ; i != end; i += inc )
  7743. os << std::setw(2) << static_cast<unsigned>(bytes[i]);
  7744. return os.str();
  7745. }
  7746. }
  7747. template<typename T>
  7748. std::string fpToString( T value, int precision ) {
  7749. std::ostringstream oss;
  7750. oss << std::setprecision( precision )
  7751. << std::fixed
  7752. << value;
  7753. std::string d = oss.str();
  7754. std::size_t i = d.find_last_not_of( '0' );
  7755. if( i != std::string::npos && i != d.size()-1 ) {
  7756. if( d[i] == '.' )
  7757. i++;
  7758. d = d.substr( 0, i+1 );
  7759. }
  7760. return d;
  7761. }
  7762. //// ======================================================= ////
  7763. //
  7764. // Out-of-line defs for full specialization of StringMaker
  7765. //
  7766. //// ======================================================= ////
  7767. std::string StringMaker<std::string>::convert(const std::string& str) {
  7768. if (!getCurrentContext().getConfig()->showInvisibles()) {
  7769. return '"' + str + '"';
  7770. }
  7771. std::string s("\"");
  7772. for (char c : str) {
  7773. switch (c) {
  7774. case '\n':
  7775. s.append("\\n");
  7776. break;
  7777. case '\t':
  7778. s.append("\\t");
  7779. break;
  7780. default:
  7781. s.push_back(c);
  7782. break;
  7783. }
  7784. }
  7785. s.append("\"");
  7786. return s;
  7787. }
  7788. std::string StringMaker<std::wstring>::convert(const std::wstring& wstr) {
  7789. std::string s;
  7790. s.reserve(wstr.size());
  7791. for (auto c : wstr) {
  7792. s += (c <= 0xff) ? static_cast<char>(c) : '?';
  7793. }
  7794. return ::Catch::Detail::stringify(s);
  7795. }
  7796. std::string StringMaker<char const*>::convert(char const* str) {
  7797. if (str) {
  7798. return ::Catch::Detail::stringify(std::string{ str });
  7799. } else {
  7800. return{ "{null string}" };
  7801. }
  7802. }
  7803. std::string StringMaker<char*>::convert(char* str) {
  7804. if (str) {
  7805. return ::Catch::Detail::stringify(std::string{ str });
  7806. } else {
  7807. return{ "{null string}" };
  7808. }
  7809. }
  7810. std::string StringMaker<wchar_t const*>::convert(wchar_t const * str) {
  7811. if (str) {
  7812. return ::Catch::Detail::stringify(std::wstring{ str });
  7813. } else {
  7814. return{ "{null string}" };
  7815. }
  7816. }
  7817. std::string StringMaker<wchar_t *>::convert(wchar_t * str) {
  7818. if (str) {
  7819. return ::Catch::Detail::stringify(std::wstring{ str });
  7820. } else {
  7821. return{ "{null string}" };
  7822. }
  7823. }
  7824. std::string StringMaker<int>::convert(int value) {
  7825. return ::Catch::Detail::stringify(static_cast<long long>(value));
  7826. }
  7827. std::string StringMaker<long>::convert(long value) {
  7828. return ::Catch::Detail::stringify(static_cast<long long>(value));
  7829. }
  7830. std::string StringMaker<long long>::convert(long long value) {
  7831. std::ostringstream oss;
  7832. oss << value;
  7833. if (value > Detail::hexThreshold) {
  7834. oss << " (0x" << std::hex << value << ')';
  7835. }
  7836. return oss.str();
  7837. }
  7838. std::string StringMaker<unsigned int>::convert(unsigned int value) {
  7839. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  7840. }
  7841. std::string StringMaker<unsigned long>::convert(unsigned long value) {
  7842. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  7843. }
  7844. std::string StringMaker<unsigned long long>::convert(unsigned long long value) {
  7845. std::ostringstream oss;
  7846. oss << value;
  7847. if (value > Detail::hexThreshold) {
  7848. oss << " (0x" << std::hex << value << ')';
  7849. }
  7850. return oss.str();
  7851. }
  7852. std::string StringMaker<bool>::convert(bool b) {
  7853. return b ? "true" : "false";
  7854. }
  7855. std::string StringMaker<char>::convert(char value) {
  7856. if (value == '\r') {
  7857. return "'\\r'";
  7858. } else if (value == '\f') {
  7859. return "'\\f'";
  7860. } else if (value == '\n') {
  7861. return "'\\n'";
  7862. } else if (value == '\t') {
  7863. return "'\\t'";
  7864. } else if ('\0' <= value && value < ' ') {
  7865. return ::Catch::Detail::stringify(static_cast<unsigned int>(value));
  7866. } else {
  7867. char chstr[] = "' '";
  7868. chstr[1] = value;
  7869. return chstr;
  7870. }
  7871. }
  7872. std::string StringMaker<signed char>::convert(signed char c) {
  7873. return ::Catch::Detail::stringify(static_cast<char>(c));
  7874. }
  7875. std::string StringMaker<unsigned char>::convert(unsigned char c) {
  7876. return ::Catch::Detail::stringify(static_cast<char>(c));
  7877. }
  7878. std::string StringMaker<std::nullptr_t>::convert(std::nullptr_t) {
  7879. return "nullptr";
  7880. }
  7881. std::string StringMaker<float>::convert(float value) {
  7882. return fpToString(value, 5) + 'f';
  7883. }
  7884. std::string StringMaker<double>::convert(double value) {
  7885. return fpToString(value, 10);
  7886. }
  7887. } // end namespace Catch
  7888. #if defined(__clang__)
  7889. # pragma clang diagnostic pop
  7890. #endif
  7891. // end catch_tostring.cpp
  7892. // start catch_totals.cpp
  7893. namespace Catch {
  7894. Counts Counts::operator - ( Counts const& other ) const {
  7895. Counts diff;
  7896. diff.passed = passed - other.passed;
  7897. diff.failed = failed - other.failed;
  7898. diff.failedButOk = failedButOk - other.failedButOk;
  7899. return diff;
  7900. }
  7901. Counts& Counts::operator += ( Counts const& other ) {
  7902. passed += other.passed;
  7903. failed += other.failed;
  7904. failedButOk += other.failedButOk;
  7905. return *this;
  7906. }
  7907. std::size_t Counts::total() const {
  7908. return passed + failed + failedButOk;
  7909. }
  7910. bool Counts::allPassed() const {
  7911. return failed == 0 && failedButOk == 0;
  7912. }
  7913. bool Counts::allOk() const {
  7914. return failed == 0;
  7915. }
  7916. Totals Totals::operator - ( Totals const& other ) const {
  7917. Totals diff;
  7918. diff.assertions = assertions - other.assertions;
  7919. diff.testCases = testCases - other.testCases;
  7920. return diff;
  7921. }
  7922. Totals& Totals::operator += ( Totals const& other ) {
  7923. assertions += other.assertions;
  7924. testCases += other.testCases;
  7925. return *this;
  7926. }
  7927. Totals Totals::delta( Totals const& prevTotals ) const {
  7928. Totals diff = *this - prevTotals;
  7929. if( diff.assertions.failed > 0 )
  7930. ++diff.testCases.failed;
  7931. else if( diff.assertions.failedButOk > 0 )
  7932. ++diff.testCases.failedButOk;
  7933. else
  7934. ++diff.testCases.passed;
  7935. return diff;
  7936. }
  7937. }
  7938. // end catch_totals.cpp
  7939. // start catch_version.cpp
  7940. #include <ostream>
  7941. namespace Catch {
  7942. Version::Version
  7943. ( unsigned int _majorVersion,
  7944. unsigned int _minorVersion,
  7945. unsigned int _patchNumber,
  7946. char const * const _branchName,
  7947. unsigned int _buildNumber )
  7948. : majorVersion( _majorVersion ),
  7949. minorVersion( _minorVersion ),
  7950. patchNumber( _patchNumber ),
  7951. branchName( _branchName ),
  7952. buildNumber( _buildNumber )
  7953. {}
  7954. std::ostream& operator << ( std::ostream& os, Version const& version ) {
  7955. os << version.majorVersion << '.'
  7956. << version.minorVersion << '.'
  7957. << version.patchNumber;
  7958. // branchName is never null -> 0th char is \0 if it is empty
  7959. if (version.branchName[0]) {
  7960. os << '-' << version.branchName
  7961. << '.' << version.buildNumber;
  7962. }
  7963. return os;
  7964. }
  7965. Version const& libraryVersion() {
  7966. static Version version( 2, 0, 1, "", 0 );
  7967. return version;
  7968. }
  7969. }
  7970. // end catch_version.cpp
  7971. // start catch_wildcard_pattern.cpp
  7972. namespace Catch {
  7973. WildcardPattern::WildcardPattern( std::string const& pattern,
  7974. CaseSensitive::Choice caseSensitivity )
  7975. : m_caseSensitivity( caseSensitivity ),
  7976. m_pattern( adjustCase( pattern ) )
  7977. {
  7978. if( startsWith( m_pattern, '*' ) ) {
  7979. m_pattern = m_pattern.substr( 1 );
  7980. m_wildcard = WildcardAtStart;
  7981. }
  7982. if( endsWith( m_pattern, '*' ) ) {
  7983. m_pattern = m_pattern.substr( 0, m_pattern.size()-1 );
  7984. m_wildcard = static_cast<WildcardPosition>( m_wildcard | WildcardAtEnd );
  7985. }
  7986. }
  7987. bool WildcardPattern::matches( std::string const& str ) const {
  7988. switch( m_wildcard ) {
  7989. case NoWildcard:
  7990. return m_pattern == adjustCase( str );
  7991. case WildcardAtStart:
  7992. return endsWith( adjustCase( str ), m_pattern );
  7993. case WildcardAtEnd:
  7994. return startsWith( adjustCase( str ), m_pattern );
  7995. case WildcardAtBothEnds:
  7996. return contains( adjustCase( str ), m_pattern );
  7997. default:
  7998. CATCH_INTERNAL_ERROR( "Unknown enum" );
  7999. }
  8000. }
  8001. std::string WildcardPattern::adjustCase( std::string const& str ) const {
  8002. return m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str;
  8003. }
  8004. }
  8005. // end catch_wildcard_pattern.cpp
  8006. // start catch_xmlwriter.cpp
  8007. // start catch_xmlwriter.h
  8008. #include <sstream>
  8009. #include <vector>
  8010. namespace Catch {
  8011. class XmlEncode {
  8012. public:
  8013. enum ForWhat { ForTextNodes, ForAttributes };
  8014. XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes );
  8015. void encodeTo( std::ostream& os ) const;
  8016. friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode );
  8017. private:
  8018. std::string m_str;
  8019. ForWhat m_forWhat;
  8020. };
  8021. class XmlWriter {
  8022. public:
  8023. class ScopedElement {
  8024. public:
  8025. ScopedElement( XmlWriter* writer );
  8026. ScopedElement( ScopedElement&& other ) noexcept;
  8027. ScopedElement& operator=( ScopedElement&& other ) noexcept;
  8028. ~ScopedElement();
  8029. ScopedElement& writeText( std::string const& text, bool indent = true );
  8030. template<typename T>
  8031. ScopedElement& writeAttribute( std::string const& name, T const& attribute ) {
  8032. m_writer->writeAttribute( name, attribute );
  8033. return *this;
  8034. }
  8035. private:
  8036. mutable XmlWriter* m_writer = nullptr;
  8037. };
  8038. XmlWriter( std::ostream& os = Catch::cout() );
  8039. ~XmlWriter();
  8040. XmlWriter( XmlWriter const& ) = delete;
  8041. XmlWriter& operator=( XmlWriter const& ) = delete;
  8042. XmlWriter& startElement( std::string const& name );
  8043. ScopedElement scopedElement( std::string const& name );
  8044. XmlWriter& endElement();
  8045. XmlWriter& writeAttribute( std::string const& name, std::string const& attribute );
  8046. XmlWriter& writeAttribute( std::string const& name, bool attribute );
  8047. template<typename T>
  8048. XmlWriter& writeAttribute( std::string const& name, T const& attribute ) {
  8049. m_oss.clear();
  8050. m_oss.str(std::string());
  8051. m_oss << attribute;
  8052. return writeAttribute( name, m_oss.str() );
  8053. }
  8054. XmlWriter& writeText( std::string const& text, bool indent = true );
  8055. XmlWriter& writeComment( std::string const& text );
  8056. void writeStylesheetRef( std::string const& url );
  8057. XmlWriter& writeBlankLine();
  8058. void ensureTagClosed();
  8059. private:
  8060. void writeDeclaration();
  8061. void newlineIfNecessary();
  8062. bool m_tagIsOpen = false;
  8063. bool m_needsNewline = false;
  8064. std::vector<std::string> m_tags;
  8065. std::string m_indent;
  8066. std::ostream& m_os;
  8067. std::ostringstream m_oss;
  8068. };
  8069. }
  8070. // end catch_xmlwriter.h
  8071. #include <iomanip>
  8072. namespace Catch {
  8073. XmlEncode::XmlEncode( std::string const& str, ForWhat forWhat )
  8074. : m_str( str ),
  8075. m_forWhat( forWhat )
  8076. {}
  8077. void XmlEncode::encodeTo( std::ostream& os ) const {
  8078. // Apostrophe escaping not necessary if we always use " to write attributes
  8079. // (see: http://www.w3.org/TR/xml/#syntax)
  8080. for( std::size_t i = 0; i < m_str.size(); ++ i ) {
  8081. char c = m_str[i];
  8082. switch( c ) {
  8083. case '<': os << "&lt;"; break;
  8084. case '&': os << "&amp;"; break;
  8085. case '>':
  8086. // See: http://www.w3.org/TR/xml/#syntax
  8087. if( i > 2 && m_str[i-1] == ']' && m_str[i-2] == ']' )
  8088. os << "&gt;";
  8089. else
  8090. os << c;
  8091. break;
  8092. case '\"':
  8093. if( m_forWhat == ForAttributes )
  8094. os << "&quot;";
  8095. else
  8096. os << c;
  8097. break;
  8098. default:
  8099. // Escape control chars - based on contribution by @espenalb in PR #465 and
  8100. // by @mrpi PR #588
  8101. if ( ( c >= 0 && c < '\x09' ) || ( c > '\x0D' && c < '\x20') || c=='\x7F' ) {
  8102. // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0
  8103. os << "\\x" << std::uppercase << std::hex << std::setfill('0') << std::setw(2)
  8104. << static_cast<int>( c );
  8105. }
  8106. else
  8107. os << c;
  8108. }
  8109. }
  8110. }
  8111. std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) {
  8112. xmlEncode.encodeTo( os );
  8113. return os;
  8114. }
  8115. XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer )
  8116. : m_writer( writer )
  8117. {}
  8118. XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept
  8119. : m_writer( other.m_writer ){
  8120. other.m_writer = nullptr;
  8121. }
  8122. XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) noexcept {
  8123. if ( m_writer ) {
  8124. m_writer->endElement();
  8125. }
  8126. m_writer = other.m_writer;
  8127. other.m_writer = nullptr;
  8128. return *this;
  8129. }
  8130. XmlWriter::ScopedElement::~ScopedElement() {
  8131. if( m_writer )
  8132. m_writer->endElement();
  8133. }
  8134. XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string const& text, bool indent ) {
  8135. m_writer->writeText( text, indent );
  8136. return *this;
  8137. }
  8138. XmlWriter::XmlWriter( std::ostream& os ) : m_os( os )
  8139. {
  8140. writeDeclaration();
  8141. }
  8142. XmlWriter::~XmlWriter() {
  8143. while( !m_tags.empty() )
  8144. endElement();
  8145. }
  8146. XmlWriter& XmlWriter::startElement( std::string const& name ) {
  8147. ensureTagClosed();
  8148. newlineIfNecessary();
  8149. m_os << m_indent << '<' << name;
  8150. m_tags.push_back( name );
  8151. m_indent += " ";
  8152. m_tagIsOpen = true;
  8153. return *this;
  8154. }
  8155. XmlWriter::ScopedElement XmlWriter::scopedElement( std::string const& name ) {
  8156. ScopedElement scoped( this );
  8157. startElement( name );
  8158. return scoped;
  8159. }
  8160. XmlWriter& XmlWriter::endElement() {
  8161. newlineIfNecessary();
  8162. m_indent = m_indent.substr( 0, m_indent.size()-2 );
  8163. if( m_tagIsOpen ) {
  8164. m_os << "/>";
  8165. m_tagIsOpen = false;
  8166. }
  8167. else {
  8168. m_os << m_indent << "</" << m_tags.back() << ">";
  8169. }
  8170. m_os << std::endl;
  8171. m_tags.pop_back();
  8172. return *this;
  8173. }
  8174. XmlWriter& XmlWriter::writeAttribute( std::string const& name, std::string const& attribute ) {
  8175. if( !name.empty() && !attribute.empty() )
  8176. m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"';
  8177. return *this;
  8178. }
  8179. XmlWriter& XmlWriter::writeAttribute( std::string const& name, bool attribute ) {
  8180. m_os << ' ' << name << "=\"" << ( attribute ? "true" : "false" ) << '"';
  8181. return *this;
  8182. }
  8183. XmlWriter& XmlWriter::writeText( std::string const& text, bool indent ) {
  8184. if( !text.empty() ){
  8185. bool tagWasOpen = m_tagIsOpen;
  8186. ensureTagClosed();
  8187. if( tagWasOpen && indent )
  8188. m_os << m_indent;
  8189. m_os << XmlEncode( text );
  8190. m_needsNewline = true;
  8191. }
  8192. return *this;
  8193. }
  8194. XmlWriter& XmlWriter::writeComment( std::string const& text ) {
  8195. ensureTagClosed();
  8196. m_os << m_indent << "<!--" << text << "-->";
  8197. m_needsNewline = true;
  8198. return *this;
  8199. }
  8200. void XmlWriter::writeStylesheetRef( std::string const& url ) {
  8201. m_os << "<?xml-stylesheet type=\"text/xsl\" href=\"" << url << "\"?>\n";
  8202. }
  8203. XmlWriter& XmlWriter::writeBlankLine() {
  8204. ensureTagClosed();
  8205. m_os << '\n';
  8206. return *this;
  8207. }
  8208. void XmlWriter::ensureTagClosed() {
  8209. if( m_tagIsOpen ) {
  8210. m_os << ">" << std::endl;
  8211. m_tagIsOpen = false;
  8212. }
  8213. }
  8214. void XmlWriter::writeDeclaration() {
  8215. m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
  8216. }
  8217. void XmlWriter::newlineIfNecessary() {
  8218. if( m_needsNewline ) {
  8219. m_os << std::endl;
  8220. m_needsNewline = false;
  8221. }
  8222. }
  8223. }
  8224. // end catch_xmlwriter.cpp
  8225. // start catch_reporter_bases.cpp
  8226. #include <cstring>
  8227. #include <cfloat>
  8228. #include <cstdio>
  8229. #include <assert.h>
  8230. #include <memory>
  8231. namespace Catch {
  8232. void prepareExpandedExpression(AssertionResult& result) {
  8233. result.getExpandedExpression();
  8234. }
  8235. // Because formatting using c++ streams is stateful, drop down to C is required
  8236. // Alternatively we could use stringstream, but its performance is... not good.
  8237. std::string getFormattedDuration( double duration ) {
  8238. // Max exponent + 1 is required to represent the whole part
  8239. // + 1 for decimal point
  8240. // + 3 for the 3 decimal places
  8241. // + 1 for null terminator
  8242. const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1;
  8243. char buffer[maxDoubleSize];
  8244. // Save previous errno, to prevent sprintf from overwriting it
  8245. ErrnoGuard guard;
  8246. #ifdef _MSC_VER
  8247. sprintf_s(buffer, "%.3f", duration);
  8248. #else
  8249. sprintf(buffer, "%.3f", duration);
  8250. #endif
  8251. return std::string(buffer);
  8252. }
  8253. TestEventListenerBase::TestEventListenerBase(ReporterConfig const & _config)
  8254. :StreamingReporterBase(_config) {}
  8255. void TestEventListenerBase::assertionStarting(AssertionInfo const &) {}
  8256. bool TestEventListenerBase::assertionEnded(AssertionStats const &) {
  8257. return false;
  8258. }
  8259. } // end namespace Catch
  8260. // end catch_reporter_bases.cpp
  8261. // start catch_reporter_compact.cpp
  8262. namespace {
  8263. #ifdef CATCH_PLATFORM_MAC
  8264. const char* failedString() { return "FAILED"; }
  8265. const char* passedString() { return "PASSED"; }
  8266. #else
  8267. const char* failedString() { return "failed"; }
  8268. const char* passedString() { return "passed"; }
  8269. #endif
  8270. // Colour::LightGrey
  8271. Catch::Colour::Code dimColour() { return Catch::Colour::FileName; }
  8272. std::string bothOrAll( std::size_t count ) {
  8273. return count == 1 ? std::string() :
  8274. count == 2 ? "both " : "all " ;
  8275. }
  8276. }
  8277. namespace Catch {
  8278. struct CompactReporter : StreamingReporterBase<CompactReporter> {
  8279. using StreamingReporterBase::StreamingReporterBase;
  8280. ~CompactReporter() override;
  8281. static std::string getDescription() {
  8282. return "Reports test results on a single line, suitable for IDEs";
  8283. }
  8284. ReporterPreferences getPreferences() const override {
  8285. ReporterPreferences prefs;
  8286. prefs.shouldRedirectStdOut = false;
  8287. return prefs;
  8288. }
  8289. void noMatchingTestCases( std::string const& spec ) override {
  8290. stream << "No test cases matched '" << spec << '\'' << std::endl;
  8291. }
  8292. void assertionStarting( AssertionInfo const& ) override {}
  8293. bool assertionEnded( AssertionStats const& _assertionStats ) override {
  8294. AssertionResult const& result = _assertionStats.assertionResult;
  8295. bool printInfoMessages = true;
  8296. // Drop out if result was successful and we're not printing those
  8297. if( !m_config->includeSuccessfulResults() && result.isOk() ) {
  8298. if( result.getResultType() != ResultWas::Warning )
  8299. return false;
  8300. printInfoMessages = false;
  8301. }
  8302. AssertionPrinter printer( stream, _assertionStats, printInfoMessages );
  8303. printer.print();
  8304. stream << std::endl;
  8305. return true;
  8306. }
  8307. void sectionEnded(SectionStats const& _sectionStats) override {
  8308. if (m_config->showDurations() == ShowDurations::Always) {
  8309. stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  8310. }
  8311. }
  8312. void testRunEnded( TestRunStats const& _testRunStats ) override {
  8313. printTotals( _testRunStats.totals );
  8314. stream << '\n' << std::endl;
  8315. StreamingReporterBase::testRunEnded( _testRunStats );
  8316. }
  8317. private:
  8318. class AssertionPrinter {
  8319. public:
  8320. AssertionPrinter& operator= ( AssertionPrinter const& ) = delete;
  8321. AssertionPrinter( AssertionPrinter const& ) = delete;
  8322. AssertionPrinter( std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages )
  8323. : stream( _stream )
  8324. , result( _stats.assertionResult )
  8325. , messages( _stats.infoMessages )
  8326. , itMessage( _stats.infoMessages.begin() )
  8327. , printInfoMessages( _printInfoMessages )
  8328. {}
  8329. void print() {
  8330. printSourceInfo();
  8331. itMessage = messages.begin();
  8332. switch( result.getResultType() ) {
  8333. case ResultWas::Ok:
  8334. printResultType( Colour::ResultSuccess, passedString() );
  8335. printOriginalExpression();
  8336. printReconstructedExpression();
  8337. if ( ! result.hasExpression() )
  8338. printRemainingMessages( Colour::None );
  8339. else
  8340. printRemainingMessages();
  8341. break;
  8342. case ResultWas::ExpressionFailed:
  8343. if( result.isOk() )
  8344. printResultType( Colour::ResultSuccess, failedString() + std::string( " - but was ok" ) );
  8345. else
  8346. printResultType( Colour::Error, failedString() );
  8347. printOriginalExpression();
  8348. printReconstructedExpression();
  8349. printRemainingMessages();
  8350. break;
  8351. case ResultWas::ThrewException:
  8352. printResultType( Colour::Error, failedString() );
  8353. printIssue( "unexpected exception with message:" );
  8354. printMessage();
  8355. printExpressionWas();
  8356. printRemainingMessages();
  8357. break;
  8358. case ResultWas::FatalErrorCondition:
  8359. printResultType( Colour::Error, failedString() );
  8360. printIssue( "fatal error condition with message:" );
  8361. printMessage();
  8362. printExpressionWas();
  8363. printRemainingMessages();
  8364. break;
  8365. case ResultWas::DidntThrowException:
  8366. printResultType( Colour::Error, failedString() );
  8367. printIssue( "expected exception, got none" );
  8368. printExpressionWas();
  8369. printRemainingMessages();
  8370. break;
  8371. case ResultWas::Info:
  8372. printResultType( Colour::None, "info" );
  8373. printMessage();
  8374. printRemainingMessages();
  8375. break;
  8376. case ResultWas::Warning:
  8377. printResultType( Colour::None, "warning" );
  8378. printMessage();
  8379. printRemainingMessages();
  8380. break;
  8381. case ResultWas::ExplicitFailure:
  8382. printResultType( Colour::Error, failedString() );
  8383. printIssue( "explicitly" );
  8384. printRemainingMessages( Colour::None );
  8385. break;
  8386. // These cases are here to prevent compiler warnings
  8387. case ResultWas::Unknown:
  8388. case ResultWas::FailureBit:
  8389. case ResultWas::Exception:
  8390. printResultType( Colour::Error, "** internal error **" );
  8391. break;
  8392. }
  8393. }
  8394. private:
  8395. void printSourceInfo() const {
  8396. Colour colourGuard( Colour::FileName );
  8397. stream << result.getSourceInfo() << ':';
  8398. }
  8399. void printResultType( Colour::Code colour, std::string const& passOrFail ) const {
  8400. if( !passOrFail.empty() ) {
  8401. {
  8402. Colour colourGuard( colour );
  8403. stream << ' ' << passOrFail;
  8404. }
  8405. stream << ':';
  8406. }
  8407. }
  8408. void printIssue( std::string const& issue ) const {
  8409. stream << ' ' << issue;
  8410. }
  8411. void printExpressionWas() {
  8412. if( result.hasExpression() ) {
  8413. stream << ';';
  8414. {
  8415. Colour colour( dimColour() );
  8416. stream << " expression was:";
  8417. }
  8418. printOriginalExpression();
  8419. }
  8420. }
  8421. void printOriginalExpression() const {
  8422. if( result.hasExpression() ) {
  8423. stream << ' ' << result.getExpression();
  8424. }
  8425. }
  8426. void printReconstructedExpression() const {
  8427. if( result.hasExpandedExpression() ) {
  8428. {
  8429. Colour colour( dimColour() );
  8430. stream << " for: ";
  8431. }
  8432. stream << result.getExpandedExpression();
  8433. }
  8434. }
  8435. void printMessage() {
  8436. if ( itMessage != messages.end() ) {
  8437. stream << " '" << itMessage->message << '\'';
  8438. ++itMessage;
  8439. }
  8440. }
  8441. void printRemainingMessages( Colour::Code colour = dimColour() ) {
  8442. if ( itMessage == messages.end() )
  8443. return;
  8444. // using messages.end() directly yields (or auto) compilation error:
  8445. std::vector<MessageInfo>::const_iterator itEnd = messages.end();
  8446. const std::size_t N = static_cast<std::size_t>( std::distance( itMessage, itEnd ) );
  8447. {
  8448. Colour colourGuard( colour );
  8449. stream << " with " << pluralise( N, "message" ) << ':';
  8450. }
  8451. for(; itMessage != itEnd; ) {
  8452. // If this assertion is a warning ignore any INFO messages
  8453. if( printInfoMessages || itMessage->type != ResultWas::Info ) {
  8454. stream << " '" << itMessage->message << '\'';
  8455. if ( ++itMessage != itEnd ) {
  8456. Colour colourGuard( dimColour() );
  8457. stream << " and";
  8458. }
  8459. }
  8460. }
  8461. }
  8462. private:
  8463. std::ostream& stream;
  8464. AssertionResult const& result;
  8465. std::vector<MessageInfo> messages;
  8466. std::vector<MessageInfo>::const_iterator itMessage;
  8467. bool printInfoMessages;
  8468. };
  8469. // Colour, message variants:
  8470. // - white: No tests ran.
  8471. // - red: Failed [both/all] N test cases, failed [both/all] M assertions.
  8472. // - white: Passed [both/all] N test cases (no assertions).
  8473. // - red: Failed N tests cases, failed M assertions.
  8474. // - green: Passed [both/all] N tests cases with M assertions.
  8475. void printTotals( const Totals& totals ) const {
  8476. if( totals.testCases.total() == 0 ) {
  8477. stream << "No tests ran.";
  8478. }
  8479. else if( totals.testCases.failed == totals.testCases.total() ) {
  8480. Colour colour( Colour::ResultError );
  8481. const std::string qualify_assertions_failed =
  8482. totals.assertions.failed == totals.assertions.total() ?
  8483. bothOrAll( totals.assertions.failed ) : std::string();
  8484. stream <<
  8485. "Failed " << bothOrAll( totals.testCases.failed )
  8486. << pluralise( totals.testCases.failed, "test case" ) << ", "
  8487. "failed " << qualify_assertions_failed <<
  8488. pluralise( totals.assertions.failed, "assertion" ) << '.';
  8489. }
  8490. else if( totals.assertions.total() == 0 ) {
  8491. stream <<
  8492. "Passed " << bothOrAll( totals.testCases.total() )
  8493. << pluralise( totals.testCases.total(), "test case" )
  8494. << " (no assertions).";
  8495. }
  8496. else if( totals.assertions.failed ) {
  8497. Colour colour( Colour::ResultError );
  8498. stream <<
  8499. "Failed " << pluralise( totals.testCases.failed, "test case" ) << ", "
  8500. "failed " << pluralise( totals.assertions.failed, "assertion" ) << '.';
  8501. }
  8502. else {
  8503. Colour colour( Colour::ResultSuccess );
  8504. stream <<
  8505. "Passed " << bothOrAll( totals.testCases.passed )
  8506. << pluralise( totals.testCases.passed, "test case" ) <<
  8507. " with " << pluralise( totals.assertions.passed, "assertion" ) << '.';
  8508. }
  8509. }
  8510. };
  8511. CompactReporter::~CompactReporter() {}
  8512. CATCH_REGISTER_REPORTER( "compact", CompactReporter )
  8513. } // end namespace Catch
  8514. // end catch_reporter_compact.cpp
  8515. // start catch_reporter_console.cpp
  8516. #include <cfloat>
  8517. #include <cstdio>
  8518. #if defined(_MSC_VER)
  8519. #pragma warning(push)
  8520. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  8521. // Note that 4062 (not all labels are handled
  8522. // and default is missing) is enabled
  8523. #endif
  8524. namespace Catch {
  8525. namespace {
  8526. std::size_t makeRatio( std::size_t number, std::size_t total ) {
  8527. std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number/ total : 0;
  8528. return ( ratio == 0 && number > 0 ) ? 1 : ratio;
  8529. }
  8530. std::size_t& findMax( std::size_t& i, std::size_t& j, std::size_t& k ) {
  8531. if( i > j && i > k )
  8532. return i;
  8533. else if( j > k )
  8534. return j;
  8535. else
  8536. return k;
  8537. }
  8538. struct ColumnInfo {
  8539. enum Justification { Left, Right };
  8540. std::string name;
  8541. int width;
  8542. Justification justification;
  8543. };
  8544. struct ColumnBreak {};
  8545. struct RowBreak {};
  8546. class TablePrinter {
  8547. std::ostream& m_os;
  8548. std::vector<ColumnInfo> m_columnInfos;
  8549. std::ostringstream m_oss;
  8550. int m_currentColumn = -1;
  8551. bool m_isOpen = false;
  8552. public:
  8553. TablePrinter( std::ostream& os, std::vector<ColumnInfo> const& columnInfos )
  8554. : m_os( os ),
  8555. m_columnInfos( columnInfos )
  8556. {}
  8557. auto columnInfos() const -> std::vector<ColumnInfo> const& {
  8558. return m_columnInfos;
  8559. }
  8560. void open() {
  8561. if( !m_isOpen ) {
  8562. m_isOpen = true;
  8563. *this << RowBreak();
  8564. for( auto const& info : m_columnInfos )
  8565. *this << info.name << ColumnBreak();
  8566. *this << RowBreak();
  8567. m_os << Catch::getLineOfChars<'-'>() << "\n";
  8568. }
  8569. }
  8570. void close() {
  8571. if( m_isOpen ) {
  8572. *this << RowBreak();
  8573. m_os << std::endl;
  8574. m_isOpen = false;
  8575. }
  8576. }
  8577. template<typename T>
  8578. friend TablePrinter& operator << ( TablePrinter& tp, T const& value ) {
  8579. tp.m_oss << value;
  8580. return tp;
  8581. }
  8582. friend TablePrinter& operator << ( TablePrinter& tp, ColumnBreak ) {
  8583. auto colStr = tp.m_oss.str();
  8584. // This takes account of utf8 encodings
  8585. auto strSize = Catch::StringRef( colStr ).numberOfCharacters();
  8586. tp.m_oss.str("");
  8587. tp.open();
  8588. if( tp.m_currentColumn == static_cast<int>(tp.m_columnInfos.size()-1) ) {
  8589. tp.m_currentColumn = -1;
  8590. tp.m_os << "\n";
  8591. }
  8592. tp.m_currentColumn++;
  8593. auto colInfo = tp.m_columnInfos[tp.m_currentColumn];
  8594. auto padding = ( strSize+2 < static_cast<std::size_t>( colInfo.width ) )
  8595. ? std::string( colInfo.width-(strSize+2), ' ' )
  8596. : std::string();
  8597. if( colInfo.justification == ColumnInfo::Left )
  8598. tp.m_os << colStr << padding << " ";
  8599. else
  8600. tp.m_os << padding << colStr << " ";
  8601. return tp;
  8602. }
  8603. friend TablePrinter& operator << ( TablePrinter& tp, RowBreak ) {
  8604. if( tp.m_currentColumn > 0 ) {
  8605. tp.m_os << "\n";
  8606. tp.m_currentColumn = -1;
  8607. }
  8608. return tp;
  8609. }
  8610. };
  8611. class Duration {
  8612. enum class Unit {
  8613. Auto,
  8614. Nanoseconds,
  8615. Microseconds,
  8616. Milliseconds,
  8617. Seconds,
  8618. Minutes
  8619. };
  8620. static const uint64_t s_nanosecondsInAMicrosecond = 1000;
  8621. static const uint64_t s_nanosecondsInAMillisecond = 1000*s_nanosecondsInAMicrosecond;
  8622. static const uint64_t s_nanosecondsInASecond = 1000*s_nanosecondsInAMillisecond;
  8623. static const uint64_t s_nanosecondsInAMinute = 60*s_nanosecondsInASecond;
  8624. uint64_t m_inNanoseconds;
  8625. Unit m_units;
  8626. public:
  8627. Duration( uint64_t inNanoseconds, Unit units = Unit::Auto )
  8628. : m_inNanoseconds( inNanoseconds ),
  8629. m_units( units )
  8630. {
  8631. if( m_units == Unit::Auto ) {
  8632. if( m_inNanoseconds < s_nanosecondsInAMicrosecond )
  8633. m_units = Unit::Nanoseconds;
  8634. else if( m_inNanoseconds < s_nanosecondsInAMillisecond )
  8635. m_units = Unit::Microseconds;
  8636. else if( m_inNanoseconds < s_nanosecondsInASecond )
  8637. m_units = Unit::Milliseconds;
  8638. else if( m_inNanoseconds < s_nanosecondsInAMinute )
  8639. m_units = Unit::Seconds;
  8640. else
  8641. m_units = Unit::Minutes;
  8642. }
  8643. }
  8644. auto value() const -> double {
  8645. switch( m_units ) {
  8646. case Unit::Microseconds:
  8647. return m_inNanoseconds / static_cast<double>( s_nanosecondsInAMicrosecond );
  8648. case Unit::Milliseconds:
  8649. return m_inNanoseconds / static_cast<double>( s_nanosecondsInAMillisecond );
  8650. case Unit::Seconds:
  8651. return m_inNanoseconds / static_cast<double>( s_nanosecondsInASecond );
  8652. case Unit::Minutes:
  8653. return m_inNanoseconds / static_cast<double>( s_nanosecondsInAMinute );
  8654. default:
  8655. return static_cast<double>( m_inNanoseconds );
  8656. }
  8657. }
  8658. auto unitsAsString() const -> std::string {
  8659. switch( m_units ) {
  8660. case Unit::Nanoseconds:
  8661. return "ns";
  8662. case Unit::Microseconds:
  8663. return "µs";
  8664. case Unit::Milliseconds:
  8665. return "ms";
  8666. case Unit::Seconds:
  8667. return "s";
  8668. case Unit::Minutes:
  8669. return "m";
  8670. default:
  8671. return "** internal error **";
  8672. }
  8673. }
  8674. friend auto operator << ( std::ostream& os, Duration const& duration ) -> std::ostream& {
  8675. return os << duration.value() << " " << duration.unitsAsString();
  8676. }
  8677. };
  8678. } // end anon namespace
  8679. struct ConsoleReporter : StreamingReporterBase<ConsoleReporter> {
  8680. TablePrinter m_tablePrinter;
  8681. ConsoleReporter( ReporterConfig const& config )
  8682. : StreamingReporterBase( config ),
  8683. m_tablePrinter( config.stream(),
  8684. {
  8685. { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH-32, ColumnInfo::Left },
  8686. { "iters", 8, ColumnInfo::Right },
  8687. { "elapsed ns", 14, ColumnInfo::Right },
  8688. { "average", 14, ColumnInfo::Right }
  8689. } )
  8690. {}
  8691. ~ConsoleReporter() override;
  8692. static std::string getDescription() {
  8693. return "Reports test results as plain lines of text";
  8694. }
  8695. void noMatchingTestCases( std::string const& spec ) override {
  8696. stream << "No test cases matched '" << spec << '\'' << std::endl;
  8697. }
  8698. void assertionStarting( AssertionInfo const& ) override {
  8699. }
  8700. bool assertionEnded( AssertionStats const& _assertionStats ) override {
  8701. AssertionResult const& result = _assertionStats.assertionResult;
  8702. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  8703. // Drop out if result was successful but we're not printing them.
  8704. if( !includeResults && result.getResultType() != ResultWas::Warning )
  8705. return false;
  8706. lazyPrint();
  8707. AssertionPrinter printer( stream, _assertionStats, includeResults );
  8708. printer.print();
  8709. stream << std::endl;
  8710. return true;
  8711. }
  8712. void sectionStarting( SectionInfo const& _sectionInfo ) override {
  8713. m_headerPrinted = false;
  8714. StreamingReporterBase::sectionStarting( _sectionInfo );
  8715. }
  8716. void sectionEnded( SectionStats const& _sectionStats ) override {
  8717. m_tablePrinter.close();
  8718. if( _sectionStats.missingAssertions ) {
  8719. lazyPrint();
  8720. Colour colour( Colour::ResultError );
  8721. if( m_sectionStack.size() > 1 )
  8722. stream << "\nNo assertions in section";
  8723. else
  8724. stream << "\nNo assertions in test case";
  8725. stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl;
  8726. }
  8727. if( m_config->showDurations() == ShowDurations::Always ) {
  8728. stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  8729. }
  8730. if( m_headerPrinted ) {
  8731. m_headerPrinted = false;
  8732. }
  8733. StreamingReporterBase::sectionEnded( _sectionStats );
  8734. }
  8735. void benchmarkStarting( BenchmarkInfo const& info ) override {
  8736. lazyPrintWithoutClosingBenchmarkTable();
  8737. auto nameCol = Column( info.name ).width( m_tablePrinter.columnInfos()[0].width-2 );
  8738. bool firstLine = true;
  8739. for( auto line : nameCol ) {
  8740. if( !firstLine )
  8741. m_tablePrinter << ColumnBreak() << ColumnBreak() << ColumnBreak();
  8742. else
  8743. firstLine = false;
  8744. m_tablePrinter << line << ColumnBreak();
  8745. }
  8746. }
  8747. void benchmarkEnded( BenchmarkStats const& stats ) override {
  8748. Duration average( stats.elapsedTimeInNanoseconds/stats.iterations );
  8749. m_tablePrinter
  8750. << stats.iterations << ColumnBreak()
  8751. << stats.elapsedTimeInNanoseconds << ColumnBreak()
  8752. << average << ColumnBreak();
  8753. }
  8754. void testCaseEnded( TestCaseStats const& _testCaseStats ) override {
  8755. m_tablePrinter.close();
  8756. StreamingReporterBase::testCaseEnded( _testCaseStats );
  8757. m_headerPrinted = false;
  8758. }
  8759. void testGroupEnded( TestGroupStats const& _testGroupStats ) override {
  8760. if( currentGroupInfo.used ) {
  8761. printSummaryDivider();
  8762. stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n";
  8763. printTotals( _testGroupStats.totals );
  8764. stream << '\n' << std::endl;
  8765. }
  8766. StreamingReporterBase::testGroupEnded( _testGroupStats );
  8767. }
  8768. void testRunEnded( TestRunStats const& _testRunStats ) override {
  8769. printTotalsDivider( _testRunStats.totals );
  8770. printTotals( _testRunStats.totals );
  8771. stream << std::endl;
  8772. StreamingReporterBase::testRunEnded( _testRunStats );
  8773. }
  8774. private:
  8775. class AssertionPrinter {
  8776. public:
  8777. AssertionPrinter& operator= ( AssertionPrinter const& ) = delete;
  8778. AssertionPrinter( AssertionPrinter const& ) = delete;
  8779. AssertionPrinter( std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages )
  8780. : stream( _stream ),
  8781. stats( _stats ),
  8782. result( _stats.assertionResult ),
  8783. colour( Colour::None ),
  8784. message( result.getMessage() ),
  8785. messages( _stats.infoMessages ),
  8786. printInfoMessages( _printInfoMessages )
  8787. {
  8788. switch( result.getResultType() ) {
  8789. case ResultWas::Ok:
  8790. colour = Colour::Success;
  8791. passOrFail = "PASSED";
  8792. //if( result.hasMessage() )
  8793. if( _stats.infoMessages.size() == 1 )
  8794. messageLabel = "with message";
  8795. if( _stats.infoMessages.size() > 1 )
  8796. messageLabel = "with messages";
  8797. break;
  8798. case ResultWas::ExpressionFailed:
  8799. if( result.isOk() ) {
  8800. colour = Colour::Success;
  8801. passOrFail = "FAILED - but was ok";
  8802. }
  8803. else {
  8804. colour = Colour::Error;
  8805. passOrFail = "FAILED";
  8806. }
  8807. if( _stats.infoMessages.size() == 1 )
  8808. messageLabel = "with message";
  8809. if( _stats.infoMessages.size() > 1 )
  8810. messageLabel = "with messages";
  8811. break;
  8812. case ResultWas::ThrewException:
  8813. colour = Colour::Error;
  8814. passOrFail = "FAILED";
  8815. messageLabel = "due to unexpected exception with ";
  8816. if (_stats.infoMessages.size() == 1)
  8817. messageLabel += "message";
  8818. if (_stats.infoMessages.size() > 1)
  8819. messageLabel += "messages";
  8820. break;
  8821. case ResultWas::FatalErrorCondition:
  8822. colour = Colour::Error;
  8823. passOrFail = "FAILED";
  8824. messageLabel = "due to a fatal error condition";
  8825. break;
  8826. case ResultWas::DidntThrowException:
  8827. colour = Colour::Error;
  8828. passOrFail = "FAILED";
  8829. messageLabel = "because no exception was thrown where one was expected";
  8830. break;
  8831. case ResultWas::Info:
  8832. messageLabel = "info";
  8833. break;
  8834. case ResultWas::Warning:
  8835. messageLabel = "warning";
  8836. break;
  8837. case ResultWas::ExplicitFailure:
  8838. passOrFail = "FAILED";
  8839. colour = Colour::Error;
  8840. if( _stats.infoMessages.size() == 1 )
  8841. messageLabel = "explicitly with message";
  8842. if( _stats.infoMessages.size() > 1 )
  8843. messageLabel = "explicitly with messages";
  8844. break;
  8845. // These cases are here to prevent compiler warnings
  8846. case ResultWas::Unknown:
  8847. case ResultWas::FailureBit:
  8848. case ResultWas::Exception:
  8849. passOrFail = "** internal error **";
  8850. colour = Colour::Error;
  8851. break;
  8852. }
  8853. }
  8854. void print() const {
  8855. printSourceInfo();
  8856. if( stats.totals.assertions.total() > 0 ) {
  8857. if( result.isOk() )
  8858. stream << '\n';
  8859. printResultType();
  8860. printOriginalExpression();
  8861. printReconstructedExpression();
  8862. }
  8863. else {
  8864. stream << '\n';
  8865. }
  8866. printMessage();
  8867. }
  8868. private:
  8869. void printResultType() const {
  8870. if( !passOrFail.empty() ) {
  8871. Colour colourGuard( colour );
  8872. stream << passOrFail << ":\n";
  8873. }
  8874. }
  8875. void printOriginalExpression() const {
  8876. if( result.hasExpression() ) {
  8877. Colour colourGuard( Colour::OriginalExpression );
  8878. stream << " ";
  8879. stream << result.getExpressionInMacro();
  8880. stream << '\n';
  8881. }
  8882. }
  8883. void printReconstructedExpression() const {
  8884. if( result.hasExpandedExpression() ) {
  8885. stream << "with expansion:\n";
  8886. Colour colourGuard( Colour::ReconstructedExpression );
  8887. stream << Column( result.getExpandedExpression() ).indent(2) << '\n';
  8888. }
  8889. }
  8890. void printMessage() const {
  8891. if( !messageLabel.empty() )
  8892. stream << messageLabel << ':' << '\n';
  8893. for( auto const& msg : messages ) {
  8894. // If this assertion is a warning ignore any INFO messages
  8895. if( printInfoMessages || msg.type != ResultWas::Info )
  8896. stream << Column( msg.message ).indent(2) << '\n';
  8897. }
  8898. }
  8899. void printSourceInfo() const {
  8900. Colour colourGuard( Colour::FileName );
  8901. stream << result.getSourceInfo() << ": ";
  8902. }
  8903. std::ostream& stream;
  8904. AssertionStats const& stats;
  8905. AssertionResult const& result;
  8906. Colour::Code colour;
  8907. std::string passOrFail;
  8908. std::string messageLabel;
  8909. std::string message;
  8910. std::vector<MessageInfo> messages;
  8911. bool printInfoMessages;
  8912. };
  8913. void lazyPrint() {
  8914. m_tablePrinter.close();
  8915. lazyPrintWithoutClosingBenchmarkTable();
  8916. }
  8917. void lazyPrintWithoutClosingBenchmarkTable() {
  8918. if( !currentTestRunInfo.used )
  8919. lazyPrintRunInfo();
  8920. if( !currentGroupInfo.used )
  8921. lazyPrintGroupInfo();
  8922. if( !m_headerPrinted ) {
  8923. printTestCaseAndSectionHeader();
  8924. m_headerPrinted = true;
  8925. }
  8926. }
  8927. void lazyPrintRunInfo() {
  8928. stream << '\n' << getLineOfChars<'~'>() << '\n';
  8929. Colour colour( Colour::SecondaryText );
  8930. stream << currentTestRunInfo->name
  8931. << " is a Catch v" << libraryVersion() << " host application.\n"
  8932. << "Run with -? for options\n\n";
  8933. if( m_config->rngSeed() != 0 )
  8934. stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n";
  8935. currentTestRunInfo.used = true;
  8936. }
  8937. void lazyPrintGroupInfo() {
  8938. if( !currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1 ) {
  8939. printClosedHeader( "Group: " + currentGroupInfo->name );
  8940. currentGroupInfo.used = true;
  8941. }
  8942. }
  8943. void printTestCaseAndSectionHeader() {
  8944. assert( !m_sectionStack.empty() );
  8945. printOpenHeader( currentTestCaseInfo->name );
  8946. if( m_sectionStack.size() > 1 ) {
  8947. Colour colourGuard( Colour::Headers );
  8948. auto
  8949. it = m_sectionStack.begin()+1, // Skip first section (test case)
  8950. itEnd = m_sectionStack.end();
  8951. for( ; it != itEnd; ++it )
  8952. printHeaderString( it->name, 2 );
  8953. }
  8954. SourceLineInfo lineInfo = m_sectionStack.back().lineInfo;
  8955. if( !lineInfo.empty() ){
  8956. stream << getLineOfChars<'-'>() << '\n';
  8957. Colour colourGuard( Colour::FileName );
  8958. stream << lineInfo << '\n';
  8959. }
  8960. stream << getLineOfChars<'.'>() << '\n' << std::endl;
  8961. }
  8962. void printClosedHeader( std::string const& _name ) {
  8963. printOpenHeader( _name );
  8964. stream << getLineOfChars<'.'>() << '\n';
  8965. }
  8966. void printOpenHeader( std::string const& _name ) {
  8967. stream << getLineOfChars<'-'>() << '\n';
  8968. {
  8969. Colour colourGuard( Colour::Headers );
  8970. printHeaderString( _name );
  8971. }
  8972. }
  8973. // if string has a : in first line will set indent to follow it on
  8974. // subsequent lines
  8975. void printHeaderString( std::string const& _string, std::size_t indent = 0 ) {
  8976. std::size_t i = _string.find( ": " );
  8977. if( i != std::string::npos )
  8978. i+=2;
  8979. else
  8980. i = 0;
  8981. stream << Column( _string ).indent( indent+i ).initialIndent( indent ) << '\n';
  8982. }
  8983. struct SummaryColumn {
  8984. SummaryColumn( std::string const& _label, Colour::Code _colour )
  8985. : label( _label ),
  8986. colour( _colour )
  8987. {}
  8988. SummaryColumn addRow( std::size_t count ) {
  8989. std::ostringstream oss;
  8990. oss << count;
  8991. std::string row = oss.str();
  8992. for( auto& oldRow : rows ) {
  8993. while( oldRow.size() < row.size() )
  8994. oldRow = ' ' + oldRow;
  8995. while( oldRow.size() > row.size() )
  8996. row = ' ' + row;
  8997. }
  8998. rows.push_back( row );
  8999. return *this;
  9000. }
  9001. std::string label;
  9002. Colour::Code colour;
  9003. std::vector<std::string> rows;
  9004. };
  9005. void printTotals( Totals const& totals ) {
  9006. if( totals.testCases.total() == 0 ) {
  9007. stream << Colour( Colour::Warning ) << "No tests ran\n";
  9008. }
  9009. else if( totals.assertions.total() > 0 && totals.testCases.allPassed() ) {
  9010. stream << Colour( Colour::ResultSuccess ) << "All tests passed";
  9011. stream << " ("
  9012. << pluralise( totals.assertions.passed, "assertion" ) << " in "
  9013. << pluralise( totals.testCases.passed, "test case" ) << ')'
  9014. << '\n';
  9015. }
  9016. else {
  9017. std::vector<SummaryColumn> columns;
  9018. columns.push_back( SummaryColumn( "", Colour::None )
  9019. .addRow( totals.testCases.total() )
  9020. .addRow( totals.assertions.total() ) );
  9021. columns.push_back( SummaryColumn( "passed", Colour::Success )
  9022. .addRow( totals.testCases.passed )
  9023. .addRow( totals.assertions.passed ) );
  9024. columns.push_back( SummaryColumn( "failed", Colour::ResultError )
  9025. .addRow( totals.testCases.failed )
  9026. .addRow( totals.assertions.failed ) );
  9027. columns.push_back( SummaryColumn( "failed as expected", Colour::ResultExpectedFailure )
  9028. .addRow( totals.testCases.failedButOk )
  9029. .addRow( totals.assertions.failedButOk ) );
  9030. printSummaryRow( "test cases", columns, 0 );
  9031. printSummaryRow( "assertions", columns, 1 );
  9032. }
  9033. }
  9034. void printSummaryRow( std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row ) {
  9035. for( auto col : cols ) {
  9036. std::string value = col.rows[row];
  9037. if( col.label.empty() ) {
  9038. stream << label << ": ";
  9039. if( value != "0" )
  9040. stream << value;
  9041. else
  9042. stream << Colour( Colour::Warning ) << "- none -";
  9043. }
  9044. else if( value != "0" ) {
  9045. stream << Colour( Colour::LightGrey ) << " | ";
  9046. stream << Colour( col.colour )
  9047. << value << ' ' << col.label;
  9048. }
  9049. }
  9050. stream << '\n';
  9051. }
  9052. void printTotalsDivider( Totals const& totals ) {
  9053. if( totals.testCases.total() > 0 ) {
  9054. std::size_t failedRatio = makeRatio( totals.testCases.failed, totals.testCases.total() );
  9055. std::size_t failedButOkRatio = makeRatio( totals.testCases.failedButOk, totals.testCases.total() );
  9056. std::size_t passedRatio = makeRatio( totals.testCases.passed, totals.testCases.total() );
  9057. while( failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH-1 )
  9058. findMax( failedRatio, failedButOkRatio, passedRatio )++;
  9059. while( failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH-1 )
  9060. findMax( failedRatio, failedButOkRatio, passedRatio )--;
  9061. stream << Colour( Colour::Error ) << std::string( failedRatio, '=' );
  9062. stream << Colour( Colour::ResultExpectedFailure ) << std::string( failedButOkRatio, '=' );
  9063. if( totals.testCases.allPassed() )
  9064. stream << Colour( Colour::ResultSuccess ) << std::string( passedRatio, '=' );
  9065. else
  9066. stream << Colour( Colour::Success ) << std::string( passedRatio, '=' );
  9067. }
  9068. else {
  9069. stream << Colour( Colour::Warning ) << std::string( CATCH_CONFIG_CONSOLE_WIDTH-1, '=' );
  9070. }
  9071. stream << '\n';
  9072. }
  9073. void printSummaryDivider() {
  9074. stream << getLineOfChars<'-'>() << '\n';
  9075. }
  9076. private:
  9077. bool m_headerPrinted = false;
  9078. };
  9079. CATCH_REGISTER_REPORTER( "console", ConsoleReporter )
  9080. ConsoleReporter::~ConsoleReporter() {}
  9081. } // end namespace Catch
  9082. #if defined(_MSC_VER)
  9083. #pragma warning(pop)
  9084. #endif
  9085. // end catch_reporter_console.cpp
  9086. // start catch_reporter_junit.cpp
  9087. #include <assert.h>
  9088. #include <ctime>
  9089. #include <algorithm>
  9090. namespace Catch {
  9091. namespace {
  9092. std::string getCurrentTimestamp() {
  9093. // Beware, this is not reentrant because of backward compatibility issues
  9094. // Also, UTC only, again because of backward compatibility (%z is C++11)
  9095. time_t rawtime;
  9096. std::time(&rawtime);
  9097. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  9098. #ifdef _MSC_VER
  9099. std::tm timeInfo = {};
  9100. gmtime_s(&timeInfo, &rawtime);
  9101. #else
  9102. std::tm* timeInfo;
  9103. timeInfo = std::gmtime(&rawtime);
  9104. #endif
  9105. char timeStamp[timeStampSize];
  9106. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  9107. #ifdef _MSC_VER
  9108. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  9109. #else
  9110. std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
  9111. #endif
  9112. return std::string(timeStamp);
  9113. }
  9114. std::string fileNameTag(const std::vector<std::string> &tags) {
  9115. auto it = std::find_if(begin(tags),
  9116. end(tags),
  9117. [] (std::string const& tag) {return tag.front() == '#'; });
  9118. if (it != tags.end())
  9119. return it->substr(1);
  9120. return std::string();
  9121. }
  9122. }
  9123. class JunitReporter : public CumulativeReporterBase<JunitReporter> {
  9124. public:
  9125. JunitReporter( ReporterConfig const& _config )
  9126. : CumulativeReporterBase( _config ),
  9127. xml( _config.stream() )
  9128. {
  9129. m_reporterPrefs.shouldRedirectStdOut = true;
  9130. }
  9131. ~JunitReporter() override;
  9132. static std::string getDescription() {
  9133. return "Reports test results in an XML format that looks like Ant's junitreport target";
  9134. }
  9135. void noMatchingTestCases( std::string const& /*spec*/ ) override {}
  9136. void testRunStarting( TestRunInfo const& runInfo ) override {
  9137. CumulativeReporterBase::testRunStarting( runInfo );
  9138. xml.startElement( "testsuites" );
  9139. }
  9140. void testGroupStarting( GroupInfo const& groupInfo ) override {
  9141. suiteTimer.start();
  9142. stdOutForSuite.str("");
  9143. stdErrForSuite.str("");
  9144. unexpectedExceptions = 0;
  9145. CumulativeReporterBase::testGroupStarting( groupInfo );
  9146. }
  9147. void testCaseStarting( TestCaseInfo const& testCaseInfo ) override {
  9148. m_okToFail = testCaseInfo.okToFail();
  9149. }
  9150. bool assertionEnded( AssertionStats const& assertionStats ) override {
  9151. if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail )
  9152. unexpectedExceptions++;
  9153. return CumulativeReporterBase::assertionEnded( assertionStats );
  9154. }
  9155. void testCaseEnded( TestCaseStats const& testCaseStats ) override {
  9156. stdOutForSuite << testCaseStats.stdOut;
  9157. stdErrForSuite << testCaseStats.stdErr;
  9158. CumulativeReporterBase::testCaseEnded( testCaseStats );
  9159. }
  9160. void testGroupEnded( TestGroupStats const& testGroupStats ) override {
  9161. double suiteTime = suiteTimer.getElapsedSeconds();
  9162. CumulativeReporterBase::testGroupEnded( testGroupStats );
  9163. writeGroup( *m_testGroups.back(), suiteTime );
  9164. }
  9165. void testRunEndedCumulative() override {
  9166. xml.endElement();
  9167. }
  9168. void writeGroup( TestGroupNode const& groupNode, double suiteTime ) {
  9169. XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" );
  9170. TestGroupStats const& stats = groupNode.value;
  9171. xml.writeAttribute( "name", stats.groupInfo.name );
  9172. xml.writeAttribute( "errors", unexpectedExceptions );
  9173. xml.writeAttribute( "failures", stats.totals.assertions.failed-unexpectedExceptions );
  9174. xml.writeAttribute( "tests", stats.totals.assertions.total() );
  9175. xml.writeAttribute( "hostname", "tbd" ); // !TBD
  9176. if( m_config->showDurations() == ShowDurations::Never )
  9177. xml.writeAttribute( "time", "" );
  9178. else
  9179. xml.writeAttribute( "time", suiteTime );
  9180. xml.writeAttribute( "timestamp", getCurrentTimestamp() );
  9181. // Write test cases
  9182. for( auto const& child : groupNode.children )
  9183. writeTestCase( *child );
  9184. xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite.str() ), false );
  9185. xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite.str() ), false );
  9186. }
  9187. void writeTestCase( TestCaseNode const& testCaseNode ) {
  9188. TestCaseStats const& stats = testCaseNode.value;
  9189. // All test cases have exactly one section - which represents the
  9190. // test case itself. That section may have 0-n nested sections
  9191. assert( testCaseNode.children.size() == 1 );
  9192. SectionNode const& rootSection = *testCaseNode.children.front();
  9193. std::string className = stats.testInfo.className;
  9194. if( className.empty() ) {
  9195. className = fileNameTag(stats.testInfo.tags);
  9196. if ( className.empty() )
  9197. className = "global";
  9198. }
  9199. if ( !m_config->name().empty() )
  9200. className = m_config->name() + "." + className;
  9201. writeSection( className, "", rootSection );
  9202. }
  9203. void writeSection( std::string const& className,
  9204. std::string const& rootName,
  9205. SectionNode const& sectionNode ) {
  9206. std::string name = trim( sectionNode.stats.sectionInfo.name );
  9207. if( !rootName.empty() )
  9208. name = rootName + '/' + name;
  9209. if( !sectionNode.assertions.empty() ||
  9210. !sectionNode.stdOut.empty() ||
  9211. !sectionNode.stdErr.empty() ) {
  9212. XmlWriter::ScopedElement e = xml.scopedElement( "testcase" );
  9213. if( className.empty() ) {
  9214. xml.writeAttribute( "classname", name );
  9215. xml.writeAttribute( "name", "root" );
  9216. }
  9217. else {
  9218. xml.writeAttribute( "classname", className );
  9219. xml.writeAttribute( "name", name );
  9220. }
  9221. xml.writeAttribute( "time", ::Catch::Detail::stringify( sectionNode.stats.durationInSeconds ) );
  9222. writeAssertions( sectionNode );
  9223. if( !sectionNode.stdOut.empty() )
  9224. xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), false );
  9225. if( !sectionNode.stdErr.empty() )
  9226. xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), false );
  9227. }
  9228. for( auto const& childNode : sectionNode.childSections )
  9229. if( className.empty() )
  9230. writeSection( name, "", *childNode );
  9231. else
  9232. writeSection( className, name, *childNode );
  9233. }
  9234. void writeAssertions( SectionNode const& sectionNode ) {
  9235. for( auto const& assertion : sectionNode.assertions )
  9236. writeAssertion( assertion );
  9237. }
  9238. void writeAssertion( AssertionStats const& stats ) {
  9239. AssertionResult const& result = stats.assertionResult;
  9240. if( !result.isOk() ) {
  9241. std::string elementName;
  9242. switch( result.getResultType() ) {
  9243. case ResultWas::ThrewException:
  9244. case ResultWas::FatalErrorCondition:
  9245. elementName = "error";
  9246. break;
  9247. case ResultWas::ExplicitFailure:
  9248. elementName = "failure";
  9249. break;
  9250. case ResultWas::ExpressionFailed:
  9251. elementName = "failure";
  9252. break;
  9253. case ResultWas::DidntThrowException:
  9254. elementName = "failure";
  9255. break;
  9256. // We should never see these here:
  9257. case ResultWas::Info:
  9258. case ResultWas::Warning:
  9259. case ResultWas::Ok:
  9260. case ResultWas::Unknown:
  9261. case ResultWas::FailureBit:
  9262. case ResultWas::Exception:
  9263. elementName = "internalError";
  9264. break;
  9265. }
  9266. XmlWriter::ScopedElement e = xml.scopedElement( elementName );
  9267. xml.writeAttribute( "message", result.getExpandedExpression() );
  9268. xml.writeAttribute( "type", result.getTestMacroName() );
  9269. std::ostringstream oss;
  9270. if( !result.getMessage().empty() )
  9271. oss << result.getMessage() << '\n';
  9272. for( auto const& msg : stats.infoMessages )
  9273. if( msg.type == ResultWas::Info )
  9274. oss << msg.message << '\n';
  9275. oss << "at " << result.getSourceInfo();
  9276. xml.writeText( oss.str(), false );
  9277. }
  9278. }
  9279. XmlWriter xml;
  9280. Timer suiteTimer;
  9281. std::ostringstream stdOutForSuite;
  9282. std::ostringstream stdErrForSuite;
  9283. unsigned int unexpectedExceptions = 0;
  9284. bool m_okToFail = false;
  9285. };
  9286. JunitReporter::~JunitReporter() {}
  9287. CATCH_REGISTER_REPORTER( "junit", JunitReporter )
  9288. } // end namespace Catch
  9289. // end catch_reporter_junit.cpp
  9290. // start catch_reporter_multi.cpp
  9291. namespace Catch {
  9292. void MultipleReporters::add( IStreamingReporterPtr&& reporter ) {
  9293. m_reporters.push_back( std::move( reporter ) );
  9294. }
  9295. ReporterPreferences MultipleReporters::getPreferences() const {
  9296. return m_reporters[0]->getPreferences();
  9297. }
  9298. std::set<Verbosity> MultipleReporters::getSupportedVerbosities() {
  9299. return std::set<Verbosity>{ };
  9300. }
  9301. void MultipleReporters::noMatchingTestCases( std::string const& spec ) {
  9302. for( auto const& reporter : m_reporters )
  9303. reporter->noMatchingTestCases( spec );
  9304. }
  9305. void MultipleReporters::benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) {
  9306. for( auto const& reporter : m_reporters )
  9307. reporter->benchmarkStarting( benchmarkInfo );
  9308. }
  9309. void MultipleReporters::benchmarkEnded( BenchmarkStats const& benchmarkStats ) {
  9310. for( auto const& reporter : m_reporters )
  9311. reporter->benchmarkEnded( benchmarkStats );
  9312. }
  9313. void MultipleReporters::testRunStarting( TestRunInfo const& testRunInfo ) {
  9314. for( auto const& reporter : m_reporters )
  9315. reporter->testRunStarting( testRunInfo );
  9316. }
  9317. void MultipleReporters::testGroupStarting( GroupInfo const& groupInfo ) {
  9318. for( auto const& reporter : m_reporters )
  9319. reporter->testGroupStarting( groupInfo );
  9320. }
  9321. void MultipleReporters::testCaseStarting( TestCaseInfo const& testInfo ) {
  9322. for( auto const& reporter : m_reporters )
  9323. reporter->testCaseStarting( testInfo );
  9324. }
  9325. void MultipleReporters::sectionStarting( SectionInfo const& sectionInfo ) {
  9326. for( auto const& reporter : m_reporters )
  9327. reporter->sectionStarting( sectionInfo );
  9328. }
  9329. void MultipleReporters::assertionStarting( AssertionInfo const& assertionInfo ) {
  9330. for( auto const& reporter : m_reporters )
  9331. reporter->assertionStarting( assertionInfo );
  9332. }
  9333. // The return value indicates if the messages buffer should be cleared:
  9334. bool MultipleReporters::assertionEnded( AssertionStats const& assertionStats ) {
  9335. bool clearBuffer = false;
  9336. for( auto const& reporter : m_reporters )
  9337. clearBuffer |= reporter->assertionEnded( assertionStats );
  9338. return clearBuffer;
  9339. }
  9340. void MultipleReporters::sectionEnded( SectionStats const& sectionStats ) {
  9341. for( auto const& reporter : m_reporters )
  9342. reporter->sectionEnded( sectionStats );
  9343. }
  9344. void MultipleReporters::testCaseEnded( TestCaseStats const& testCaseStats ) {
  9345. for( auto const& reporter : m_reporters )
  9346. reporter->testCaseEnded( testCaseStats );
  9347. }
  9348. void MultipleReporters::testGroupEnded( TestGroupStats const& testGroupStats ) {
  9349. for( auto const& reporter : m_reporters )
  9350. reporter->testGroupEnded( testGroupStats );
  9351. }
  9352. void MultipleReporters::testRunEnded( TestRunStats const& testRunStats ) {
  9353. for( auto const& reporter : m_reporters )
  9354. reporter->testRunEnded( testRunStats );
  9355. }
  9356. void MultipleReporters::skipTest( TestCaseInfo const& testInfo ) {
  9357. for( auto const& reporter : m_reporters )
  9358. reporter->skipTest( testInfo );
  9359. }
  9360. bool MultipleReporters::isMulti() const {
  9361. return true;
  9362. }
  9363. } // end namespace Catch
  9364. // end catch_reporter_multi.cpp
  9365. // start catch_reporter_xml.cpp
  9366. #if defined(_MSC_VER)
  9367. #pragma warning(push)
  9368. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  9369. // Note that 4062 (not all labels are handled
  9370. // and default is missing) is enabled
  9371. #endif
  9372. namespace Catch {
  9373. class XmlReporter : public StreamingReporterBase<XmlReporter> {
  9374. public:
  9375. XmlReporter( ReporterConfig const& _config )
  9376. : StreamingReporterBase( _config ),
  9377. m_xml(_config.stream())
  9378. {
  9379. m_reporterPrefs.shouldRedirectStdOut = true;
  9380. }
  9381. ~XmlReporter() override;
  9382. static std::string getDescription() {
  9383. return "Reports test results as an XML document";
  9384. }
  9385. virtual std::string getStylesheetRef() const {
  9386. return std::string();
  9387. }
  9388. void writeSourceInfo( SourceLineInfo const& sourceInfo ) {
  9389. m_xml
  9390. .writeAttribute( "filename", sourceInfo.file )
  9391. .writeAttribute( "line", sourceInfo.line );
  9392. }
  9393. public: // StreamingReporterBase
  9394. void noMatchingTestCases( std::string const& s ) override {
  9395. StreamingReporterBase::noMatchingTestCases( s );
  9396. }
  9397. void testRunStarting( TestRunInfo const& testInfo ) override {
  9398. StreamingReporterBase::testRunStarting( testInfo );
  9399. std::string stylesheetRef = getStylesheetRef();
  9400. if( !stylesheetRef.empty() )
  9401. m_xml.writeStylesheetRef( stylesheetRef );
  9402. m_xml.startElement( "Catch" );
  9403. if( !m_config->name().empty() )
  9404. m_xml.writeAttribute( "name", m_config->name() );
  9405. }
  9406. void testGroupStarting( GroupInfo const& groupInfo ) override {
  9407. StreamingReporterBase::testGroupStarting( groupInfo );
  9408. m_xml.startElement( "Group" )
  9409. .writeAttribute( "name", groupInfo.name );
  9410. }
  9411. void testCaseStarting( TestCaseInfo const& testInfo ) override {
  9412. StreamingReporterBase::testCaseStarting(testInfo);
  9413. m_xml.startElement( "TestCase" )
  9414. .writeAttribute( "name", trim( testInfo.name ) )
  9415. .writeAttribute( "description", testInfo.description )
  9416. .writeAttribute( "tags", testInfo.tagsAsString() );
  9417. writeSourceInfo( testInfo.lineInfo );
  9418. if ( m_config->showDurations() == ShowDurations::Always )
  9419. m_testCaseTimer.start();
  9420. m_xml.ensureTagClosed();
  9421. }
  9422. void sectionStarting( SectionInfo const& sectionInfo ) override {
  9423. StreamingReporterBase::sectionStarting( sectionInfo );
  9424. if( m_sectionDepth++ > 0 ) {
  9425. m_xml.startElement( "Section" )
  9426. .writeAttribute( "name", trim( sectionInfo.name ) )
  9427. .writeAttribute( "description", sectionInfo.description );
  9428. writeSourceInfo( sectionInfo.lineInfo );
  9429. m_xml.ensureTagClosed();
  9430. }
  9431. }
  9432. void assertionStarting( AssertionInfo const& ) override { }
  9433. bool assertionEnded( AssertionStats const& assertionStats ) override {
  9434. AssertionResult const& result = assertionStats.assertionResult;
  9435. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  9436. if( includeResults ) {
  9437. // Print any info messages in <Info> tags.
  9438. for( auto const& msg : assertionStats.infoMessages ) {
  9439. if( msg.type == ResultWas::Info ) {
  9440. m_xml.scopedElement( "Info" )
  9441. .writeText( msg.message );
  9442. } else if ( msg.type == ResultWas::Warning ) {
  9443. m_xml.scopedElement( "Warning" )
  9444. .writeText( msg.message );
  9445. }
  9446. }
  9447. }
  9448. // Drop out if result was successful but we're not printing them.
  9449. if( !includeResults && result.getResultType() != ResultWas::Warning )
  9450. return true;
  9451. // Print the expression if there is one.
  9452. if( result.hasExpression() ) {
  9453. m_xml.startElement( "Expression" )
  9454. .writeAttribute( "success", result.succeeded() )
  9455. .writeAttribute( "type", result.getTestMacroName() );
  9456. writeSourceInfo( result.getSourceInfo() );
  9457. m_xml.scopedElement( "Original" )
  9458. .writeText( result.getExpression() );
  9459. m_xml.scopedElement( "Expanded" )
  9460. .writeText( result.getExpandedExpression() );
  9461. }
  9462. // And... Print a result applicable to each result type.
  9463. switch( result.getResultType() ) {
  9464. case ResultWas::ThrewException:
  9465. m_xml.startElement( "Exception" );
  9466. writeSourceInfo( result.getSourceInfo() );
  9467. m_xml.writeText( result.getMessage() );
  9468. m_xml.endElement();
  9469. break;
  9470. case ResultWas::FatalErrorCondition:
  9471. m_xml.startElement( "FatalErrorCondition" );
  9472. writeSourceInfo( result.getSourceInfo() );
  9473. m_xml.writeText( result.getMessage() );
  9474. m_xml.endElement();
  9475. break;
  9476. case ResultWas::Info:
  9477. m_xml.scopedElement( "Info" )
  9478. .writeText( result.getMessage() );
  9479. break;
  9480. case ResultWas::Warning:
  9481. // Warning will already have been written
  9482. break;
  9483. case ResultWas::ExplicitFailure:
  9484. m_xml.startElement( "Failure" );
  9485. writeSourceInfo( result.getSourceInfo() );
  9486. m_xml.writeText( result.getMessage() );
  9487. m_xml.endElement();
  9488. break;
  9489. default:
  9490. break;
  9491. }
  9492. if( result.hasExpression() )
  9493. m_xml.endElement();
  9494. return true;
  9495. }
  9496. void sectionEnded( SectionStats const& sectionStats ) override {
  9497. StreamingReporterBase::sectionEnded( sectionStats );
  9498. if( --m_sectionDepth > 0 ) {
  9499. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResults" );
  9500. e.writeAttribute( "successes", sectionStats.assertions.passed );
  9501. e.writeAttribute( "failures", sectionStats.assertions.failed );
  9502. e.writeAttribute( "expectedFailures", sectionStats.assertions.failedButOk );
  9503. if ( m_config->showDurations() == ShowDurations::Always )
  9504. e.writeAttribute( "durationInSeconds", sectionStats.durationInSeconds );
  9505. m_xml.endElement();
  9506. }
  9507. }
  9508. void testCaseEnded( TestCaseStats const& testCaseStats ) override {
  9509. StreamingReporterBase::testCaseEnded( testCaseStats );
  9510. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResult" );
  9511. e.writeAttribute( "success", testCaseStats.totals.assertions.allOk() );
  9512. if ( m_config->showDurations() == ShowDurations::Always )
  9513. e.writeAttribute( "durationInSeconds", m_testCaseTimer.getElapsedSeconds() );
  9514. if( !testCaseStats.stdOut.empty() )
  9515. m_xml.scopedElement( "StdOut" ).writeText( trim( testCaseStats.stdOut ), false );
  9516. if( !testCaseStats.stdErr.empty() )
  9517. m_xml.scopedElement( "StdErr" ).writeText( trim( testCaseStats.stdErr ), false );
  9518. m_xml.endElement();
  9519. }
  9520. void testGroupEnded( TestGroupStats const& testGroupStats ) override {
  9521. StreamingReporterBase::testGroupEnded( testGroupStats );
  9522. // TODO: Check testGroupStats.aborting and act accordingly.
  9523. m_xml.scopedElement( "OverallResults" )
  9524. .writeAttribute( "successes", testGroupStats.totals.assertions.passed )
  9525. .writeAttribute( "failures", testGroupStats.totals.assertions.failed )
  9526. .writeAttribute( "expectedFailures", testGroupStats.totals.assertions.failedButOk );
  9527. m_xml.endElement();
  9528. }
  9529. void testRunEnded( TestRunStats const& testRunStats ) override {
  9530. StreamingReporterBase::testRunEnded( testRunStats );
  9531. m_xml.scopedElement( "OverallResults" )
  9532. .writeAttribute( "successes", testRunStats.totals.assertions.passed )
  9533. .writeAttribute( "failures", testRunStats.totals.assertions.failed )
  9534. .writeAttribute( "expectedFailures", testRunStats.totals.assertions.failedButOk );
  9535. m_xml.endElement();
  9536. }
  9537. private:
  9538. Timer m_testCaseTimer;
  9539. XmlWriter m_xml;
  9540. int m_sectionDepth = 0;
  9541. };
  9542. XmlReporter::~XmlReporter() {}
  9543. CATCH_REGISTER_REPORTER( "xml", XmlReporter )
  9544. } // end namespace Catch
  9545. #if defined(_MSC_VER)
  9546. #pragma warning(pop)
  9547. #endif
  9548. // end catch_reporter_xml.cpp
  9549. namespace Catch {
  9550. LeakDetector leakDetector;
  9551. }
  9552. #ifdef __clang__
  9553. #pragma clang diagnostic pop
  9554. #endif
  9555. // end catch_impl.hpp
  9556. #endif
  9557. #ifdef CATCH_CONFIG_MAIN
  9558. // start catch_default_main.hpp
  9559. #ifndef __OBJC__
  9560. #if defined(WIN32) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN)
  9561. // Standard C/C++ Win32 Unicode wmain entry point
  9562. extern "C" int wmain (int argc, wchar_t * argv[], wchar_t * []) {
  9563. #else
  9564. // Standard C/C++ main entry point
  9565. int main (int argc, char * argv[]) {
  9566. #endif
  9567. return Catch::Session().run( argc, argv );
  9568. }
  9569. #else // __OBJC__
  9570. // Objective-C entry point
  9571. int main (int argc, char * const argv[]) {
  9572. #if !CATCH_ARC_ENABLED
  9573. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  9574. #endif
  9575. Catch::registerTestMethods();
  9576. int result = Catch::Session().run( argc, (char**)argv );
  9577. #if !CATCH_ARC_ENABLED
  9578. [pool drain];
  9579. #endif
  9580. return result;
  9581. }
  9582. #endif // __OBJC__
  9583. // end catch_default_main.hpp
  9584. #endif
  9585. #ifdef CLARA_CONFIG_MAIN_NOT_DEFINED
  9586. # undef CLARA_CONFIG_MAIN
  9587. #endif
  9588. #if !defined(CATCH_CONFIG_DISABLE)
  9589. //////
  9590. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  9591. #ifdef CATCH_CONFIG_PREFIX_ALL
  9592. #define CATCH_REQUIRE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  9593. #define CATCH_REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  9594. #define CATCH_REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, "", __VA_ARGS__ )
  9595. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  9596. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  9597. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  9598. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  9599. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  9600. #define CATCH_REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  9601. #define CATCH_CHECK( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  9602. #define CATCH_CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  9603. #define CATCH_CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  9604. #define CATCH_CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  9605. #define CATCH_CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  9606. #define CATCH_CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, "", __VA_ARGS__ )
  9607. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  9608. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  9609. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  9610. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  9611. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  9612. #define CATCH_CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  9613. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  9614. #define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  9615. #define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  9616. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  9617. #define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg )
  9618. #define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  9619. #define CATCH_CAPTURE( msg ) INTERNAL_CATCH_INFO( "CATCH_CAPTURE", #msg " := " << ::Catch::Detail::stringify(msg) )
  9620. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  9621. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  9622. #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  9623. #define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  9624. #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  9625. #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  9626. #define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  9627. #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  9628. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  9629. // "BDD-style" convenience wrappers
  9630. #define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ )
  9631. #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  9632. #define CATCH_GIVEN( desc ) CATCH_SECTION( std::string( "Given: ") + desc )
  9633. #define CATCH_WHEN( desc ) CATCH_SECTION( std::string( " When: ") + desc )
  9634. #define CATCH_AND_WHEN( desc ) CATCH_SECTION( std::string( " And: ") + desc )
  9635. #define CATCH_THEN( desc ) CATCH_SECTION( std::string( " Then: ") + desc )
  9636. #define CATCH_AND_THEN( desc ) CATCH_SECTION( std::string( " And: ") + desc )
  9637. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  9638. #else
  9639. #define REQUIRE( ... ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  9640. #define REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  9641. #define REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  9642. #define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  9643. #define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  9644. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  9645. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  9646. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  9647. #define REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  9648. #define CHECK( ... ) INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  9649. #define CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  9650. #define CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  9651. #define CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  9652. #define CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  9653. #define CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  9654. #define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  9655. #define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  9656. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  9657. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  9658. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  9659. #define CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  9660. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  9661. #define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  9662. #define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  9663. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  9664. #define INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg )
  9665. #define WARN( msg ) INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  9666. #define CAPTURE( msg ) INTERNAL_CATCH_INFO( "CAPTURE", #msg " := " << ::Catch::Detail::stringify(msg) )
  9667. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  9668. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  9669. #define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  9670. #define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  9671. #define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  9672. #define FAIL( ... ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  9673. #define FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  9674. #define SUCCEED( ... ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  9675. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  9676. #endif
  9677. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature )
  9678. // "BDD-style" convenience wrappers
  9679. #define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ )
  9680. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  9681. #define GIVEN( desc ) SECTION( std::string(" Given: ") + desc )
  9682. #define WHEN( desc ) SECTION( std::string(" When: ") + desc )
  9683. #define AND_WHEN( desc ) SECTION( std::string("And when: ") + desc )
  9684. #define THEN( desc ) SECTION( std::string(" Then: ") + desc )
  9685. #define AND_THEN( desc ) SECTION( std::string(" And: ") + desc )
  9686. using Catch::Detail::Approx;
  9687. #else
  9688. //////
  9689. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  9690. #ifdef CATCH_CONFIG_PREFIX_ALL
  9691. #define CATCH_REQUIRE( ... ) (void)(0)
  9692. #define CATCH_REQUIRE_FALSE( ... ) (void)(0)
  9693. #define CATCH_REQUIRE_THROWS( ... ) (void)(0)
  9694. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  9695. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  9696. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  9697. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  9698. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  9699. #define CATCH_REQUIRE_NOTHROW( ... ) (void)(0)
  9700. #define CATCH_CHECK( ... ) (void)(0)
  9701. #define CATCH_CHECK_FALSE( ... ) (void)(0)
  9702. #define CATCH_CHECKED_IF( ... ) if (__VA_ARGS__)
  9703. #define CATCH_CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  9704. #define CATCH_CHECK_NOFAIL( ... ) (void)(0)
  9705. #define CATCH_CHECK_THROWS( ... ) (void)(0)
  9706. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  9707. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  9708. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  9709. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  9710. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  9711. #define CATCH_CHECK_NOTHROW( ... ) (void)(0)
  9712. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  9713. #define CATCH_CHECK_THAT( arg, matcher ) (void)(0)
  9714. #define CATCH_REQUIRE_THAT( arg, matcher ) (void)(0)
  9715. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  9716. #define CATCH_INFO( msg ) (void)(0)
  9717. #define CATCH_WARN( msg ) (void)(0)
  9718. #define CATCH_CAPTURE( msg ) (void)(0)
  9719. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  9720. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  9721. #define CATCH_METHOD_AS_TEST_CASE( method, ... )
  9722. #define CATCH_REGISTER_TEST_CASE( Function, ... ) (void)(0)
  9723. #define CATCH_SECTION( ... )
  9724. #define CATCH_FAIL( ... ) (void)(0)
  9725. #define CATCH_FAIL_CHECK( ... ) (void)(0)
  9726. #define CATCH_SUCCEED( ... ) (void)(0)
  9727. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  9728. // "BDD-style" convenience wrappers
  9729. #define CATCH_SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  9730. #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 )
  9731. #define CATCH_GIVEN( desc )
  9732. #define CATCH_WHEN( desc )
  9733. #define CATCH_AND_WHEN( desc )
  9734. #define CATCH_THEN( desc )
  9735. #define CATCH_AND_THEN( desc )
  9736. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  9737. #else
  9738. #define REQUIRE( ... ) (void)(0)
  9739. #define REQUIRE_FALSE( ... ) (void)(0)
  9740. #define REQUIRE_THROWS( ... ) (void)(0)
  9741. #define REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  9742. #define REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  9743. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  9744. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  9745. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  9746. #define REQUIRE_NOTHROW( ... ) (void)(0)
  9747. #define CHECK( ... ) (void)(0)
  9748. #define CHECK_FALSE( ... ) (void)(0)
  9749. #define CHECKED_IF( ... ) if (__VA_ARGS__)
  9750. #define CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  9751. #define CHECK_NOFAIL( ... ) (void)(0)
  9752. #define CHECK_THROWS( ... ) (void)(0)
  9753. #define CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  9754. #define CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  9755. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  9756. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  9757. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  9758. #define CHECK_NOTHROW( ... ) (void)(0)
  9759. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  9760. #define CHECK_THAT( arg, matcher ) (void)(0)
  9761. #define REQUIRE_THAT( arg, matcher ) (void)(0)
  9762. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  9763. #define INFO( msg ) (void)(0)
  9764. #define WARN( msg ) (void)(0)
  9765. #define CAPTURE( msg ) (void)(0)
  9766. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  9767. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  9768. #define METHOD_AS_TEST_CASE( method, ... )
  9769. #define REGISTER_TEST_CASE( Function, ... ) (void)(0)
  9770. #define SECTION( ... )
  9771. #define FAIL( ... ) (void)(0)
  9772. #define FAIL_CHECK( ... ) (void)(0)
  9773. #define SUCCEED( ... ) (void)(0)
  9774. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  9775. #endif
  9776. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
  9777. // "BDD-style" convenience wrappers
  9778. #define SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) )
  9779. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className )
  9780. #define GIVEN( desc )
  9781. #define WHEN( desc )
  9782. #define AND_WHEN( desc )
  9783. #define THEN( desc )
  9784. #define AND_THEN( desc )
  9785. using Catch::Detail::Approx;
  9786. #endif
  9787. // start catch_reenable_warnings.h
  9788. #ifdef __clang__
  9789. # ifdef __ICC // icpc defines the __clang__ macro
  9790. # pragma warning(pop)
  9791. # else
  9792. # pragma clang diagnostic pop
  9793. # endif
  9794. #elif defined __GNUC__
  9795. # pragma GCC diagnostic pop
  9796. #endif
  9797. // end catch_reenable_warnings.h
  9798. // end catch.hpp
  9799. #endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED